2020-12-29 13:35:37 +01:00
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using zero.Core.Entities;
|
|
|
|
|
|
|
|
|
|
namespace zero.Core.Extensions
|
2020-11-25 16:04:00 +01:00
|
|
|
{
|
|
|
|
|
public static class NumberExtensions
|
|
|
|
|
{
|
2020-12-29 13:35:37 +01:00
|
|
|
static Dictionary<FileSizeNotation, string[]> FileSizeUnits = new()
|
|
|
|
|
{
|
|
|
|
|
{ FileSizeNotation.SI, new string[] { "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" } },
|
|
|
|
|
{ FileSizeNotation.IEC, new string[] { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB" } },
|
|
|
|
|
{ FileSizeNotation.JEDEC, new string[] { "B", "KB", "MB", "GB" } }
|
|
|
|
|
};
|
|
|
|
|
|
2020-11-25 16:04:00 +01:00
|
|
|
public static int Limit(this int input, int min, int max)
|
|
|
|
|
{
|
|
|
|
|
if (input < min)
|
|
|
|
|
{
|
|
|
|
|
return min;
|
|
|
|
|
}
|
|
|
|
|
if (input > max)
|
|
|
|
|
{
|
|
|
|
|
return max;
|
|
|
|
|
}
|
|
|
|
|
return input;
|
|
|
|
|
}
|
2020-12-29 13:35:37 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
public static string GetFileSize(this long sizeInBytes, FileSizeNotation notation = FileSizeNotation.JEDEC)
|
|
|
|
|
{
|
|
|
|
|
if (!FileSizeUnits.ContainsKey(notation))
|
|
|
|
|
{
|
|
|
|
|
throw new NotImplementedException($"The notation {notation} has no implementation for generating human-readable file sizes");
|
|
|
|
|
}
|
|
|
|
|
|
2020-12-30 15:05:59 +01:00
|
|
|
int power = notation == FileSizeNotation.SI ? 1000 : 1024;
|
|
|
|
|
|
2020-12-29 13:35:37 +01:00
|
|
|
string[] units = FileSizeUnits[notation];
|
|
|
|
|
|
|
|
|
|
int order = 0;
|
|
|
|
|
|
2020-12-30 15:05:59 +01:00
|
|
|
while (sizeInBytes >= power && order + 1 < units.Length)
|
2020-12-29 13:35:37 +01:00
|
|
|
{
|
|
|
|
|
order++;
|
2020-12-30 15:05:59 +01:00
|
|
|
sizeInBytes = sizeInBytes / power;
|
2020-12-29 13:35:37 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return String.Format("{0:0.##} {1}", sizeInBytes, units[order]);
|
|
|
|
|
}
|
2020-11-25 16:04:00 +01:00
|
|
|
}
|
|
|
|
|
}
|