Utility.h 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. #define MIN_MAX(type, name) \
  11. inline type max##name(type a, type b) { \
  12. return a > b ? a : b; \
  13. } \
  14. inline type min##name(type a, type b) { \
  15. return a < b ? a : b; \
  16. } \
  17. inline type clamp##name(type t, type from, type to) { \
  18. return max##name(min##name(t, to), from); \
  19. }
  20. MIN_MAX(size_t, Size)
  21. MIN_MAX(u32, U32)
  22. typedef void (*ExitHandler)(int, void*);
  23. [[noreturn]] void exitWithHandler(const char* file, int line, int value);
  24. void setExitHandler(ExitHandler h, void* data);
  25. #define EXIT(exitValue) exitWithHandler(__FILE__, __LINE__, exitValue)
  26. typedef void (*OutOfMemoryHandler)(void*);
  27. void setOutOfMemoryHandler(OutOfMemoryHandler h, void* data);
  28. #ifdef CHECK_MEMORY
  29. void* coreDebugAllocate(const char* file, int line, size_t n);
  30. void* coreDebugZeroAllocate(const char* file, int line, size_t n);
  31. void* coreDebugReallocate(const char* file, int line, void* p, size_t n);
  32. void coreFreeDebug(const char* file, int line, void* p);
  33. void printMemoryReport(void);
  34. #define coreAllocate(n) coreDebugAllocate(__FILE__, __LINE__, n)
  35. #define coreZeroAllocate(n) coreDebugZeroAllocate(__FILE__, __LINE__, n)
  36. #define coreReallocate(p, n) coreDebugReallocate(__FILE__, __LINE__, p, n)
  37. #define coreFree(p) coreFreeDebug(__FILE__, __LINE__, p)
  38. #else
  39. void* coreAllocate(size_t n);
  40. void* coreZeroAllocate(size_t n);
  41. void* coreReallocate(void* p, size_t n);
  42. void coreFree(void* p);
  43. #define printMemoryReport()
  44. #endif
  45. bool sleepMillis(i64 millis);
  46. bool sleepNanos(i64 nanos);
  47. i64 getNanos(void);
  48. #define swap(a, b) \
  49. do { \
  50. auto aPointer = (a); \
  51. auto bPointer = (b); \
  52. auto tmp = *aPointer; \
  53. *aPointer = *bPointer; \
  54. *bPointer = tmp; \
  55. } while(0)
  56. #define BUBBLE_SORT(type, Type) void bubbleSort##Type(type* data, size_t n);
  57. #define BUBBLE_SORT_SOURCE(type, Type, greaterThan) \
  58. void bubbleSort##Type(type* data, size_t n) { \
  59. bool swapped = true; \
  60. while(swapped && n > 0) { \
  61. swapped = false; \
  62. n--; \
  63. for(size_t i = 0; i < n; i++) { \
  64. if(greaterThan(data[i], data[i + 1])) { \
  65. swap(data + i, data + i + 1); \
  66. swapped = true; \
  67. } \
  68. } \
  69. } \
  70. }
  71. #endif