zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

commit 058bfb254c4c0e1cfb254791f771c88c74f299e8 (tree)
parent 0db33e9c86ff43d3fe7f7f8fb2e29333c2fad2af
Author: Andrew Kelley <superjoe30@gmail.com>
Date:   Tue, 31 Jul 2018 11:34:42 -0400

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

closes #1285

Diffstat:
Mstd/fmt/index.zig | 34++++++++++++++++++++++++++++++++++
1 file changed, 34 insertions(+), 0 deletions(-)

diff --git a/std/fmt/index.zig b/std/fmt/index.zig @@ -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");