From d046c7d20fd283c90495d3af4bb53d1cfb2a0812 Mon Sep 17 00:00:00 2001 From: ubq323 Date: Thu, 8 Aug 2024 14:44:48 +0100 Subject: misc --- lib.c | 49 +++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 45 insertions(+), 4 deletions(-) (limited to 'lib.c') diff --git a/lib.c b/lib.c index a1ca311..dddd377 100644 --- a/lib.c +++ b/lib.c @@ -1,9 +1,12 @@ #include +#include +#include #include "lib.h" #include "state.h" #include "val.h" #include "util.h" +#include "mem.h" static Val fn_clock(State *S, int nargs, Val *args) { return VAL_NUM((double)clock() / CLOCKS_PER_SEC); @@ -11,15 +14,33 @@ static Val fn_clock(State *S, int nargs, Val *args) { static Val fn_write(State *S, int nargs, Val *args) { CHECK(nargs>0, "need 1 arg to write"); - print_val(args[0]); + for (int i = 0; i < nargs; i++) print_val(args[i]); return VAL_NIL; } static Val fn_say(State *S, int nargs, Val *args) { CHECK(nargs>0, "need 1 arg to say"); - println_val(args[0]); + for (int i = 0; i < nargs; i++) println_val(args[i]); return VAL_NIL; } +static uint8_t num_to_u8(Val v) { + CHECK(IS_NUM(v), "can't convert non-num to u8"); + return (uint8_t)AS_NUM(v); +} +static Val fn_writebytes(State *S, int nargs, Val *args) { + CHECK(nargs == 1, "need exactly 1 arg to writebytes"); + CHECK(IS_ARR(args[0]), "need array arg to writebytes"); + ObjArr *a = AS_ARR(args[0]); + uint8_t *buf = malloc(1 * a->len); + for (int i = 0; i < a->len; i++) { + buf[i] = num_to_u8(a->d[i]); + } + fwrite(buf, 1, a->len, stdout); + return VAL_NIL; +} + + + // lists static Val fn_arr(State *S, int nargs, Val *args) { @@ -57,6 +78,24 @@ static Val fn_pend(State *S, int nargs, Val *args) { } +// strings +static Val fn_spend(State *S, int nargs, Val *args) { + size_t len = 0; + for (int i = 0; i < nargs; i++) { + CHECK(IS_STRING(args[i]), "can only spend strings"); + len += AS_STRING(args[i])->len; + } + char *new = NEW_ARR(S, char, len+1); + char *cur = new; + for (int i = 0; i < nargs; i++) { + ObjString *s = AS_STRING(args[i]); + memcpy(cur, s->d, s->len); + cur += s->len; + } + return VAL_OBJ(objstring_take(S, new, len)); +} + + typedef struct { char *name; CFunc func; @@ -65,11 +104,13 @@ static BuiltinFunc builtin_funcs[] = { { "clock", fn_clock }, { "say", fn_say }, { "write", fn_write }, + { "writebytes", fn_writebytes }, { "arr", fn_arr }, - { "append", fn_append }, - { "len", fn_len }, + { "append!", fn_append }, + { "#", fn_len }, { ",", fn_pend }, + { "s,", fn_spend }, { 0 }, }; -- cgit v1.2.3