-
Notifications
You must be signed in to change notification settings - Fork 0
/
chunk.c
39 lines (33 loc) · 1.17 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
#include <stdlib.h>
#include "chunk.h"
#include "memory.h"
void initChunk(Chunk* chunk) {
chunk->count = 0;
chunk->capacity = 0;
chunk->code = NULL;
initValueArray(&chunk->constants);
chunk->lines = NULL;
}
void writeChunk(Chunk* chunk, uint8_t byte, int line) {
// if the array is full, increase capacity and copy all bytecodes to new array and then append
// else append at end
if (chunk->capacity < chunk->count + 1) {
int oldCap = chunk->capacity;
chunk->capacity = GROW_CAPACITY(oldCap);
chunk->code = GROW_ARRAY(uint8_t, chunk->code, oldCap, chunk->capacity);
chunk->lines = GROW_ARRAY(int, chunk->lines, oldCap, chunk->capacity);
}
chunk->code[chunk->count] = byte;
chunk->lines[chunk->count] = line;
chunk->count++;
}
void freeChunk(Chunk* chunk) {
FREE_ARRAY(uint8_t, chunk->code, chunk->capacity);
FREE_ARRAY(int, chunk->lines, chunk->capacity);
freeValueArray(&chunk->constants);
initChunk(chunk);
}
int addConstant(Chunk* chunk, int value) {
writeValueArray(&chunk->constants, value);
return chunk->constants.count - 1; // location of where the constant has been appended
}