Skip to content

std.ascii: make toLower toUpper branchless #21369

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 3 commits into from
Sep 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 4 additions & 10 deletions lib/std/ascii.zig
Original file line number Diff line number Diff line change
Expand Up @@ -182,20 +182,14 @@ pub const isASCII = isAscii;

/// Uppercases the character and returns it as-is if already uppercase or not a letter.
pub fn toUpper(c: u8) u8 {
if (isLower(c)) {
return c & 0b11011111;
} else {
return c;
}
const mask = @as(u8, @intFromBool(isLower(c))) << 5;
return c ^ mask;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this be &, rather than ^ (xor)? As is it would toggle the case, which isn't what the function is supposed to do (both by convention and according to doc comment)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

xor looks correct -- you're right that it toggles the case, but only when isLower(c) is true

}

/// Lowercases the character and returns it as-is if already lowercase or not a letter.
pub fn toLower(c: u8) u8 {
if (isUpper(c)) {
return c | 0b00100000;
} else {
return c;
}
const mask = @as(u8, @intFromBool(isUpper(c))) << 5;
return c | mask;
}

test "ASCII character classes" {
Expand Down