commit dd05c7c2a081b0621e22983c9e2927d1bb559072
parent 2d510dc987174f1e7ffaa2590e1b4d1f2485e367
Author: Sebastian <sebastian@sebsite.pw>
Date: Sat, 9 Dec 2023 21:13:45 -0500
ascii: add strlower_buf and strupper_buf
Signed-off-by: Sebastian <sebastian@sebsite.pw>
Diffstat:
1 file changed, 24 insertions(+), 10 deletions(-)
diff --git a/ascii/string.ha b/ascii/string.ha
@@ -4,34 +4,48 @@
use encoding::utf8;
use strings;
-// Convert all ASCII uppercase characters in a string to their lowercase
+// Converts all ASCII uppercase characters in a string to their lowercase
// representation, returning a new string. The return value must be freed by the
// caller.
export fn strlower(s: str) str = {
let new: []u8 = alloc([], len(s));
+ return strlower_buf(s, new);
+};
+
+// Converts all ASCII uppercase characters in a string to their lowercase
+// representation, returning a new string. The new string data is stored in the
+// supplied buffer. This function will abort if the buffer's length is too small
+// to fit the entire string.
+export fn strlower_buf(s: str, buf: []u8) str = {
let it = strings::iter(s);
for (true) match (strings::next(&it)) {
+ case void => break;
case let r: rune =>
- static append(new, utf8::encoderune(tolower(r))...);
- case void =>
- break;
+ static append(buf, utf8::encoderune(tolower(r))...);
};
- return strings::fromutf8(new)!;
+ return strings::fromutf8(buf)!;
};
-// Convert all ASCII lowercase characters in a string to their uppercase
+// Converts all ASCII lowercase characters in a string to their uppercase
// representation, returning a new string. The return value must be freed by the
// caller.
export fn strupper(s: str) str = {
let new: []u8 = alloc([], len(s));
+ return strupper_buf(s, new);
+};
+
+// Converts all ASCII lowercase characters in a string to their uppercase
+// representation, returning a new string. The new string data is stored in the
+// supplied buffer. This function will abort if the buffer's length is too small
+// to fit the entire string.
+export fn strupper_buf(s: str, buf: []u8) str = {
let it = strings::iter(s);
for (true) match (strings::next(&it)) {
+ case void => break;
case let r: rune =>
- static append(new, utf8::encoderune(toupper(r))...);
- case void =>
- break;
+ static append(buf, utf8::encoderune(toupper(r))...);
};
- return strings::fromutf8(new)!;
+ return strings::fromutf8(buf)!;
};
// Compares two strings by their sort order, treating all ASCII capital letters