Utility.h 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #ifndef CORE_UTILITY_H
  2. #define CORE_UTILITY_H
  3. #include <string.h>
  4. #include "core/Types.h"
  5. size_t popCount(u64 u);
  6. #define interpolate(a, b, factor) ((a) * (1.0f - (factor)) + (b) * (factor))
  7. #define PI 3.14159265358979323846f
  8. #define radianToDegree(radians) ((radians) * (180.0f / PI))
  9. #define degreeToRadian(degrees) ((degrees) * (PI / 180.0f))
  10. inline size_t maxSize(size_t a, size_t b) {
  11. return a > b ? a : b;
  12. }
  13. inline size_t minSize(size_t a, size_t b) {
  14. return a < b ? a : b;
  15. }
  16. typedef void (*ExitHandler)(int, void*);
  17. [[noreturn]] void exitWithHandler(const char* file, int line, int value);
  18. void setExitHandler(ExitHandler h, void* data);
  19. #define EXIT(exitValue) exitWithHandler(__FILE__, __LINE__, exitValue)
  20. typedef void (*OutOfMemoryHandler)(void*);
  21. void setOutOfMemoryHandler(OutOfMemoryHandler h, void* data);
  22. #ifdef CHECK_MEMORY
  23. void* coreDebugAllocate(const char* file, int line, size_t n);
  24. void* coreDebugReallocate(const char* file, int line, void* p, size_t n);
  25. void coreFreeDebug(const char* file, int line, void* p);
  26. void printMemoryReport(void);
  27. #define coreAllocate(n) coreDebugAllocate(__FILE__, __LINE__, n)
  28. #define coreReallocate(p, n) coreDebugReallocate(__FILE__, __LINE__, p, n)
  29. #define coreFree(p) coreFreeDebug(__FILE__, __LINE__, p)
  30. #else
  31. void* coreAllocate(size_t n);
  32. void* coreReallocate(void* p, size_t n);
  33. void coreFree(void* p);
  34. #define printMemoryReport()
  35. #endif
  36. bool sleepNanos(i64 nanos);
  37. i64 getNanos(void);
  38. // TODO: replace typeof with auto when available
  39. #define swap(a, b) \
  40. do { \
  41. typeof(a) aPointer = (a); \
  42. typeof(b) bPointer = (b); \
  43. typeof(*aPointer) tmp = *aPointer; \
  44. *aPointer = *bPointer; \
  45. *bPointer = tmp; \
  46. } while(0)
  47. #define BUBBLE_SORT(type, Type) void bubbleSort##Type(type* data, size_t n);
  48. #define BUBBLE_SORT_SOURCE(type, Type, greaterThan) \
  49. void bubbleSort##Type(type* data, size_t n) { \
  50. bool swapped = true; \
  51. while(swapped && n > 0) { \
  52. swapped = false; \
  53. n--; \
  54. for(size_t i = 0; i < n; i++) { \
  55. if(greaterThan(data[i], data[i + 1])) { \
  56. swap(data + i, data + i + 1); \
  57. swapped = true; \
  58. } \
  59. } \
  60. } \
  61. }
  62. #endif