| ... | ... | @@ -1,4 +1,5 @@ |
| 1 | 1 | const std = @import("std.zig"); |
| 2 | const io = std.io; |
| 2 | 3 | const math = std.math; |
| 3 | 4 | const assert = std.debug.assert; |
| 4 | 5 | const mem = std.mem; |
| ... | ... | @@ -877,8 +878,11 @@ fn formatSizeImpl(comptime radix: comptime_int) type { |
| 877 | 878 | ) !void { |
| 878 | 879 | _ = fmt; |
| 879 | 880 | if (value == 0) { |
| 880 | | return writer.writeAll("0B"); |
| 881 | return formatBuf("0B", options, writer); |
| 881 | 882 | } |
| 883 | // The worst case in terms of space needed is 32 bytes + 3 for the suffix. |
| 884 | var buf: [35]u8 = undefined; |
| 885 | var bufstream = io.fixedBufferStream(buf[0..]); |
| 882 | 886 | |
| 883 | 887 | const mags_si = " kMGTPEZY"; |
| 884 | 888 | const mags_iec = " KMGTPEZY"; |
| ... | ... | @@ -896,18 +900,20 @@ fn formatSizeImpl(comptime radix: comptime_int) type { |
| 896 | 900 | else => unreachable, |
| 897 | 901 | }; |
| 898 | 902 | |
| 899 | | try formatFloatDecimal(new_value, options, writer); |
| 900 | | |
| 901 | | if (suffix == ' ') { |
| 902 | | return writer.writeAll("B"); |
| 903 | | } |
| 903 | formatFloatDecimal(new_value, options, bufstream.writer()) catch |err| switch (err) { |
| 904 | error.NoSpaceLeft => unreachable, // 35 bytes should be enough |
| 905 | }; |
| 904 | 906 | |
| 905 | | const buf = switch (radix) { |
| 907 | bufstream.writer().writeAll(if (suffix == ' ') |
| 908 | "B" |
| 909 | else switch (radix) { |
| 906 | 910 | 1000 => &[_]u8{ suffix, 'B' }, |
| 907 | 911 | 1024 => &[_]u8{ suffix, 'i', 'B' }, |
| 908 | 912 | else => unreachable, |
| 913 | }) catch |err| switch (err) { |
| 914 | error.NoSpaceLeft => unreachable, |
| 909 | 915 | }; |
| 910 | | return writer.writeAll(buf); |
| 916 | return formatBuf(bufstream.getWritten(), options, writer); |
| 911 | 917 | } |
| 912 | 918 | }; |
| 913 | 919 | } |
| ... | ... | @@ -2155,6 +2161,10 @@ test "filesize" { |
| 2155 | 2161 | try expectFmt("file size: 63MiB\n", "file size: {}\n", .{fmtIntSizeBin(63 * 1024 * 1024)}); |
| 2156 | 2162 | try expectFmt("file size: 66.06MB\n", "file size: {:.2}\n", .{fmtIntSizeDec(63 * 1024 * 1024)}); |
| 2157 | 2163 | try expectFmt("file size: 60.08MiB\n", "file size: {:.2}\n", .{fmtIntSizeBin(63 * 1000 * 1000)}); |
| 2164 | try expectFmt("file size: =66.06MB=\n", "file size: {:=^9.2}\n", .{fmtIntSizeDec(63 * 1024 * 1024)}); |
| 2165 | try expectFmt("file size: 66.06MB\n", "file size: {: >9.2}\n", .{fmtIntSizeDec(63 * 1024 * 1024)}); |
| 2166 | try expectFmt("file size: 66.06MB \n", "file size: {: <9.2}\n", .{fmtIntSizeDec(63 * 1024 * 1024)}); |
| 2167 | try expectFmt("file size: 0.01844674407370955ZB\n", "file size: {}\n", .{fmtIntSizeDec(math.maxInt(u64))}); |
| 2158 | 2168 | } |
| 2159 | 2169 | |
| 2160 | 2170 | test "struct" { |