array.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * 3D Engine
  3. * array.c:
  4. * Based on pikuma.com 3D software renderer in C
  5. * Copyright (c) 2021 986-Studio. All rights reserved.
  6. *
  7. * Created by Manoël Trapier on 04/03/2021.
  8. */
  9. #include <stdlib.h>
  10. #include <stddef.h>
  11. #include <array.h>
  12. struct array_t
  13. {
  14. uint32_t allocatedSize;
  15. uint32_t usedSize;
  16. char data;
  17. };
  18. #define TO_ARRAY_T(_array) (struct array_t *) ((void*)(_array) - offsetof(struct array_t, data))
  19. void *arrayCheckSize(void *array, uint32_t count, size_t typeSize)
  20. {
  21. struct array_t *base = TO_ARRAY_T(array);
  22. uint32_t arrayLength;
  23. if (array == NULL)
  24. {
  25. /* Need to create the array */
  26. base = (struct array_t*)malloc(typeSize * count + sizeof(struct array_t));
  27. base->allocatedSize = count;
  28. base->usedSize = count;
  29. arrayLength = count;
  30. return &(base->data);
  31. }
  32. else if ((base->usedSize + count) <= base->allocatedSize)
  33. {
  34. /* Have enough space inside the array */
  35. base->usedSize += count;
  36. return array;
  37. }
  38. else
  39. {
  40. /* The array is not big enough */
  41. uint32_t newSize = base->allocatedSize;
  42. while(newSize < (base->usedSize + count))
  43. {
  44. newSize *= 2;
  45. }
  46. base = (struct array_t*)realloc(base, newSize * typeSize + sizeof(struct array_t));
  47. base->allocatedSize = newSize;
  48. base->usedSize += count;
  49. return &(base->data);
  50. }
  51. }
  52. uint32_t arrayGetSize(void *array)
  53. {
  54. struct array_t *base = TO_ARRAY_T(array);
  55. if ((array != NULL) && (base != NULL))
  56. {
  57. return base->usedSize;
  58. }
  59. return 0;
  60. }
  61. void arrayEmpty(void *array)
  62. {
  63. struct array_t *base = TO_ARRAY_T(array);
  64. if ((array != NULL) && (base != NULL))
  65. {
  66. base->usedSize = 0;
  67. }
  68. }
  69. void arrayFree(void *array)
  70. {
  71. struct array_t *base = TO_ARRAY_T(array);
  72. if ((array != NULL) && (base != NULL))
  73. {
  74. free(base);
  75. }
  76. }