authorgravatar for tgschultz@gmail.comtgschultz <tgschultz@gmail.com> 2018-06-10 11:57:21-05:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-06-10 12:57:21-04:00
log854f90aa3064e8bf7ab62a113de3ff3aafa3e6f6
treeb7ec4317f69a987f654f970c6b9fdbadebc5b09a
parentdc8bda7e0203410132e0689b7561d9e8731176e9

Added C string support to fmt by using "{s}". The format string requirement is for saftey. (#1092)


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

std/fmt/index.zig+13-1
...@@ -161,6 +161,14 @@ pub fn formatType(...@@ -161,6 +161,14 @@ pub fn formatType(
161 else => return format(context, Errors, output, "{}@{x}", @typeName(T.Child), @ptrToInt(value)),161 else => return format(context, Errors, output, "{}@{x}", @typeName(T.Child), @ptrToInt(value)),
162 },162 },
163 builtin.TypeInfo.Pointer.Size.Many => {163 builtin.TypeInfo.Pointer.Size.Many => {
164 if (ptr_info.child == u8) {
165 //This is a bit of a hack, but it made more sense to
166 // do this check here than have formatText do it
167 if (fmt[0] == 's') {
168 const len = std.cstr.len(value);
169 return formatText(value[0..len], fmt, context, Errors, output);
170 }
171 }
164 return format(context, Errors, output, "{}@{x}", @typeName(T.Child), @ptrToInt(value));172 return format(context, Errors, output, "{}@{x}", @typeName(T.Child), @ptrToInt(value));
165 },173 },
166 builtin.TypeInfo.Pointer.Size.Slice => {174 builtin.TypeInfo.Pointer.Size.Slice => {
...@@ -300,7 +308,7 @@ pub fn formatBuf(...@@ -300,7 +308,7 @@ pub fn formatBuf(
300 var leftover_padding = if (width > buf.len) (width - buf.len) else return;308 var leftover_padding = if (width > buf.len) (width - buf.len) else return;
301 const pad_byte: u8 = ' ';309 const pad_byte: u8 = ' ';
302 while (leftover_padding > 0) : (leftover_padding -= 1) {310 while (leftover_padding > 0) : (leftover_padding -= 1) {
303 try output(context, (&pad_byte)[0..1]);311 try output(context, (*[1]u8)(&pad_byte)[0..1]);
304 }312 }
305}313}
306314
...@@ -841,6 +849,10 @@ test "fmt.format" {...@@ -841,6 +849,10 @@ test "fmt.format" {
841 const value: u8 = 'a';849 const value: u8 = 'a';
842 try testFmt("u8: a\n", "u8: {c}\n", value);850 try testFmt("u8: a\n", "u8: {c}\n", value);
843 }851 }
852 try testFmt("buf: Test \n", "buf: {s5}\n", "Test");
853 try testFmt("buf: Test\n Other text", "buf: {s}\n Other text", "Test");
854 try testFmt("cstr: Test C\n", "cstr: {s}\n", c"Test C");
855 try testFmt("cstr: Test C \n", "cstr: {s10}\n", c"Test C");
844 try testFmt("file size: 63MiB\n", "file size: {Bi}\n", usize(63 * 1024 * 1024));856 try testFmt("file size: 63MiB\n", "file size: {Bi}\n", usize(63 * 1024 * 1024));
845 try testFmt("file size: 66.06MB\n", "file size: {B2}\n", usize(63 * 1024 * 1024));857 try testFmt("file size: 66.06MB\n", "file size: {B2}\n", usize(63 * 1024 * 1024));
846 {858 {