vec.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. // Public Domain.
  2. #include <stdlib.h> // realloc
  3. #include <string.h> // memcmp
  4. #include <stdio.h> // fprintf
  5. #include "vec.h"
  6. #ifndef STI_HAS_STATIC_nextPOT
  7. #define STI_HAS_STATIC_nextPOT
  8. // super nifty site:
  9. // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
  10. inline static size_t nextPOT(size_t in) {
  11. in--;
  12. in |= in >> 1;
  13. in |= in >> 2;
  14. in |= in >> 4;
  15. in |= in >> 8;
  16. in |= in >> 16;
  17. in++;
  18. return in;
  19. }
  20. #endif
  21. void vec_resize_to(void** data, size_t* size, size_t elem_size, size_t new_size) {
  22. void* tmp;
  23. if(*size >= new_size) return;
  24. *size = nextPOT(new_size);
  25. tmp = realloc(*data, *size * elem_size);
  26. if(!tmp) {
  27. fprintf(stderr, "Out of memory in vector resize, %ld bytes requested\n", *size);
  28. return;
  29. }
  30. *data = tmp;
  31. }
  32. void vec_resize(void** data, size_t* size, size_t elem_size) {
  33. void* tmp;
  34. if(*size < 8) *size = 8;
  35. else *size *= 2;
  36. tmp = realloc(*data, *size * elem_size);
  37. if(!tmp) {
  38. fprintf(stderr, "Out of memory in vector resize");
  39. return;
  40. }
  41. *data = tmp;
  42. }
  43. ptrdiff_t vec_find(void* data, size_t len, size_t stride, void* search) {
  44. size_t i;
  45. for(i = 0; i < len; i++) {
  46. if(0 == memcmp((char*)data + (i * stride), search, stride)) {
  47. return i;
  48. }
  49. }
  50. return -1;
  51. }
  52. ptrdiff_t vec_rm_val(char* data, size_t* len, size_t stride, void* search) {
  53. size_t i;
  54. for(i = 0; i < *len; i++) {
  55. if(0 == memcmp(data + (i * stride), search, stride)) {
  56. if(i < *len) {
  57. memcpy(data + (i * stride), data + ((*len - 1) * stride), stride);
  58. }
  59. (*len)--;
  60. return 0;
  61. }
  62. }
  63. return 1;
  64. }
  65. void vec_copy(
  66. char** dst_data, char* src_data,
  67. size_t* dst_alloc, size_t src_alloc,
  68. size_t* dst_len, size_t src_len,
  69. size_t elem_size
  70. ) {
  71. if(*dst_alloc < src_alloc) {
  72. *dst_alloc = src_alloc;
  73. if(*dst_alloc == 0) {
  74. *dst_data = malloc(elem_size * src_alloc);
  75. }
  76. else {
  77. *dst_data = realloc(*dst_data, elem_size * src_alloc);
  78. }
  79. }
  80. *dst_len = src_len;
  81. memcpy(*dst_data, src_data, elem_size * src_len);
  82. }