| ... | ... | @@ -0,0 +1,24 @@ |
| 1 | const std = @import("std"); |
| 2 | const string = []const u8; |
| 3 | |
| 4 | pub fn fmtByteCountIEC(alloc: *std.mem.Allocator, b: u64) !string { |
| 5 | return try reduceNumber(alloc, b, 1024, "B", "KMGTPEZY"); |
| 6 | } |
| 7 | |
| 8 | pub fn reduceNumber(alloc: *std.mem.Allocator, input: u64, comptime unit: u64, comptime base: string, comptime prefixes: string) !string { |
| 9 | if (input < unit) { |
| 10 | return std.fmt.allocPrint(alloc, "{d} {s}", .{ input, base }); |
| 11 | } |
| 12 | var div = unit; |
| 13 | var exp: usize = 0; |
| 14 | var n = input / unit; |
| 15 | while (n >= unit) : (n /= unit) { |
| 16 | div *= unit; |
| 17 | exp += 1; |
| 18 | } |
| 19 | return try std.fmt.allocPrint(alloc, "{d:.3} {s}{s}", .{ intToFloat(input) / intToFloat(div), prefixes[exp .. exp + 1], base }); |
| 20 | } |
| 21 | |
| 22 | pub fn intToFloat(n: u64) f64 { |
| 23 | return @intToFloat(f64, n); |
| 24 | } |