utils.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #pragma once
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #define PK_REGION(name) 1
  5. #define PK_SLICE_LOOP(i, start, stop, step) \
  6. for(int i = start; step > 0 ? i < stop : i > stop; i += step)
  7. // global constants
  8. #define PK_HEX_TABLE "0123456789abcdef"
  9. #ifdef _MSC_VER
  10. #define c11__unreachable() __assume(0)
  11. #else
  12. #define c11__unreachable() __builtin_unreachable()
  13. #endif
  14. #define c11__abort(...) \
  15. do { \
  16. fprintf(stderr, __VA_ARGS__); \
  17. putchar('\n'); \
  18. abort(); \
  19. } while(0)
  20. #define c11__min(a, b) ((a) < (b) ? (a) : (b))
  21. #define c11__max(a, b) ((a) > (b) ? (a) : (b))
  22. #define c11__count_array(a) (sizeof(a) / sizeof(a[0]))
  23. // NARGS
  24. #define PK_NARGS_SEQ(_1, _2, _3, _4, N, ...) N
  25. #define PK_NARGS(...) PK_NARGS_SEQ(__VA_ARGS__, 4, 3, 2, 1, 0)
  26. #define PK_NPTRS(...) PK_NARGS_SEQ(__VA_ARGS__, int****, int***, int**, int*, int)
  27. // ref counting
  28. typedef struct RefCounted {
  29. int count;
  30. void (*dtor)(void*);
  31. } RefCounted;
  32. #define PK_INCREF(obj) (obj)->rc.count++
  33. #define PK_DECREF(obj) \
  34. do { \
  35. if(--(obj)->rc.count == 0) { \
  36. (obj)->rc.dtor(obj); \
  37. free(obj); \
  38. } \
  39. } while(0)