1
0
mirror of https://github.com/chylex/Discord-History-Tracker.git synced 2024-12-04 21:42:47 +01:00
Discord-History-Tracker/app/Desktop/Common/BytesValueConverter.cs

54 lines
1.4 KiB
C#
Raw Normal View History

2022-05-23 00:20:52 +02:00
using System;
using System.Globalization;
using Avalonia.Data.Converters;
namespace DHT.Desktop.Common;
sealed class BytesValueConverter : IValueConverter {
private sealed class Unit {
private readonly string label;
private readonly string numberFormat;
public Unit(string label, int decimalPlaces) {
this.label = label;
this.numberFormat = "{0:n" + decimalPlaces + "}";
2022-05-23 00:20:52 +02:00
}
public string Format(double size) {
return string.Format(Program.Culture, numberFormat, size) + " " + label;
2022-05-23 00:20:52 +02:00
}
}
2023-12-31 19:12:06 +01:00
private static readonly Unit[] Units = [
new Unit("B", decimalPlaces: 0),
new Unit("kB", decimalPlaces: 0),
new Unit("MB", decimalPlaces: 1),
new Unit("GB", decimalPlaces: 1),
new Unit("TB", decimalPlaces: 1)
];
private const int Scale = 1000;
2022-05-23 00:20:52 +02:00
public static string Convert(ulong size) {
int power = size == 0L ? 0 : (int) Math.Log(size, Scale);
int unit = power >= Units.Length ? Units.Length - 1 : power;
return Units[unit].Format(unit == 0 ? size : size / Math.Pow(Scale, unit));
}
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) {
if (value is long size and >= 0L) {
return Convert((ulong) size);
}
else if (value is ulong usize) {
return Convert(usize);
2022-05-23 00:20:52 +02:00
}
else {
return "-";
}
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) {
throw new NotSupportedException();
2022-05-23 00:20:52 +02:00
}
}