lib/strings+test: port join from Hare str... variadic (#19)
This commit is contained in:
@@ -1686,6 +1686,47 @@ export fn concat(strs: str...) str = {
|
||||
return r;
|
||||
};
|
||||
|
||||
// join — fresh allocation with `delim` placed between each element of
|
||||
// `strs`. Caller releases with `os.free(r.ptr, r.len: u64)`.
|
||||
// ref/hare/strings/concat.ha:46. Hare's `nomem` return is dropped:
|
||||
// `os.alloc` aborts on OOM.
|
||||
export fn join(delim: str, strs: str...) str = {
|
||||
let total: i32 = 0;
|
||||
let i: i32 = 0;
|
||||
for (i < strs.len) {
|
||||
total += strs[i].len;
|
||||
if (i + 1 < strs.len) { total += delim.len; };
|
||||
i += 1;
|
||||
};
|
||||
let r: str;
|
||||
r.ptr = nil;
|
||||
r.len = 0;
|
||||
if (total == 0) { return r; };
|
||||
let buf: *u8 = os.alloc(total: u64): *u8;
|
||||
let off: i32 = 0;
|
||||
i = 0;
|
||||
for (i < strs.len) {
|
||||
let j: i32 = 0;
|
||||
for (j < strs[i].len) {
|
||||
buf[off + j] = strs[i][j];
|
||||
j += 1;
|
||||
};
|
||||
off += strs[i].len;
|
||||
if (i + 1 < strs.len) {
|
||||
j = 0;
|
||||
for (j < delim.len) {
|
||||
buf[off + j] = delim[j];
|
||||
j += 1;
|
||||
};
|
||||
off += delim.len;
|
||||
};
|
||||
i += 1;
|
||||
};
|
||||
r.ptr = buf;
|
||||
r.len = total;
|
||||
return r;
|
||||
};
|
||||
|
||||
// sub — borrowed `s[start..end]`. ref/hare/strings/sub.ha:30 is
|
||||
// rune-wise; this ww form is byte-wise (no rune iterator yet, planned
|
||||
// for commit 2). Clamps out-of-range silently where Hare aborts —
|
||||
|
||||
Reference in New Issue
Block a user