-
Notifications
You must be signed in to change notification settings - Fork 0
/
chunk.c
41 lines (35 loc) · 1.09 KB
/
chunk.c
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
#include <stdlib.h>
#include "chunk.h"
#include "memory.h"
#include "vm.h"
void init_chunk(Chunk *chunk) {
chunk->code = NULL;
chunk->lines = NULL;
chunk->len = 0;
chunk->cap = 0;
init_value_array(&chunk->constants);
}
void write_chunk(Chunk *chunk, uint8_t byte, int line) {
if (chunk->cap < chunk->len + 1) {
int old_cap = chunk->cap;
chunk->cap = GROW_CAPACITY(old_cap);
chunk->code = GROW_ARRAY(uint8_t, chunk->code, old_cap, chunk->cap);
chunk->lines = GROW_ARRAY(int, chunk->lines, old_cap, chunk->cap);
}
chunk->code[chunk->len] = byte;
// TODO this is a waste of memory, use run-length encoding to store line info
chunk->lines[chunk->len] = line;
chunk->len++;
}
void free_chunk(Chunk *chunk) {
FREE_ARRAY(uint8_t, chunk->code, chunk->cap);
FREE_ARRAY(int, chunk->lines, chunk->cap);
free_value_array(&chunk->constants);
init_chunk(chunk);
}
int add_constant(Chunk *chunk, Value value) {
push(value);
write_value_array(&chunk->constants, value);
pop();
return chunk->constants.len - 1;
}