authorgravatar for thatlemon@gmail.comLemonBoy <thatlemon@gmail.com> 2020-09-21 15:59:10+02:00
committergravatar for thatlemon@gmail.comLemonBoy <thatlemon@gmail.com> 2020-11-05 16:10:34+01:00
log675de8d6b723aa4be6a51e7f371364799dd7491b
treea4456248cb61028d63cea2581ccd8bbba1c59083
parent44533f10fee130498fb811eabb72e2afdc3c0f56

Clean up the unicode codepoint formatter a bit


1 files changed, 11 insertions(+), 10 deletions(-)

lib/std/fmt.zig+11-10
...@@ -7,6 +7,7 @@ const std = @import("std.zig");...@@ -7,6 +7,7 @@ const std = @import("std.zig");
7const math = std.math;7const math = std.math;
8const assert = std.debug.assert;8const assert = std.debug.assert;
9const mem = std.mem;9const mem = std.mem;
10const unicode = std.unicode;
10const builtin = @import("builtin");11const builtin = @import("builtin");
11const errol = @import("fmt/errol.zig");12const errol = @import("fmt/errol.zig");
12const lossyCast = std.math.lossyCast;13const lossyCast = std.math.lossyCast;
...@@ -653,17 +654,17 @@ pub fn formatUnicodeCodepoint(...@@ -653,17 +654,17 @@ pub fn formatUnicodeCodepoint(
653 options: FormatOptions,654 options: FormatOptions,
654 writer: anytype,655 writer: anytype,
655) !void {656) !void {
656 var buf: [4]u8 = undefined;657 if (unicode.utf8ValidCodepoint(c)) {
658 var buf: [4]u8 = undefined;
659 // The codepoint is surely valid, hence the use of unreachable
660 const len = std.unicode.utf8Encode(@truncate(u21, c), &buf) catch |err| switch (err) {
661 error.Utf8CannotEncodeSurrogateHalf, error.CodepointTooLarge => unreachable,
662 };
663 return formatBuf(buf[0..len], options, writer);
664 }
665
657 // In case of error output the replacement char U+FFFD666 // In case of error output the replacement char U+FFFD
658 const len = std.unicode.utf8Encode(@truncate(u21, c), &buf) catch |err| switch (err) {667 return formatBuf(&[_]u8{ 0xef, 0xbf, 0xbd }, options, writer);
659 error.Utf8CannotEncodeSurrogateHalf => {
660 return writer.writeAll(&[_]u8{ 0xef, 0xbf, 0xbd });
661 },
662 error.CodepointTooLarge => {
663 return writer.writeAll(&[_]u8{ 0xef, 0xbf, 0xbd });
664 },
665 };
666 return writer.writeAll(buf[0..len]);
667}668}
668669
669pub fn formatBuf(670pub fn formatBuf(