From d129a60d1c04d9b142a44519cdec15f11d701e74 Mon Sep 17 00:00:00 2001 From: chylex Date: Mon, 23 May 2022 00:20:52 +0200 Subject: [PATCH] Add BytesValueConverter --- app/Desktop/App.axaml | 1 + app/Desktop/Common/BytesValueConverter.cs | 45 +++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 app/Desktop/Common/BytesValueConverter.cs diff --git a/app/Desktop/App.axaml b/app/Desktop/App.axaml index 59a66f9..3665f72 100644 --- a/app/Desktop/App.axaml +++ b/app/Desktop/App.axaml @@ -105,6 +105,7 @@ + 14 0 diff --git a/app/Desktop/Common/BytesValueConverter.cs b/app/Desktop/Common/BytesValueConverter.cs new file mode 100644 index 0000000..e2b1ea6 --- /dev/null +++ b/app/Desktop/Common/BytesValueConverter.cs @@ -0,0 +1,45 @@ +using System; +using System.Globalization; +using Avalonia.Data.Converters; + +namespace DHT.Desktop.Common { + sealed class BytesValueConverter : IValueConverter { + private static readonly string[] Units = { + "B", + "kB", + "MB", + "GB", + "TB" + }; + + private const int Scale = 1000; + + private static string Convert(ulong size) { + int power = size == 0L ? 0 : (int) Math.Log(size, Scale); + int unit = power >= Units.Length ? Units.Length - 1 : power; + if (unit == 0) { + return string.Format(Program.Culture, "{0:n0}", size) + " " + Units[unit]; + } + else { + double humanReadableSize = size / Math.Pow(Scale, unit); + return string.Format(Program.Culture, "{0:n0}", humanReadableSize) + " " + Units[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); + } + else { + return "-"; + } + } + + public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) { + throw new NotSupportedException(); + } + } +}