ByteCode.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include "vm/ByteCode.h"
  5. ByteCode* bcInit() {
  6. ByteCode* bc = malloc(sizeof(ByteCode));
  7. bc->capacity = 16;
  8. bc->length = 0;
  9. bc->code = malloc(bc->capacity);
  10. return bc;
  11. }
  12. void bcDelete(ByteCode* bc) {
  13. free(bc->code);
  14. free(bc);
  15. }
  16. static void bcReAlloc(ByteCode* bc, int length) {
  17. while(bc->length + length > bc->capacity) {
  18. bc->capacity *= 2;
  19. bc->code = realloc(bc->code, bc->capacity);
  20. }
  21. }
  22. int bcReserveBytes(ByteCode* bc, int length) {
  23. bcReAlloc(bc, length);
  24. int p = bc->length;
  25. bc->length += length;
  26. return p;
  27. }
  28. void bcSetBytes(ByteCode* bc, int p, const void* data, int length) {
  29. memcpy(bc->code + p, data, length);
  30. }
  31. void bcAddBytes(ByteCode* bc, const void* data, int length) {
  32. bcSetBytes(bc, bcReserveBytes(bc, length), data, length);
  33. }
  34. int bcGetAddress(ByteCode* bc) {
  35. return bc->length;
  36. }
  37. void bcInsertBytes(ByteCode* bc, const void* data, int length, int address) {
  38. bcReAlloc(bc, length);
  39. memmove(bc->code + address + length, bc->code + address,
  40. bc->length - address);
  41. memcpy(bc->code + address, data, length);
  42. bc->length += length;
  43. }