blob: b65ad42b97a14c4d0e0e8d50b1d21ded88a3139a (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
#include "memory.h"
#include "slice.h"
#include <stdlib.h>
#include <stdio.h>
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 len = 0;
for (Token *e = list; e != NULL; e = e->next)
if (e->type == TOK_GROUP)
len += strings_cat(mem + len, e->group.tokens);
else if (e->type == TOK_STRING) {
slice_cpy(mem + len, e->slice);
len += slice_len(e->slice) + 1;
}
return len;
}
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);
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;
}
}
|