-
Notifications
You must be signed in to change notification settings - Fork 0
/
chunk.c
59 lines (52 loc) · 1.51 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include "chunk.h"
#include "common.h"
#include "memory.h"
#include "rle.h"
#include "vm.h"
#include <stdlib.h>
void initChunk(Chunk *chunk) {
chunk->count = 0;
chunk->capacity = 0;
chunk->code = NULL;
chunk->lines = NULL;
initValueArray(&chunk->constants);
init_rle(&chunk->rle);
}
void freeChunk(Chunk *chunk) {
FREE_ARRAY(uint8_t, chunk->code, chunk->capacity);
FREE_ARRAY(int, chunk->lines, chunk->capacity);
freeValueArray(&chunk->constants);
initChunk(chunk);
}
void writeChunk(Chunk *chunk, uint8_t byte, int line) {
if (chunk->capacity < chunk->count + 1) {
int oldCapacity = chunk->capacity;
chunk->capacity = GROW_CAPACITY(oldCapacity);
chunk->code =
GROW_ARRAY(uint8_t, chunk->code, oldCapacity, chunk->capacity);
chunk->lines = GROW_ARRAY(int, chunk->lines, oldCapacity, chunk->capacity);
}
chunk->code[chunk->count] = byte;
chunk->lines[chunk->count] = line;
push_rle(&chunk->rle, line);
chunk->count++;
}
int addConstant(Chunk *chunk, Value value) {
push(value);
writeValueArray(&chunk->constants, value);
pop();
return chunk->constants.count - 1;
}
// TODO: Exercise, add support for multi-byte operands
void writeConstant(Chunk *chunk, Value value, int line) {
int index = addConstant(chunk, value);
if (index >= 256) {
writeChunk(chunk, index, line);
writeChunk(chunk, index, line);
}
}
int getLine(Chunk chunk, int position) {
int arr[chunk.rle.original_count];
expand_rle(&chunk.rle, arr, chunk.rle.original_count);
return arr[position];
}