cs-codex-dist-tests/DistTestCore/ByteSize.cs

85 lines
2.1 KiB
C#
Raw Normal View History

2023-04-12 11:53:55 +00:00
namespace DistTestCore
{
public class ByteSize
{
2023-06-06 14:10:30 +00:00
private static readonly string[] sizeSuffixes = { "B", "KB", "MB", "GB", "TB", "PB", "EB" };
2023-04-12 11:53:55 +00:00
public ByteSize(long sizeInBytes)
{
2023-06-06 14:10:30 +00:00
if (sizeInBytes < 0) throw new ArgumentException("Cannot create ByteSize object with size less than 0. Was: " + sizeInBytes);
2023-04-12 11:53:55 +00:00
SizeInBytes = sizeInBytes;
}
public long SizeInBytes { get; }
2023-04-19 07:57:37 +00:00
public long ToMB()
{
return SizeInBytes / (1024 * 1024);
}
public override bool Equals(object? obj)
{
return obj is ByteSize size && SizeInBytes == size.SizeInBytes;
}
public override int GetHashCode()
{
return HashCode.Combine(SizeInBytes);
}
2023-04-19 07:57:37 +00:00
public override string ToString()
{
2023-06-06 14:10:30 +00:00
if (SizeInBytes == 0) return "0" + sizeSuffixes[0];
var sizeOrder = Convert.ToInt32(Math.Floor(Math.Log(SizeInBytes, 1024)));
var digit = Math.Round(SizeInBytes / Math.Pow(1024, sizeOrder), 1);
return digit.ToString() + sizeSuffixes[sizeOrder];
2023-04-19 07:57:37 +00:00
}
2023-04-12 11:53:55 +00:00
}
public static class ByteSizeIntExtensions
2023-04-12 11:53:55 +00:00
{
private const long Kilo = 1024;
public static ByteSize KB(this long i)
{
return new ByteSize(i * Kilo);
}
public static ByteSize MB(this long i)
{
return (i * Kilo).KB();
}
public static ByteSize GB(this long i)
{
return (i * Kilo).MB();
}
public static ByteSize TB(this long i)
{
return (i * Kilo).GB();
}
public static ByteSize KB(this int i)
{
return Convert.ToInt64(i).KB();
}
public static ByteSize MB(this int i)
{
return Convert.ToInt64(i).MB();
}
public static ByteSize GB(this int i)
{
return Convert.ToInt64(i).GB();
}
public static ByteSize TB(this int i)
{
return Convert.ToInt64(i).TB();
}
}
}