-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
std.fmt meets UTF-8 #6390
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
std.fmt meets UTF-8 #6390
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
678ecc9
Add 'u' specifier to std.format
data-man 2cce230
Update the API and add add error-recovery path
LemonBoy 6c4efab
std: Introduce std.unicode.utf8CountCodepoints
LemonBoy 44533f1
std: Introduce std.unicode.utf8ValidCodepoint
LemonBoy 675de8d
Clean up the unicode codepoint formatter a bit
LemonBoy 0316ac9
Make std.formatBuf UTF-8 aware
LemonBoy 1982e0c
Fix typo in documentation
LemonBoy 3a1f515
Address review comments
LemonBoy 53c1624
std: Make utf8CountCodepoints much faster
LemonBoy 60638f0
Nicer code for the error code path
LemonBoy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -23,11 +23,12 @@ pub fn utf8CodepointSequenceLength(c: u21) !u3 { | |
/// returns a number 1-4 indicating the total length of the codepoint in bytes. | ||
/// If this byte does not match the form of a UTF-8 start byte, returns Utf8InvalidStartByte. | ||
pub fn utf8ByteSequenceLength(first_byte: u8) !u3 { | ||
return switch (@clz(u8, ~first_byte)) { | ||
0 => 1, | ||
2 => 2, | ||
3 => 3, | ||
4 => 4, | ||
// The switch is optimized much better than a "smart" approach using @clz | ||
return switch (first_byte) { | ||
0b0000_0000 ... 0b0111_1111 => 1, | ||
0b1100_0000 ... 0b1101_1111 => 2, | ||
0b1110_0000 ... 0b1110_1111 => 3, | ||
0b1111_0000 ... 0b1111_0111 => 4, | ||
else => error.Utf8InvalidStartByte, | ||
}; | ||
} | ||
|
@@ -153,6 +154,50 @@ pub fn utf8Decode4(bytes: []const u8) Utf8Decode4Error!u21 { | |
return value; | ||
} | ||
|
||
/// Returns true if the given unicode codepoint can be encoded in UTF-8. | ||
pub fn utf8ValidCodepoint(value: u21) bool { | ||
return switch (value) { | ||
0xD800 ... 0xDFFF => false, // Surrogates range | ||
0x110000 ... 0x1FFFFF => false, // Above the maximum codepoint value | ||
else => true, | ||
}; | ||
} | ||
|
||
/// Returns the length of a supplied UTF-8 string literal in terms of unicode | ||
/// codepoints. | ||
/// Asserts that the data is valid UTF-8. | ||
pub fn utf8CountCodepoints(s: []const u8) !usize { | ||
var len: usize = 0; | ||
|
||
const N = @sizeOf(usize); | ||
const MASK = 0x80 * (std.math.maxInt(usize) / 0xff); | ||
|
||
var i: usize = 0; | ||
while (i < s.len) { | ||
// Fast path for ASCII sequences | ||
while (i + N <= s.len) : (i += N) { | ||
const v = mem.readIntNative(usize, s[i..][0..N]); | ||
if (v & MASK != 0) break; | ||
len += N; | ||
} | ||
|
||
if (i < s.len) { | ||
const n = try utf8ByteSequenceLength(s[i]); | ||
if (i + n > s.len) return error.TruncatedInput; | ||
|
||
switch (n) { | ||
1 => {}, // ASCII, no validation needed | ||
else => _ = try utf8Decode(s[i .. i + n]), | ||
} | ||
|
||
i += n; | ||
len += 1; | ||
} | ||
} | ||
|
||
return len; | ||
} | ||
|
||
pub fn utf8ValidateSlice(s: []const u8) bool { | ||
var i: usize = 0; | ||
while (i < s.len) { | ||
|
@@ -687,7 +732,6 @@ pub fn utf8ToUtf16LeStringLiteral(comptime utf8: []const u8) *const [calcUtf16Le | |
} | ||
} | ||
|
||
/// Returns length of a supplied UTF-8 string literal. Asserts that the data is valid UTF-8. | ||
fn calcUtf16LeLen(utf8: []const u8) usize { | ||
var src_i: usize = 0; | ||
var dest_len: usize = 0; | ||
|
@@ -757,3 +801,31 @@ test "utf8ToUtf16LeStringLiteral" { | |
testing.expect(utf16[2] == 0); | ||
} | ||
} | ||
|
||
fn testUtf8CountCodepoints() !void { | ||
testing.expectEqual(@as(usize, 10), try utf8CountCodepoints("abcdefghij")); | ||
testing.expectEqual(@as(usize, 10), try utf8CountCodepoints("äåéëþüúíóö")); | ||
testing.expectEqual(@as(usize, 5), try utf8CountCodepoints("こんにちは")); | ||
// testing.expectError(error.Utf8EncodesSurrogateHalf, utf8CountCodepoints("\xED\xA0\x80")); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Commented out code? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. My bad, I'll add it back |
||
} | ||
|
||
test "utf8 count codepoints" { | ||
try testUtf8CountCodepoints(); | ||
comptime testUtf8CountCodepoints() catch unreachable; | ||
} | ||
|
||
fn testUtf8ValidCodepoint() !void { | ||
testing.expect(utf8ValidCodepoint('e')); | ||
testing.expect(utf8ValidCodepoint('ë')); | ||
testing.expect(utf8ValidCodepoint('は')); | ||
testing.expect(utf8ValidCodepoint(0xe000)); | ||
testing.expect(utf8ValidCodepoint(0x10ffff)); | ||
testing.expect(!utf8ValidCodepoint(0xd800)); | ||
testing.expect(!utf8ValidCodepoint(0xdfff)); | ||
testing.expect(!utf8ValidCodepoint(0x110000)); | ||
} | ||
|
||
test "utf8 valid codepoint" { | ||
try testUtf8ValidCodepoint(); | ||
comptime testUtf8ValidCodepoint() catch unreachable; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This won't decide the string width! A codepoint is not a single character. Example:
"👩👦👦"
is U+1F469 U+200D U+1F466 U+200D U+1F466, which has 5 codepoints, but only width 1You can look that up with this tool: https://cryptii.com/pipes/unicode-lookup
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That's a good approximation of the string width, the same approximation used by other PLs.
Entering the
wcwidth
territory and dealing with tables needing constant updates or mismatches between the producer (Zig, in this case) and the consumer (the terminal emulator/editor/browser) is definitely not something that I'd rank high on my todo list.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Surely it would be nice if a user could put a table in the root source file and std.unicode apis could use it
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think the best solution is to implement the runtime width specifier (see #1358) and let the user specify the display width, I'm playing with a prototype of this idea and it looks promising.