summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorubq323 <ubq323@ubq323.website>2024-08-09 23:37:13 +0100
committerubq323 <ubq323@ubq323.website>2024-08-09 23:37:13 +0100
commit14b6304bb416795ca1016e9ce5f052b0861e5a48 (patch)
treec3d89d22e85f8ebb7070ed742a8baef471aa64c8
parentd046c7d20fd283c90495d3af4bb53d1cfb2a0812 (diff)
add ssplit
-rw-r--r--Makefile2
-rw-r--r--lib.c22
-rw-r--r--tests/ssplit.bth7
-rw-r--r--tests/ssplit.out7
4 files changed, 37 insertions, 1 deletions
diff --git a/Makefile b/Makefile
index ef71e96..df852dd 100644
--- a/Makefile
+++ b/Makefile
@@ -1,6 +1,6 @@
CS= com.c dis.c ht.c lib.c mem.c read.c state.c val.c vm.c
HS=chunk.h com.h dis.h ht.h lib.h mem.h read.h state.h util.h val.h vm.h
-CFLAGS=$(EXTRA_CFLAGS) -g -lm -Wall -Wpedantic -Werror=implicit-function-declaration
+CFLAGS=$(EXTRA_CFLAGS) -O3 -g -lm -Wall -Wpedantic -Werror=implicit-function-declaration
bth: $(CS) $(HS) Makefile
$(CC) $(CFLAGS) -o bth $(CS)
diff --git a/lib.c b/lib.c
index dddd377..5d5d2b3 100644
--- a/lib.c
+++ b/lib.c
@@ -94,6 +94,27 @@ static Val fn_spend(State *S, int nargs, Val *args) {
}
return VAL_OBJ(objstring_take(S, new, len));
}
+static Val fn_ssplit(State *S, int nargs, Val *args) {
+ CHECK(nargs==2,"need exactly 2 args for ssplit");
+ CHECK(IS_STRING(args[0]) && IS_STRING(args[1]), "need two strings for ssplit");
+ ObjString *delim = AS_STRING(args[0]);
+ ObjString *text = AS_STRING(args[1]);
+ CHECK(delim->len == 1, "need length-1 delimiter");
+ char delimc = delim->d[0];
+
+ ObjArr *out = objarr_new(S);
+ int start = 0;
+ for (int i = 0; i <= text->len; i++) {
+ if (text->d[i] == delimc || i == text->len) {
+ ObjString *new = objstring_copy(S, &text->d[start], i-start);
+ objarr_append(S, out, VAL_OBJ(new));
+ start = i + 1;
+ }
+ }
+
+ return VAL_OBJ(out);
+}
+
typedef struct {
@@ -111,6 +132,7 @@ static BuiltinFunc builtin_funcs[] = {
{ "#", fn_len },
{ ",", fn_pend },
{ "s,", fn_spend },
+ { "ssplit", fn_ssplit },
{ 0 },
};
diff --git a/tests/ssplit.bth b/tests/ssplit.bth
new file mode 100644
index 0000000..4dbc860
--- /dev/null
+++ b/tests/ssplit.bth
@@ -0,0 +1,7 @@
+(say (ssplit " " "aaa bbb ccc"))
+(say (ssplit 'l "flucloxacillin"))
+(say (ssplit 'l "hi"))
+(say (ssplit 'l ""))
+(say (ssplit 'l 'local))
+(say (ssplit 'l 'focal))
+(say (ssplit 'l 'locate))
diff --git a/tests/ssplit.out b/tests/ssplit.out
new file mode 100644
index 0000000..fd23afa
--- /dev/null
+++ b/tests/ssplit.out
@@ -0,0 +1,7 @@
+[aaa bbb ccc]
+[f uc oxaci in]
+[hi]
+[]
+[ oca ]
+[foca ]
+[ ocate]