From 8ddce90e62e52244b7f6d1104bb39a55350f0a83 Mon Sep 17 00:00:00 2001 From: CrazyboyQCD <53971641+CrazyboyQCD@users.noreply.github.com> Date: Sat, 14 Sep 2024 08:22:19 +0800 Subject: [PATCH] `std.ascii`: make `toLower` `toUpper` branchless (#21369) Co-authored-by: WX\shixi --- lib/std/ascii.zig | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/lib/std/ascii.zig b/lib/std/ascii.zig index d5b028500f..7b99f6f4cf 100644 --- a/lib/std/ascii.zig +++ b/lib/std/ascii.zig @@ -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; } /// 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" {