Allocator.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "vm/Allocator.h"
  4. /*void aInit(Allocator* a) {
  5. a->capacity = 0;
  6. a->usedStart = -1;
  7. a->freeStart = -1;
  8. a->data = NULL;
  9. }
  10. void aDelete(Allocator* a) {
  11. for(int i = a->usedStart; i != -1; i = a->data[i].next) {
  12. printf("end Dealloc %d\n", a->data[i].length);
  13. free(a->data[i].data);
  14. }
  15. free(a->data);
  16. }
  17. static void aInitArray(Array* a, int next) {
  18. a->length = 0;
  19. a->next = next;
  20. a->marked = false;
  21. a->data = NULL;
  22. }
  23. static void aInitArrays(Allocator* a, int start) {
  24. for(int i = start; i < a->capacity - 1; i++) {
  25. aInitArray(a->data + i, i + 1);
  26. }
  27. aInitArray(a->data + (a->capacity - 1), -1);
  28. a->freeStart = start;
  29. }
  30. int aAllocate(Allocator* a, int length) {
  31. if(a->freeStart == -1) {
  32. if(a->data == NULL) {
  33. a->capacity = 4;
  34. a->data = malloc(sizeof(Array) * a->capacity);
  35. aInitArrays(a, 0);
  36. } else {
  37. int start = a->capacity;
  38. a->capacity *= 2;
  39. a->data = realloc(a->data, sizeof(Array) * a->capacity);
  40. aInitArrays(a, start);
  41. }
  42. }
  43. int index = a->freeStart;
  44. Array* array = a->data + index;
  45. a->freeStart = array->next;
  46. array->length = length;
  47. array->next = a->usedStart;
  48. a->usedStart = index;
  49. array->data = malloc(sizeof(Object) * length);
  50. for(int i = 0; i < length; i++) {
  51. array->data[i].type = OT_NULL;
  52. }
  53. return index;
  54. }
  55. void aClearMarker(Allocator* a) {
  56. for(int i = a->usedStart; i != -1; i = a->data[i].next) {
  57. a->data[i].marked = false;
  58. }
  59. }
  60. void aRemoveUnmarked(Allocator* a) {
  61. int prev = -1;
  62. int i = a->usedStart;
  63. while(i != -1) {
  64. int next = a->data[i].next;
  65. if(!a->data[i].marked) {
  66. free(a->data[i].data);
  67. if(prev == -1) {
  68. a->usedStart = next;
  69. } else {
  70. a->data[prev].next = next;
  71. }
  72. a->data[i].next = a->freeStart;
  73. a->freeStart = i;
  74. a->data[i].length = 0;
  75. a->data[i].data = NULL;
  76. } else {
  77. prev = i;
  78. }
  79. i = next;
  80. }
  81. }*/