vec.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include <ell/vec.h>
  2. #include <assert.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. void ell__vec_init(struct ell_vec_core* core, void** data)
  6. {
  7. assert(core != 0);
  8. assert(data != 0);
  9. core->capacity = 0;
  10. core->size = 0;
  11. *data = 0;
  12. }
  13. void ell__vec_ensure_capacity(struct ell_vec_core* core, void** data, size_t element_size)
  14. {
  15. assert(core != 0);
  16. assert(data != 0);
  17. if (core->size >= core->capacity) {
  18. size_t new_capacity = core->capacity ? 2 * core->capacity : 2;
  19. ell__vec_reserve(core, data, element_size, new_capacity);
  20. }
  21. }
  22. void ell__vec_reset(struct ell_vec_core* core, void** data)
  23. {
  24. assert(core != 0);
  25. assert(data != 0);
  26. if (*data != 0) {
  27. free(*data);
  28. }
  29. ell__vec_init(core, data);
  30. }
  31. void ell__vec_reserve(struct ell_vec_core* core, void** data, size_t element_size, size_t elements)
  32. {
  33. assert(core != 0);
  34. assert(data != 0);
  35. if (core->capacity < elements) {
  36. *data = realloc(*data, elements * element_size);
  37. core->capacity = elements;
  38. }
  39. }
  40. void ell__vec_resize(struct ell_vec_core* core, void** data, size_t element_size, size_t elements)
  41. {
  42. assert(core != 0);
  43. assert(data != 0);
  44. if (core->capacity < elements) {
  45. ell__vec_reserve(core, data, element_size, elements);
  46. }
  47. core->size = elements;
  48. }
  49. void ell__vec_fill_from_first(struct ell_vec_core* core, void* data, size_t element_size)
  50. {
  51. void* src = data;
  52. unsigned char* dst = ((unsigned char*)data) + element_size;
  53. for (size_t i = 1; i < core->size; i++) {
  54. memcpy(dst, src, element_size);
  55. dst += element_size;
  56. }
  57. }