lib/strings: add dup, Hare-shape

This commit is contained in:
2026-05-13 01:41:39 +09:00
parent da8d34e0d4
commit 3f0d1939f5

View File

@@ -106,3 +106,23 @@ export fn concat(a: str, b: str) str = {
r.len = total;
return r;
};
// dup — duplicate a string into a fresh allocation. Caller owns the
// returned str's storage; release via `os.free(r.ptr, r.len)`. Mirrors
// Hare's strings::dup shape — Hare returns `(str | nomem)`, ww doesn't
// have nomem (os.alloc aborts on OOM), so we return plain `str`.
//
// Empty input yields a `{nil, 0}` str — Hare returns the static empty
// string; same observable result.
export fn dup(s: str) str = {
let r: str;
r.ptr = nil;
r.len = 0;
if (s.len == 0) { return r; };
let buf: *u8 = os.alloc(s.len: u64): *u8;
let i: i32 = 0;
for (i < s.len) { buf[i] = s[i]; i += 1; };
r.ptr = buf;
r.len = s.len;
return r;
};