List.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #define IMPORT_CORE
  2. #include "core/List.h"
  3. #include <assert.h>
  4. #include "core/Utility.h"
  5. static void ensureCapacity(List* l) {
  6. if(l->length >= l->capacity) {
  7. reserveListEntries(l, l->capacity + maxSize(4lu, l->capacity / 4));
  8. }
  9. }
  10. static void setSize(List* l, size_t n) {
  11. l->capacity = n;
  12. l->data = cReallocate(l->data, l->dataSize * n);
  13. }
  14. static void* getPointer(const List* l, size_t index) {
  15. return (char*)l->data + (l->dataSize * index);
  16. }
  17. void initList(List* l, size_t dataSize) {
  18. *l = (List){0, 0, dataSize, nullptr};
  19. }
  20. void destroyList(List* l) {
  21. cFree(l->data);
  22. *l = (List){0};
  23. }
  24. void reserveListEntries(List* l, size_t n) {
  25. if(n > l->capacity) {
  26. setSize(l, n);
  27. }
  28. }
  29. void addListData(List* l, const void* data) {
  30. memcpy(addEmptyListData(l), data, l->dataSize);
  31. }
  32. void addLastListData(List* l) {
  33. addListData(l, getListLast(l));
  34. }
  35. void* addEmptyListData(List* l) {
  36. ensureCapacity(l);
  37. return getPointer(l, l->length++);
  38. }
  39. void* getListIndex(const List* l, size_t index) {
  40. assert(index < l->length);
  41. return getPointer(l, index);
  42. }
  43. void* getListLast(const List* l) {
  44. return getListIndex(l, l->length - 1);
  45. }
  46. void clearList(List* l) {
  47. l->length = 0;
  48. }
  49. void removeListIndexBySwap(List* l, size_t index) {
  50. assert(index < l->length);
  51. size_t length = l->length - 1;
  52. if(index != length) {
  53. memcpy(getPointer(l, index), getPointer(l, length), l->dataSize);
  54. }
  55. l->length = length;
  56. }
  57. void removeListIndex(List* l, size_t index) {
  58. assert(index < l->length);
  59. l->length--;
  60. char* p = getPointer(l, index);
  61. char* end = getListEnd(l);
  62. while(p != end) {
  63. *p = *(p + l->dataSize);
  64. p++;
  65. }
  66. }
  67. void removeListLast(List* l) {
  68. removeListIndexBySwap(l, l->length - 1);
  69. }
  70. void* getListStart(const List* l) {
  71. return l->data;
  72. }
  73. void* getListEnd(const List* l) {
  74. return getPointer(l, l->length);
  75. }