commit a20ec460699dc41e5b20b73210f91b8b9e204249
parent 4882b6603c9af2b5f67edeea556196b6a53be9b3
Author: Vlad-Stefan Harbuz <vlad@vladh.net>
Date: Thu, 3 Feb 2022 14:14:10 +0100
strings: add to_cbuf()
Signed-off-by: Vlad-Stefan Harbuz <vlad@vladh.net>
Diffstat:
1 file changed, 15 insertions(+), 13 deletions(-)
diff --git a/strings/cstrings.ha b/strings/cstrings.ha
@@ -40,18 +40,20 @@ export fn fromc(cstr: *const char) const str = {
// Converts a Hare string to a C string. The result is allocated, the caller
// must free it when they're done.
export fn to_c(s: const str) *char = {
- let ptr = rt::malloc(len(s) + 1): nullable *[*]u8;
- let ptr = match (ptr) {
- case null =>
- abort("Out of memory");
- case let p: *[*]u8 =>
- yield p;
- };
- match ((&s: *types::string).data) {
- case null => void;
- case let data: *[*]u8 =>
- yield rt::memcpy(ptr, data, len(s));
+ let slice: []u8 = alloc([0...], len(s) + 1);
+ return to_cbuf(s, slice);
+};
+
+// Converts a Hare string to a C string. The result is stored into a
+// user-supplied buffer.
+export fn to_cbuf(s: const str, sl: []u8) *char = {
+ if (len(sl) < len(s) + 1) {
+ abort("to_cbuf: buffer has insufficient space for string plus NUL");
};
- ptr[len(s)] = 0;
- return ptr: *char;
+
+ const s = &s: *[]u8;
+ sl[..len(s)] = s[..];
+ sl[len(s)] = 0;
+
+ return (*(&sl: *types::slice)).data: *char;
};