authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-07-31 11:34:42-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-07-31 11:36:57-04:00
log058bfb254c4c0e1cfb254791f771c88c74f299e8
tree9d94b8c4edd193478ada30f2e5a07efb47e430f3
parent0db33e9c86ff43d3fe7f7f8fb2e29333c2fad2af

std.fmt.format: add '*' for formatting things as pointers

closes #1285

1 files changed, 34 insertions(+), 0 deletions(-)

std/fmt/index.zig+34
......@@ -18,6 +18,7 @@ pub fn format(context: var, comptime Errors: type, output: fn (@typeOf(context),
1818 OpenBrace,
1919 CloseBrace,
2020 FormatString,
21 Pointer,
2122 };
2223
2324 comptime var start_index = 0;
......@@ -54,6 +55,7 @@ pub fn format(context: var, comptime Errors: type, output: fn (@typeOf(context),
5455 state = State.Start;
5556 start_index = i + 1;
5657 },
58 '*' => state = State.Pointer,
5759 else => {
5860 state = State.FormatString;
5961 },
......@@ -75,6 +77,17 @@ pub fn format(context: var, comptime Errors: type, output: fn (@typeOf(context),
7577 },
7678 else => {},
7779 },
80 State.Pointer => switch (c) {
81 '}' => {
82 try output(context, @typeName(@typeOf(args[next_arg]).Child));
83 try output(context, "@");
84 try formatInt(@ptrToInt(args[next_arg]), 16, false, 0, context, Errors, output);
85 next_arg += 1;
86 state = State.Start;
87 start_index = i + 1;
88 },
89 else => @compileError("Unexpected format character after '*'"),
90 },
7891 }
7992 }
8093 comptime {
......@@ -861,6 +874,27 @@ test "fmt.format" {
861874 const value: u8 = 'a';
862875 try testFmt("u8: a\n", "u8: {c}\n", value);
863876 }
877 {
878 const value: [3]u8 = "abc";
879 try testFmt("array: abc\n", "array: {}\n", value);
880 try testFmt("array: abc\n", "array: {}\n", &value);
881
882 var buf: [100]u8 = undefined;
883 try testFmt(
884 try bufPrint(buf[0..], "array: [3]u8@{x}\n", @ptrToInt(&value)),
885 "array: {*}\n",
886 &value,
887 );
888 }
889 {
890 const value: []const u8 = "abc";
891 try testFmt("slice: abc\n", "slice: {}\n", value);
892 }
893 {
894 const value = @intToPtr(*i32, 0xdeadbeef);
895 try testFmt("pointer: i32@deadbeef\n", "pointer: {}\n", value);
896 try testFmt("pointer: i32@deadbeef\n", "pointer: {*}\n", value);
897 }
864898 try testFmt("buf: Test \n", "buf: {s5}\n", "Test");
865899 try testFmt("buf: Test\n Other text", "buf: {s}\n Other text", "Test");
866900 try testFmt("cstr: Test C\n", "cstr: {s}\n", c"Test C");