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

closes #1285
This commit is contained in:
Andrew Kelley 2018-07-31 11:34:42 -04:00
parent 0db33e9c86
commit 058bfb254c

View File

@ -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;
@ -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;
},
@ -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 {
@ -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");