stretchy_buffer.txt 1.1 KB

1234567891011121314151617181920212223242526272829
  1. // stretchy buffer // init: NULL // free: sbfree() // push_back: sbpush() // size: sbcount() //
  2. #define sbfree(a) ((a) ? free(stb__sbraw(a)),0 : 0)
  3. #define sbpush(a,v) (stb__sbmaybegrow(a,1), (a)[stb__sbn(a)++] = (v))
  4. #define sbcount(a) ((a) ? stb__sbn(a) : 0)
  5. #define sbadd(a,n) (stb__sbmaybegrow(a,n), stb__sbn(a)+=(n), &(a)[stb__sbn(a)-(n)])
  6. #define sblast(a) ((a)[stb__sbn(a)-1])
  7. #include <stdlib.h>
  8. #define stb__sbraw(a) ((int *) (a) - 2)
  9. #define stb__sbm(a) stb__sbraw(a)[0]
  10. #define stb__sbn(a) stb__sbraw(a)[1]
  11. #define stb__sbneedgrow(a,n) ((a)==0 || stb__sbn(a)+n >= stb__sbm(a))
  12. #define stb__sbmaybegrow(a,n) (stb__sbneedgrow(a,(n)) ? stb__sbgrow(a,n) : 0)
  13. #define stb__sbgrow(a,n) stb__sbgrowf((void **) &(a), (n), sizeof(*(a)))
  14. static void stb__sbgrowf(void **arr, int increment, int itemsize)
  15. {
  16. int m = *arr ? 2*stb__sbm(*arr)+increment : increment+1;
  17. void *p = realloc(*arr ? stb__sbraw(*arr) : 0, itemsize * m + sizeof(int)*2);
  18. assert(p);
  19. if (p) {
  20. if (!*arr) ((int *) p)[1] = 0;
  21. *arr = (void *) ((int *) p + 2);
  22. stb__sbm(*arr) = m;
  23. }
  24. }