| 1 |
// SPDX-License-Identifier: MPL-2.0 |
| 2 |
// (c) Hare authors <https://harelang.org> |
| 3 |
|
| 4 |
// Concatenates multiple strings. The caller must free the return value. |
| 5 |
export fn concat(strs: str...) (str | nomem) = { |
| 6 |
let z = 0z; |
| 7 |
for (let s .. strs) { |
| 8 |
z += len(s); |
| 9 |
}; |
| 10 |
|
| 11 |
let new: []u8 = alloc([], z)?; |
| 12 |
for (let s .. strs) { |
| 13 |
static append(new, toutf8(s)...)!; |
| 14 |
}; |
| 15 |
return fromutf8_unsafe(new); |
| 16 |
}; |
| 17 |
|
| 18 |
@test fn concat() void = { |
| 19 |
let s = concat("hello ", "world")!; |
| 20 |
defer free(s); |
| 21 |
assert(s == "hello world"); |
| 22 |
|
| 23 |
let s = concat("hello", " ", "world")!; |
| 24 |
defer free(s); |
| 25 |
assert(s == "hello world"); |
| 26 |
|
| 27 |
let s = concat("hello", "", "world")!; |
| 28 |
defer free(s); |
| 29 |
assert(s == "helloworld"); |
| 30 |
|
| 31 |
let s = concat("", "")!; |
| 32 |
defer free(s); |
| 33 |
assert(s == ""); |
| 34 |
|
| 35 |
let s = concat()!; |
| 36 |
defer free(s); |
| 37 |
assert(s == ""); |
| 38 |
|
| 39 |
let s = concat("hello")!; |
| 40 |
defer free(s); |
| 41 |
assert(s == "hello"); |
| 42 |
}; |
| 43 |
|
| 44 |
// Joins several strings together by placing a delimiter between them. The |
| 45 |
// caller must free the return value. |
| 46 |
export fn join(delim: str, strs: str...) (str | nomem) = { |
| 47 |
let z = 0z; |
| 48 |
for (let i = 0z; i < len(strs); i += 1) { |
| 49 |
z += len(strs[i]); |
| 50 |
if (i + 1 < len(strs)) { |
| 51 |
z += len(delim); |
| 52 |
}; |
| 53 |
}; |
| 54 |
let new: []u8 = alloc([], z)?; |
| 55 |
for (let i = 0z; i < len(strs); i += 1) { |
| 56 |
static append(new, toutf8(strs[i])...)!; |
| 57 |
if (i + 1 < len(strs)) { |
| 58 |
static append(new, toutf8(delim)...)!; |
| 59 |
}; |
| 60 |
}; |
| 61 |
return fromutf8_unsafe(new); |
| 62 |
}; |
| 63 |
|
| 64 |
@test fn join() void = { |
| 65 |
let s = join(".", "a", "b", "c")!; |
| 66 |
defer free(s); |
| 67 |
assert(s == "a.b.c"); |
| 68 |
|
| 69 |
let s = join("", "a", "b", "c")!; |
| 70 |
defer free(s); |
| 71 |
assert(s == "abc"); |
| 72 |
|
| 73 |
let s = join(".")!; |
| 74 |
defer free(s); |
| 75 |
assert(s == ""); |
| 76 |
|
| 77 |
let s = join(".", "a")!; |
| 78 |
defer free(s); |
| 79 |
assert(s == "a"); |
| 80 |
}; |