diff options
| author | Rose Hogenson <rhogenson@posteo.net> | 2023-02-11 13:50:38 -0800 |
|---|---|---|
| committer | Rose Hogenson <rhogenson@posteo.net> | 2023-02-11 13:50:38 -0800 |
| commit | aafc502de6f9ecbeb4638b1862f4fa5ac82199d7 (patch) | |
| tree | a9358c71c0dd88b4f2ea4e7276fd28b8a83a95ed | |
| parent | 60622614731bc42dd44704d3cff55b4e4c4f492c (diff) | |
| download | sml-aafc502de6f9ecbeb4638b1862f4fa5ac82199d7.tar.zst | |
Slightly simplify bytecode interpreter.
| -rw-r--r-- | bytecode/bytecode.c | 32 |
1 files changed, 10 insertions, 22 deletions
diff --git a/bytecode/bytecode.c b/bytecode/bytecode.c index a21231b..1d0f957 100644 --- a/bytecode/bytecode.c +++ b/bytecode/bytecode.c @@ -6,18 +6,6 @@ #include "panic.h" #include "slice.h" -static struct slice xmalloc(size_t size) -{ - void *p = malloc(size); - if (!p) { - panicf("Out of memory!\n"); - } - return (struct slice) { - .buf = p, - .size = size, - }; -} - static struct slice xrealloc(void *ptr, size_t size) { void *p = realloc(ptr, size); @@ -30,26 +18,26 @@ static struct slice xrealloc(void *ptr, size_t size) }; } -void read_file(struct slice *out, char *filename) +struct slice read_file(char *filename) { FILE *f = fopen(filename, "r"); if (!f) { panicf("File %s does not exit!\n", filename); } + struct slice out = { .size = 0, .buf = NULL }; size_t offset = 0; while (true) { - if (offset >= out->size) { - size_t new_size = 2 * out->size; - *out = xrealloc(out->buf, new_size); + if (offset >= out.size) { + size_t new_size = 2 * out.size + 1; + out = xrealloc(out.buf, new_size); } - size_t read_size = out->size - offset; - size_t n = fread(out->buf + offset, 1, read_size, f); + size_t read_size = out.size - offset; + size_t n = fread(out.buf + offset, 1, read_size, f); if (n < read_size) { if (ferror(f)) { panicf("Read error!\n"); } - out->size = offset + n; - return; + return slice(out, 0, offset + n); } offset += n; } @@ -62,10 +50,10 @@ int main(int argc, char **argv) return 1; } - struct slice program = xmalloc(1); - read_file(&program, argv[1]); + struct slice program = read_file(argv[1]); run(program); + // run never returns. I'm just putting this here to taunt you: free(program.buf); } |
