authorgravatar for datamanrb@gmail.comdata-man <datamanrb@gmail.com> 2019-12-22 15:38:27+05:00
committergravatar for thatlemon@gmail.comLemonBoy <thatlemon@gmail.com> 2020-11-05 16:10:33+01:00
log678ecc94ca8584e8fef9bfae4ed5fa97c62c58e1
treec92c68995a7a6f0fcf7e21cb9b45c4018d093b08
parent17837affd22a6055c65a14252fa38610fdeabc3a

Add 'u' specifier to std.format


1 files changed, 27 insertions(+), 0 deletions(-)

lib/std/fmt.zig+27
......@@ -76,6 +76,7 @@ fn peekIsAlign(comptime fmt: []const u8) bool {
7676/// - `b`: output integer value in binary notation
7777/// - `o`: output integer value in octal notation
7878/// - `c`: output integer as an ASCII character. Integer type must have 8 bits at max.
79/// - `u`: output integer as an UTF-8 sequence. Integer type must have 32 bits at max.
7980/// - `*`: output the address of the value instead of the value itself.
8081///
8182/// If a formatted user type contains a function of the type
......@@ -555,6 +556,12 @@ pub fn formatIntValue(
555556 } else {
556557 @compileError("Cannot escape character with more than 8 bits");
557558 }
559 } else if (comptime std.mem.eql(u8, fmt, "u")) {
560 if (@TypeOf(int_value).bit_count <= 32) {
561 return formatUtf8Codepoint(@as(u32, int_value), options, context, Errors, output);
562 } else {
563 @compileError("Cannot print integer that is larger than 32 bits as an UTF-8 sequence");
564 }
558565 } else if (comptime std.mem.eql(u8, fmt, "b")) {
559566 radix = 2;
560567 uppercase = false;
......@@ -641,6 +648,18 @@ pub fn formatAsciiChar(
641648 return writer.writeAll(@as(*const [1]u8, &c));
642649}
643650
651pub fn formatUtf8Codepoint(
652 c: u32,
653 options: FormatOptions,
654 context: anytype,
655 comptime Errors: type,
656 output: fn (@TypeOf(context), []const u8) Errors!void,
657) Errors!void {
658 var buf: [4]u8 = undefined;
659 const len = std.unicode.utf8Encode(c, buf[0..]) catch unreachable;
660 return output(context, @as(*const [4]u8, &buf)[0..len]);
661}
662
644663pub fn formatBuf(
645664 buf: []const u8,
646665 options: FormatOptions,
......@@ -1385,6 +1404,14 @@ test "int.specifier" {
13851404 const value: u16 = 0o1234;
13861405 try testFmt("u16: 0o1234\n", "u16: 0o{o}\n", .{value});
13871406 }
1407 {
1408 const value: u8 = 'a';
1409 try testFmt("UTF-8: a\n", "UTF-8: {u}\n", .{value});
1410 }
1411 {
1412 const value: u32 = 0x1F310;
1413 try testFmt("UTF-8: 🌐\n", "UTF-8: {u}\n", .{value});
1414 }
13881415}
13891416
13901417test "int.padded" {