Arrays.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "vm/Arrays.h"
  4. /*typedef struct {
  5. int length;
  6. DataType type;
  7. int references;
  8. int next;
  9. int previous;
  10. void* data;
  11. } Array;
  12. typedef struct {
  13. int capacity;
  14. int usedStart;
  15. int freeStart;
  16. Array* data;
  17. } Arrays;*/
  18. void asInit(Arrays* as) {
  19. as->capacity = 0;
  20. as->usedStart = -1;
  21. as->freeStart = -1;
  22. as->data = NULL;
  23. }
  24. void asDelete(Arrays* as) {
  25. for(int i = 0; i < as->capacity; i++) {
  26. free(as->data[i].data);
  27. }
  28. free(as->data);
  29. }
  30. static void aInitArray(Array* a, int previous, int next) {
  31. a->length = 0;
  32. a->type = DT_VOID;
  33. a->references = 0;
  34. a->next = next;
  35. a->previous = previous;
  36. a->data = NULL;
  37. }
  38. static void asInitArrays(Arrays* as, int start) {
  39. int end = as->capacity - 1;
  40. aInitArray(as->data + start, -1, start + 1);
  41. for(int i = start + 1; i < end; i++) {
  42. aInitArray(as->data + i, i - 1, i + 1);
  43. }
  44. aInitArray(as->data + end, end - 1, -1);
  45. as->freeStart = start;
  46. }
  47. static void asEnsureCapacity(Arrays* as) {
  48. if(as->freeStart != -1) {
  49. return;
  50. }
  51. if(as->data == NULL) {
  52. as->capacity = 4;
  53. as->data = malloc(sizeof(Array) * as->capacity);
  54. asInitArrays(as, 0);
  55. } else {
  56. int start = as->capacity;
  57. as->capacity *= 2;
  58. as->data = realloc(as->data, sizeof(Array) * as->capacity);
  59. asInitArrays(as, start);
  60. }
  61. }
  62. int asAllocate(Arrays* as, DataType type, int length) {
  63. asEnsureCapacity(as);
  64. int index = as->freeStart;
  65. Array* array = as->data + index;
  66. as->freeStart = array->next;
  67. if(array->next == -1) {
  68. as->data[array->next].previous = -1;
  69. }
  70. array->next = as->usedStart;
  71. if(as->usedStart != -1) {
  72. as->data[as->usedStart].previous = index;
  73. }
  74. as->usedStart = index;
  75. array->length = length;
  76. array->type = type;
  77. array->data = malloc(sizeof(dtGetSize(type)) * length);
  78. return index;
  79. }
  80. Array* asGet(Arrays* as, int p) {
  81. if(p < 0 || p >= as->capacity) {
  82. return NULL;
  83. }
  84. return as->data + p;
  85. }
  86. void aAddReference(Array* a) {
  87. a->references++;
  88. }
  89. void aRemoveReference(Array* a) {
  90. if(--a->references > 0) {
  91. return;
  92. }
  93. printf("Please remove me");
  94. }
  95. void asPrintDebug(Arrays* as) {
  96. (void)as;
  97. }