diff options
author | ubq323 <ubq323@ubq323.website> | 2024-08-08 14:44:48 +0100 |
---|---|---|
committer | ubq323 <ubq323@ubq323.website> | 2024-08-08 14:49:05 +0100 |
commit | d046c7d20fd283c90495d3af4bb53d1cfb2a0812 (patch) | |
tree | a764b20d45135101b179a4fbdc122ca0c76bd6b6 /lib.c | |
parent | a4e8599e8d0fde881cd4e6e3031e5b52550e878e (diff) |
misc
Diffstat (limited to 'lib.c')
-rw-r--r-- | lib.c | 49 |
1 files changed, 45 insertions, 4 deletions
@@ -1,9 +1,12 @@ #include <time.h> +#include <string.h> +#include <stdio.h> #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 }, }; |