Files
ucvl-zonghengjia-open-source/windows/SpeedDisplay.cs
T

41 lines
1.5 KiB
C#
Raw Normal View History

using System.Globalization;
namespace UCVL.VPNPlus;
// One presentation policy for measured byte rates. KB/s is the smallest unit;
// low and zero readings stay truthful rather than being raised to 0.1 KB/s.
internal static class SpeedDisplay
{
private static readonly string[] Units = ["KB/s", "MB/s", "GB/s", "TB/s"];
internal static string Format(double? bytesPerSecond)
{
var (value, unit) = Parts(bytesPerSecond);
return unit.Length == 0 ? value : value + " " + unit;
}
internal static (string ValueText, string UnitText) Parts(double? bytesPerSecond)
{
if (bytesPerSecond is not { } bytes || !double.IsFinite(bytes) || bytes < 0) return ("—", "");
var (divisor, unit) = UnitFor(bytes);
return (Number(bytes / divisor), unit);
}
internal static (double Divisor, string UnitText) UnitFor(double bytesPerSecond)
{
var divisor = 1024d;
var unit = 0;
// Promote a value that would otherwise display as 1024.0 in its old
// unit, so rounding and exact unit boundaries use the same convention.
while (unit < Units.Length - 1 && Math.Round(bytesPerSecond / divisor, 1, MidpointRounding.AwayFromZero) >= 1024)
{ divisor *= 1024; unit++; }
return (divisor, Units[unit]);
}
internal static string Number(double value)
{
var rounded = Math.Round(value, 1, MidpointRounding.AwayFromZero);
return (rounded == 0 ? 0 : rounded).ToString("0.0", CultureInfo.InvariantCulture);
}
}