Skip to content

Commit

Permalink
std.fmt.format: add '*' for formatting things as pointers
Browse files Browse the repository at this point in the history
closes #1285
  • Loading branch information
andrewrk committed Jul 31, 2018
1 parent 0db33e9 commit 058bfb2
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions std/fmt/index.zig
Expand Up @@ -18,6 +18,7 @@ pub fn format(context: var, comptime Errors: type, output: fn (@typeOf(context),
OpenBrace,
CloseBrace,
FormatString,
Pointer,
};

comptime var start_index = 0;
Expand Down Expand Up @@ -54,6 +55,7 @@ pub fn format(context: var, comptime Errors: type, output: fn (@typeOf(context),
state = State.Start;
start_index = i + 1;
},
'*' => state = State.Pointer,
else => {
state = State.FormatString;
},
Expand All @@ -75,6 +77,17 @@ pub fn format(context: var, comptime Errors: type, output: fn (@typeOf(context),
},
else => {},
},
State.Pointer => switch (c) {
'}' => {
try output(context, @typeName(@typeOf(args[next_arg]).Child));
try output(context, "@");
try formatInt(@ptrToInt(args[next_arg]), 16, false, 0, context, Errors, output);
next_arg += 1;
state = State.Start;
start_index = i + 1;
},
else => @compileError("Unexpected format character after '*'"),
},
}
}
comptime {
Expand Down Expand Up @@ -861,6 +874,27 @@ test "fmt.format" {
const value: u8 = 'a';
try testFmt("u8: a\n", "u8: {c}\n", value);
}
{
const value: [3]u8 = "abc";
try testFmt("array: abc\n", "array: {}\n", value);
try testFmt("array: abc\n", "array: {}\n", &value);

var buf: [100]u8 = undefined;
try testFmt(
try bufPrint(buf[0..], "array: [3]u8@{x}\n", @ptrToInt(&value)),
"array: {*}\n",
&value,
);
}
{
const value: []const u8 = "abc";
try testFmt("slice: abc\n", "slice: {}\n", value);
}
{
const value = @intToPtr(*i32, 0xdeadbeef);
try testFmt("pointer: i32@deadbeef\n", "pointer: {}\n", value);
try testFmt("pointer: i32@deadbeef\n", "pointer: {*}\n", value);
}
try testFmt("buf: Test \n", "buf: {s5}\n", "Test");
try testFmt("buf: Test\n Other text", "buf: {s}\n Other text", "Test");
try testFmt("cstr: Test C\n", "cstr: {s}\n", c"Test C");
Expand Down

0 comments on commit 058bfb2

Please sign in to comment.