cs-codex-dist-tests/Framework/Utils/ByteSize.cs

119 lines
2.8 KiB
C#
Raw Permalink Normal View History

2023-09-08 07:39:56 +00:00
namespace Utils
2023-04-12 11:53:55 +00:00
{
public class ByteSize
{
2024-03-26 13:07:06 +00:00
public static readonly ByteSize Zero = new ByteSize(0);
public const double DefaultSecondsPerMB = 10.0;
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);
}
2023-09-08 07:39:56 +00:00
public ByteSize Multiply(double factor)
{
double bytes = SizeInBytes;
double result = Math.Round(bytes * factor);
return new ByteSize(Convert.ToInt64(result));
}
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()
{
return Formatter.FormatByteSize(SizeInBytes);
2023-04-19 07:57:37 +00:00
}
public TimeSpan ToTimeSpan(double secsPerMB = DefaultSecondsPerMB)
{
var filesizeInMb = SizeInBytes / (1024 * 1024);
return TimeSpan.FromSeconds(filesizeInMb * secsPerMB);
}
2023-04-12 11:53:55 +00:00
}
2023-12-06 08:59:45 +00:00
public class BytesPerSecond : ByteSize
{
public BytesPerSecond(long sizeInBytes) : base(sizeInBytes)
{
}
2023-12-06 09:50:02 +00:00
public override string ToString()
{
return base.ToString() + "/s";
}
2023-12-06 08:59:45 +00:00
}
public static class ByteSizeIntExtensions
2023-04-12 11:53:55 +00:00
{
private const long Kilo = 1024;
2023-08-08 08:45:16 +00:00
public static ByteSize Bytes(this long i)
{
return new ByteSize(i);
}
2023-04-12 11:53:55 +00:00
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();
}
2023-08-08 08:45:16 +00:00
public static ByteSize Bytes(this int i)
{
return new ByteSize(i);
}
2023-04-12 11:53:55 +00:00
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();
}
2023-04-12 11:53:55 +00:00
}
}