authorgravatar for datamanrb@gmail.comdata-man <datamanrb@gmail.com> 2019-12-14 14:23:42+05:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-02-13 16:12:54-05:00
log948a463cf1644ab6ceb0b9128b4d2ddbcf09d6b1
treeceaccf872731601c53039f7c5baff52e0e335c6a
parent1675d4f82b94b4db0272aff483760cd526963a4c
signaturelock-open Commit is signed but in an unrecognized format.

fmt: vector formatting


1 files changed, 30 insertions(+), 1 deletions(-)

lib/std/fmt.zig+30-1
......@@ -74,7 +74,7 @@ fn peekIsAlign(comptime fmt: []const u8) bool {
7474/// with `?` being the type formatted, this function will be called instead of the default implementation.
7575/// This allows user types to be formatted in a logical manner instead of dumping all fields of the type.
7676///
77/// A user type may be a `struct`, `union` or `enum` type.
77/// A user type may be a `struct`, `vector`, `union` or `enum` type.
7878pub fn format(
7979 context: var,
8080 comptime Errors: type,
......@@ -474,6 +474,18 @@ pub fn formatType(
474474 });
475475 return formatType(@as(Slice, &value), fmt, options, context, Errors, output, max_depth);
476476 },
477 .Vector => {
478 const len = @typeInfo(T).Vector.len;
479 try output(context, "{ ");
480 var i: usize = 0;
481 while (i < len) : (i += 1) {
482 try formatValue(value[i], fmt, options, context, Errors, output);
483 if (i < len - 1) {
484 try output(context, ", ");
485 }
486 }
487 try output(context, " }");
488 },
477489 .Fn => {
478490 return format(context, Errors, output, "{}@{x}", .{ @typeName(T), @ptrToInt(value) });
479491 },
......@@ -500,6 +512,7 @@ fn formatValue(
500512 switch (@typeId(T)) {
501513 .Float => return formatFloatValue(value, fmt, options, context, Errors, output),
502514 .Int, .ComptimeInt => return formatIntValue(value, fmt, options, context, Errors, output),
515 .Bool => return output(context, if (value) "true" else "false"),
503516 else => comptime unreachable,
504517 }
505518}
......@@ -1713,3 +1726,19 @@ test "positional with specifier" {
17131726test "positional/alignment/width/precision" {
17141727 try testFmt("10.0", "{0d: >3.1}", .{@as(f64, 9.999)});
17151728}
1729
1730test "vector" {
1731 if (builtin.arch == .mipsel) return error.SkipZigTest;
1732
1733 const vbool: @Vector(4, bool) = [_]bool{ true, false, true, false };
1734 const vi64: @Vector(4, i64) = [_]i64{ -2, -1, 0, 1 };
1735 const vu64: @Vector(4, u64) = [_]u64{ 1000, 2000, 3000, 4000 };
1736
1737 try testFmt("{ true, false, true, false }", "{}", .{vbool});
1738 try testFmt("{ -2, -1, 0, 1 }", "{}", .{vi64});
1739 try testFmt("{ - 2, - 1, + 0, + 1 }", "{d:5}", .{vi64});
1740 try testFmt("{ 1000, 2000, 3000, 4000 }", "{}", .{vu64});
1741 try testFmt("{ 3e8, 7d0, bb8, fa0 }", "{x}", .{vu64});
1742 try testFmt("{ 1kB, 2kB, 3kB, 4kB }", "{B}", .{vu64});
1743 try testFmt("{ 1000B, 1.953125KiB, 2.9296875KiB, 3.90625KiB }", "{Bi}", .{vu64});
1744}