Arrays.c 2.1 KB

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