utils.h 2.2 KB

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