From 4eb86edf5dea66edebdc41ab2cccf3bf30295520 Mon Sep 17 00:00:00 2001 From: Jose Colon Rodriguez Date: Sun, 18 Feb 2024 17:04:22 -0400 Subject: center, padLeft, padRight, and wrap --- src/ascii.zig | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/ascii.zig (limited to 'src/ascii.zig') diff --git a/src/ascii.zig b/src/ascii.zig new file mode 100644 index 0000000..6c28f25 --- /dev/null +++ b/src/ascii.zig @@ -0,0 +1,33 @@ +const std = @import("std"); +const simd = std.simd; +const testing = std.testing; + +/// Returns true if `str` only contains ASCII bytes. Uses SIMD if possible. +pub fn isAsciiOnly(str: []const u8) bool { + const vec_len = simd.suggestVectorLength(u8) orelse return for (str) |b| { + if (b > 127) break false; + } else true; + + const Vec = @Vector(vec_len, u8); + var remaining = str; + + while (true) { + if (remaining.len < vec_len) return for (remaining) |b| { + if (b > 127) break false; + } else true; + + const v1 = remaining[0..vec_len].*; + const v2: Vec = @splat(127); + if (@reduce(.Or, v1 > v2)) return false; + remaining = remaining[vec_len..]; + } + + return true; +} + +test "isAsciiOnly" { + const ascii_only = "Hello, World! 0123456789 !@#$%^&*()_-=+"; + try testing.expect(isAsciiOnly(ascii_only)); + const not_ascii_only = "Héllo, World! 0123456789 !@#$%^&*()_-=+"; + try testing.expect(!isAsciiOnly(not_ascii_only)); +} -- cgit v1.2.3