commit 2c896e77c9b4aa0910eed27ef1d55a0575653ea5
parent f0fcc878219cc034a9f110f6a2b36912db148238
Author: Alexey Yerin <yyp@disroot.org>
Date: Tue, 23 Nov 2021 12:16:29 +0300
strings: make dupall return a new slice, add freeall
This makes it a bit more useful in some cases.
Signed-off-by: Alexey Yerin <yyp@disroot.org>
Diffstat:
1 file changed, 25 insertions(+), 4 deletions(-)
diff --git a/strings/dup.ha b/strings/dup.ha
@@ -26,12 +26,33 @@ export fn dup(s: const str) str = {
return *(&out: *str);
};
-// Duplicates every string of a slice in place, returning the same slice with
-// new strings.
-export fn dupall(s: []str) void = {
+// Creates a copy of a []str slice with all the strings duplicated. The result
+// must be freed using [[freeall]].
+export fn dupall(s: []str) []str = {
+ let newsl = *(&types::slice_repr {
+ data = match (rt::malloc(len(s) * size(str))) {
+ case null =>
+ abort("Out of memory");
+ case v: *void =>
+ yield v;
+ },
+ length = len(s),
+ capacity = len(s),
+ }: *[]str);
+
for (let i = 0z; i < len(s); i += 1) {
- s[i] = strings::dup(s[i]);
+ newsl[i] = strings::dup(s[i]);
};
+
+ return newsl;
+};
+
+// Frees all the strings in a slice and the slice itself. Inverse of [[dupall]].
+export fn freeall(s: []str) void = {
+ for (let i = 0z; i < len(s); i += 1) {
+ free(s[i]);
+ };
+ free(s);
};
@test fn dup() void = {