svec.c 983 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include "svec.h"
  2. void svec_resize(struct svec_base_props* base, size_t elem_size, size_t chunk_size) {
  3. if(base->chunksLen >= base->chunksAlloc) {
  4. if(base->chunksAlloc == 0) base->chunksAlloc = 16;
  5. else base->chunksAlloc *= 2;
  6. base->data = realloc(base->data, base->chunksAlloc * sizeof(void*));
  7. }
  8. base->data[base->chunksLen++] = malloc(chunk_size * elem_size);
  9. base->alloc += chunk_size;
  10. }
  11. long svec_pointer_index(struct svec_base_props* base, size_t elem_size, size_t chunk_size, void* ptr) {
  12. for(long c = 0; c < base->chunksLen; c++) {
  13. if(ptr >= base->data[c] && ptr <= base->data[c] + (chunk_size * elem_size)) {
  14. return ((ptr - base->data[c]) / elem_size) + (c * chunk_size * elem_size);
  15. }
  16. }
  17. return -1;
  18. }
  19. void svec_free(struct svec_base_props* base) {
  20. for(long i = 0; i < base->chunksLen; i++) {
  21. free(base->data[i]);
  22. }
  23. free(base->data);
  24. base->chunksAlloc = 0;
  25. base->chunksLen = 0;
  26. base->len = 0;
  27. base->alloc = 0;
  28. }