add character format specifier to std.io.OutStream.printf

This commit is contained in:
Andrew Kelley 2017-02-23 18:56:10 -05:00
parent 3075d8aee7
commit 4b99f5978f
2 changed files with 23 additions and 2 deletions

View File

@ -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);

View File

@ -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(