Function printByteSize [src]

Format option precision is ignored when value is less than 1kB

Prototype

pub fn printByteSize( w: *Writer, value: u64, comptime units: ByteSizeUnits, options: std.fmt.Options, ) Error!void

Parameters

w: *Writervalue: u64units: ByteSizeUnitsoptions: std.fmt.Options

Possible Errors

WriteFailed

See the Writer implementation for detailed diagnostics.

Example

test printByteSize { try testing.expectFmt("file size: 42B\n", "file size: {B}\n", .{42}); try testing.expectFmt("file size: 42B\n", "file size: {Bi}\n", .{42}); try testing.expectFmt("file size: 63MB\n", "file size: {B}\n", .{63 * 1000 * 1000}); try testing.expectFmt("file size: 63MiB\n", "file size: {Bi}\n", .{63 * 1024 * 1024}); try testing.expectFmt("file size: 42B\n", "file size: {B:.2}\n", .{42}); try testing.expectFmt("file size: 42B\n", "file size: {B:>9.2}\n", .{42}); try testing.expectFmt("file size: 66.06MB\n", "file size: {B:.2}\n", .{63 * 1024 * 1024}); try testing.expectFmt("file size: 60.08MiB\n", "file size: {Bi:.2}\n", .{63 * 1000 * 1000}); try testing.expectFmt("file size: =66.06MB=\n", "file size: {B:=^9.2}\n", .{63 * 1024 * 1024}); try testing.expectFmt("file size: 66.06MB\n", "file size: {B: >9.2}\n", .{63 * 1024 * 1024}); try testing.expectFmt("file size: 66.06MB \n", "file size: {B: <9.2}\n", .{63 * 1024 * 1024}); try testing.expectFmt("file size: 0.01844674407370955ZB\n", "file size: {B}\n", .{std.math.maxInt(u64)}); }

Source

pub fn printByteSize( w: *Writer, value: u64, comptime units: ByteSizeUnits, options: std.fmt.Options, ) Error!void { if (value == 0) return w.alignBufferOptions("0B", options); // The worst case in terms of space needed is 32 bytes + 3 for the suffix. var buf: [std.fmt.float.min_buffer_size + 3]u8 = undefined; const mags_si = " kMGTPEZY"; const mags_iec = " KMGTPEZY"; const log2 = std.math.log2(value); const base = switch (units) { .decimal => 1000, .binary => 1024, }; const magnitude = switch (units) { .decimal => @min(log2 / comptime std.math.log2(1000), mags_si.len - 1), .binary => @min(log2 / 10, mags_iec.len - 1), }; const new_value = std.math.lossyCast(f64, value) / std.math.pow(f64, std.math.lossyCast(f64, base), std.math.lossyCast(f64, magnitude)); const suffix = switch (units) { .decimal => mags_si[magnitude], .binary => mags_iec[magnitude], }; const s = switch (magnitude) { 0 => buf[0..std.fmt.printInt(&buf, value, 10, .lower, .{})], else => std.fmt.float.render(&buf, new_value, .{ .mode = .decimal, .precision = options.precision }) catch |err| switch (err) { error.BufferTooSmall => unreachable, }, }; var i: usize = s.len; if (suffix == ' ') { buf[i] = 'B'; i += 1; } else switch (units) { .decimal => { buf[i..][0..2].* = [_]u8{ suffix, 'B' }; i += 2; }, .binary => { buf[i..][0..3].* = [_]u8{ suffix, 'i', 'B' }; i += 3; }, } return w.alignBufferOptions(buf[0..i], options); }