commit 17089efd9e51eb2ea9b835bc89350c8dbc284f6a
parent 6b38b891ce50c16b29d8edf74734ac1acc5090d0
Author: Drew DeVault <sir@cmpwn.com>
Date: Mon, 21 Jun 2021 13:02:41 -0400
strings: add strings::join
Signed-off-by: Drew DeVault <sir@cmpwn.com>
Diffstat:
1 file changed, 34 insertions(+), 0 deletions(-)
diff --git a/strings/concat.ha b/strings/concat.ha
@@ -32,3 +32,37 @@ export fn concat(strs: str...) str = {
assert(s == "");
free(s);
};
+
+// Joins several strings together by placing a delimiter between them.
+export fn join(delim: str, strs: str...) str = {
+ let z = 0z;
+ for (let i = 0z; i < len(strs); i += 1) {
+ z += len(strs[i]);
+ if (i + 1 < len(strs)) {
+ z += len(delim);
+ };
+ };
+ let new: []u8 = alloc([], z);
+ for (let i = 0z; i < len(strs); i += 1) {
+ append(new, toutf8(strs[i])...);
+ if (i + 1 < len(strs)) {
+ append(new, toutf8(delim)...);
+ };
+ };
+ return fromutf8_unsafe(new[..z]);
+};
+
+@test fn join() void = {
+ let s = join(".", "a", "b", "c");
+ assert(s == "a.b.c");
+ free(s);
+
+ let s = join("", "a", "b", "c");
+ assert(s == "abc");
+ free(s);
+
+ let s = join(".");
+ assert(s == "");
+ free(s);
+
+};