From c15fb7460c7ebf5e9a396dc8a1e83902f4840238 Mon Sep 17 00:00:00 2001 From: Christoffer Lerno Date: Sun, 4 Dec 2022 23:01:53 +0100 Subject: [PATCH] Add functions for splitting strings. --- lib/std/core/array.c3 | 9 +++++++++ lib/std/core/str.c3 | 31 +++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/lib/std/core/array.c3 b/lib/std/core/array.c3 index 4ccf1380d..c8cf732af 100644 --- a/lib/std/core/array.c3 +++ b/lib/std/core/array.c3 @@ -15,6 +15,15 @@ macro tconcat(arr1, arr2) return result; } +macro index_of(array, element) +{ + foreach (i, &e : array) + { + if (*e == element) return i; + } + return SearchResult.MISSING!; +} + macro concat(arr1, arr2) { var $Type = $typeof(arr1[0]); diff --git a/lib/std/core/str.c3 b/lib/std/core/str.c3 index 4df5b2e87..d99fd396e 100644 --- a/lib/std/core/str.c3 +++ b/lib/std/core/str.c3 @@ -148,6 +148,37 @@ fn bool starts_with(char[] s, char[] needle) return true; } +fn char[][] tsplit(char[] s, char[] needle) = split(s, needle, mem::temp_allocator()) @inline; + +fn char[][] split(char[] s, char[] needle, Allocator* allocator = mem::current_allocator()) +{ + usz capacity = 16; + usz i = 0; + char[]* holder = allocator.alloc(char[].sizeof * capacity)!!; + while (s.len) + { + usz! index = index_of(s, needle); + char[] res = void; + if (try index) + { + res = s[:index]; + s = s[index + 1..]; + } + else + { + res = s; + s = s[:0]; + } + if (i == capacity) + { + capacity *= 2; + holder = allocator.realloc(holder, capacity)!!; + } + holder[i++] = res; + } + return holder[:i]; +} + fn usz! index_of(char[] s, char[] needle) { usz match = 0;