Add %q for runes in fmt

This commit is contained in:
gingerBill
2020-11-18 23:40:54 +00:00
parent a39921aa6a
commit fef5172278
2 changed files with 18 additions and 0 deletions

View File

@@ -776,6 +776,8 @@ fmt_rune :: proc(fi: ^Info, r: rune, verb: rune) {
switch verb {
case 'c', 'r', 'v':
strings.write_rune(fi.buf, r);
case 'q':
strings.write_quoted_rune(fi.buf, r);
case:
fmt_int(fi, u64(r), false, 32, verb);
}

View File

@@ -131,6 +131,22 @@ write_rune :: proc(b: ^Builder, r: rune) -> int {
return n;
}
write_quoted_rune :: proc(b: ^Builder, r: rune) -> (n: int) {
quote := byte('\'');
n += write_byte(b, quote);
buf, width := utf8.encode_rune(r);
if width == 1 && r == utf8.RUNE_ERROR {
n += write_byte(b, '\\');
n += write_byte(b, 'x');
n += write_byte(b, DIGITS_LOWER[buf[0]>>4]);
n += write_byte(b, DIGITS_LOWER[buf[0]&0xf]);
} else {
n += write_escaped_rune(b, r, quote);
}
n += write_byte(b, quote);
return;
}
write_string :: proc(b: ^Builder, s: string) -> (n: int) {
return write_bytes(b, transmute([]byte)s);
}