From 4b99f5978f35e54d4b4f1bfae022f48f193e40fd Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 23 Feb 2017 18:56:10 -0500 Subject: [PATCH] add character format specifier to std.io.OutStream.printf --- std/io.zig | 21 +++++++++++++++++++++ test/run_tests.cpp | 4 ++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/std/io.zig b/std/io.zig index 47e8ba287b..8fc2092fcf 100644 --- a/std/io.zig +++ b/std/io.zig @@ -101,6 +101,7 @@ pub const OutStream = struct { CloseBrace, Integer, IntegerWidth, + Character, }; /// Calls print and then flushes the buffer. @@ -155,6 +156,9 @@ pub const OutStream = struct { width = 0; state = State.Integer; }, + 'c' => { + state = State.Character; + }, else => @compileError("Unknown format character: " ++ []u8{c}), }, State.CloseBrace => switch (c) { @@ -188,6 +192,15 @@ pub const OutStream = struct { '0' ... '9' => {}, else => @compileError("Unexpected character in format string: " ++ []u8{c}), }, + State.Character => switch (c) { + '}' => { + self.printAsciiChar(args[next_arg]); + next_arg += 1; + state = State.Start; + start_index = i + 1; + }, + else => @compileError("Unexpected character in format string: " ++ []u8{c}), + }, } } comptime { @@ -228,6 +241,14 @@ pub const OutStream = struct { self.index += amt_printed; } + pub fn printAsciiChar(self: &OutStream, c: u8) -> %void { + if (self.index + 1 >= self.buffer.len) { + %return self.flush(); + } + self.buffer[self.index] = c; + self.index += 1; + } + pub fn flush(self: &OutStream) -> %void { while (true) { const write_ret = system.write(self.fd, &self.buffer[0], self.index); diff --git a/test/run_tests.cpp b/test/run_tests.cpp index a49cfdbdda..58affc1cce 100644 --- a/test/run_tests.cpp +++ b/test/run_tests.cpp @@ -335,9 +335,9 @@ pub const b_text = a_text; const io = @import("std").io; pub fn main(args: [][]u8) -> %void { - %%io.stdout.printf("Hello, world!\n{d4} {x3}\n", u32(12), u16(0x12)); + %%io.stdout.printf("Hello, world!\n{d4} {x3} {c}\n", u32(12), u16(0x12), u8('a')); } - )SOURCE", "Hello, world!\n0012 012\n"); + )SOURCE", "Hello, world!\n0012 012 a\n"); add_simple_case_libc("number literals", R"SOURCE(