#include "memory.h" #include "slice.h" #include #include static int strings_len(Token *list) { int len = 0; for (Token *e = list; e != NULL; e = e->next) if (e->type == TOK_GROUP) len += strings_len(e->group.tokens); else if (e->type == TOK_STRING) len += slice_len(e->slice) + 1; return len; } static int strings_cat(char *mem, Token *list, int off) { for (Token *e = list; e != NULL; e = e->next) if (e->type == TOK_GROUP) off = strings_cat(mem, e->group.tokens, off); else if (e->type == TOK_STRING) { slice_cpy(mem + off, e->slice); e->string_ptr = off; off += slice_len(e->slice) + 1; } return off; } int memory_create(Memory *memory, Token *list) { const int len = strings_len(list); memory->strings = malloc(len); if (memory->strings == NULL) { perror("memory_create:malloc"); return 1; } const int cated = strings_cat(memory->strings, list, 0); if (cated != len) { fprintf(stderr, "strings_cat wrote %d bytes instead of %d", cated, len); free(memory->strings); memory->strings = NULL; return 1; } return 0; } void memory_destroy(Memory *memory) { if (memory->strings != NULL) { free(memory->strings); memory->strings = NULL; } }