chunk.c 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. //
  2. // Created by 李晓明 on 2023/6/14.
  3. //
  4. #include "chunk.h"
  5. #include "memory.h"
  6. void initChunk(Chunk *chunk) {
  7. chunk->count = 0;
  8. chunk->capacity = 0;
  9. chunk->code = NULL;
  10. chunk->lines = NULL;
  11. initValueArray(&chunk->constants);
  12. }
  13. void freeChunk(Chunk *chunk) {
  14. FREE_ARRAY(uint8_t, chunk->code, chunk->capacity);
  15. FREE_ARRAY(int, chunk->lines, chunk->capacity);
  16. freeValueArray(&chunk->constants);
  17. initChunk(chunk);
  18. }
  19. void writeChunk(Chunk *chunk, uint8_t byte, int line) {
  20. // 容量不够
  21. if (chunk->capacity < chunk->count + 1) {
  22. int oldCapacity = chunk->capacity;
  23. chunk->capacity = GROW_CAPACITY(oldCapacity);
  24. chunk->code = GROW_ARRAY(uint8_t, chunk->code, oldCapacity, chunk->capacity);
  25. chunk->lines = GROW_ARRAY(int, chunk->lines, oldCapacity, chunk->capacity);
  26. }
  27. // 赋值
  28. chunk->code[chunk->count] = byte;
  29. chunk->lines[chunk->count] = line;
  30. chunk->count++;
  31. }
  32. int addConstant(Chunk *chunk, Value value) {
  33. writeValueArray(&chunk->constants, value);
  34. return chunk->constants.count - 1;
  35. }