From 7ad5181381edc9758b3550a847227c0ca5c82350 Mon Sep 17 00:00:00 2001 From: utox39 Date: Mon, 25 Aug 2025 01:23:52 +0200 Subject: [PATCH] feat(utils): add a utility function to count the codepoints in a string --- src/utils.zig | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/utils.zig b/src/utils.zig index 231bed1..f368d9e 100644 --- a/src/utils.zig +++ b/src/utils.zig @@ -77,3 +77,24 @@ test "getLongestSysInfoStringLen" { try std.testing.expectEqual(strings[3].len, getLongestSysInfoStringLen(strings[0..])); } + +pub fn countCodepoints(str: []const u8) !usize { + var count: usize = 0; + var i: usize = 0; + + while (i < str.len) { + const byte_len = try std.unicode.utf8ByteSequenceLength(str[i]); + if ((i + byte_len > str.len) or (!std.unicode.utf8ValidateSlice(str[i .. i + byte_len]))) return error.InvalidUtf8; + + count += 1; + i += byte_len; + } + + return count; +} + +test "countCodepoints" { + const str = " ████████████████"; + + try std.testing.expectEqual(28, try countCodepoints(str)); +}