ds.c 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include "ds.h"
  2. #include <string.h>
  3. // super nifty site:
  4. // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
  5. static int inline nextPOT(int in) {
  6. in--;
  7. in |= in >> 1;
  8. in |= in >> 2;
  9. in |= in >> 4;
  10. in |= in >> 8;
  11. in |= in >> 16;
  12. in++;
  13. return in;
  14. }
  15. void vec_resize_to(void** data, size_t* size, size_t elem_size, size_t new_size) {
  16. void* tmp;
  17. if(*size >= new_size) return;
  18. *size *= nextPOT(new_size);
  19. tmp = realloc(*data, *size * elem_size);
  20. if(!tmp) {
  21. fprintf(stderr, "Out of memory in vector resize");
  22. return;
  23. }
  24. *data = tmp;
  25. }
  26. void vec_resize(void** data, size_t* size, size_t elem_size) {
  27. void* tmp;
  28. if(*size < 8) *size = 8;
  29. else *size *= 2;
  30. tmp = realloc(*data, *size * elem_size);
  31. if(!tmp) {
  32. fprintf(stderr, "Out of memory in vector resize");
  33. return;
  34. }
  35. *data = tmp;
  36. }
  37. ptrdiff_t vec_find(void* data, size_t len, size_t stride, void* search) {
  38. size_t i;
  39. for(i = 0; i < len; i++) {
  40. if(0 == memcmp(data + (i * stride), search, stride)) {
  41. return i;
  42. }
  43. }
  44. return -1;
  45. }