commit b5046e746fba5281cc3f3723b28db4215e8595e3 parent 2636348713531f74bab7a0659a80a41c1fe9b32e Author: Sebastian <sebastian@sebsite.pw> Date: Tue, 12 Mar 2024 18:33:54 -0400 types::c: add strnlen Diffstat:
M | types/c/strings.ha | | | 9 | +++++++++ |
1 file changed, 9 insertions(+), 0 deletions(-)
diff --git a/types/c/strings.ha b/types/c/strings.ha @@ -18,6 +18,15 @@ export fn strlen(cstr: *const char) size = { return ln; }; +// Computes the length of a NUL-terminated C string, only looking at the first +// maxlen bytes. The computed length does not include the NUL terminator. +export fn strnlen(cstr: *const char, maxlen: size) size = { + const ptr = cstr: *[*]u8; + let ln = 0z; + for (ln < maxlen && ptr[ln] != 0; ln += 1) void; + return ln; +}; + // Converts a C string to a Hare string in O(n), and does not check if it's // valid UTF-8. export fn tostr_unsafe(cstr: *const char) const str = {