stew

a monorepo of some sort
Log | Files | Refs

commit d76e19e58222672b494e520b41eb7330e10a494e
parent f2e98968184022c01579d4fb626a6419003a9483
Author: rpa <rpa@laika>
Date:   Sun,  9 Apr 2023 22:23:11 +0000

list: new list

Diffstat:
Msrc/list/list.c | 86++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Msrc/list/list.h | 33+++++++++++++--------------------
2 files changed, 87 insertions(+), 32 deletions(-)

diff --git a/src/list/list.c b/src/list/list.c @@ -3,20 +3,82 @@ #include "list.h" -void -printlist(Cell c) +int +readcell(int fd, Cell *cell) { - if (c.type == CNull) return; - Cell fst = head(c); - print("%s\n", fst.p); - printlist(tail(c)); + if (read(fd, &cell->type, sizeof(u8int)) <= 0) return -1; + if (read(fd, &cell->count, sizeof(u32int)) <= 0) return -1; + if ((cell->type == CNull) || (cell->type == CList)) { + cell->count = 0; + return 0; + } + char *buf = malloc(sizeof(cell->count)); + if (read(fd, buf, cell->count) < cell->count) { + free(buf); + return -1; + } + cell->data = buf; + return 0; } -void -main(void) +int +writecell(int fd, Cell *cell) { - char *a = "uno", *b = "duo", *c = "tres"; - Cell A = {CAtom, a}, B = {CAtom, b}, C = {CAtom, c}; - Cell D = cons(A, cons(B, C)); - printlist(D); + if (write(fd, &cell->type, sizeof(u8int)) <= 0) return -1; + if (write(fd, &cell->count, sizeof(u32int)) <= 0) return -1; + if (write(fd, cell->data, cell->count) < cell->count) return -1; + return 0; +} + +Cell * +readlist(int fd) +{ + int i = 0, len = 0; + Cell *list = nil; + for (;;) { + if (i >= len) { + len += 256; + list = realloc(list, sizeof(Cell) * len); + } + if (readcell(fd, list + i) < 0) { + free(list); + return nil; + } + switch (list[i].type) { + case CList: + list[i].data = readlist(fd); + if (list[i].data == nil) { + free(list); + return nil; + } + break; + case CNull: + list[i].count = 0; + return list; + } + } +} + +int +writelist(int fd, Cell *cell) +{ + int n = 0, r; + for (;;) { + if ((r = write(fd, &cell->type, sizeof(u8int))) <= 0) return -1; + n += r; + if ((r = write(fd, &cell->count, sizeof(u32int))) <= 0) return -1; + n += r; + switch (cell->type) { + case CList: + writelist(fd, cell->data); + break; + case CNull: + goto over; + default: + if ((r = write(fd, cell->data, cell->count)) <= 0) return -1; + n += r; + } + } + over: + return n; } diff --git a/src/list/list.h b/src/list/list.h @@ -1,28 +1,21 @@ enum { CNull = 0, - CPair, - CAtom, - CError = -1, + CList, + CString, + + CMax, + + CGarbage = 0xff, }; typedef struct Cell Cell; struct Cell { - char type; - void *p; -}; - -typedef struct Pair Pair; -struct Pair { - union { - Cell p[2]; - struct { - Cell fst; - Cell snd; - }; - }; + u8int type; + u32int count; + void *data; }; -Cell cons (Cell, Cell); -Cell head (Cell); -Cell tail (Cell); -int eq(Cell, Cell); +int readcell(int, Cell *); +int writecell(int, Cell *); +Cell * readlist(int); +int writelist(int, Cell *);