Utility.h 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 sleepNanos(i64 nanos);
  46. i64 getNanos(void);
  47. #define swap(a, b) \
  48. do { \
  49. auto aPointer = (a); \
  50. auto bPointer = (b); \
  51. auto tmp = *aPointer; \
  52. *aPointer = *bPointer; \
  53. *bPointer = tmp; \
  54. } while(0)
  55. #define BUBBLE_SORT(type, Type) void bubbleSort##Type(type* data, size_t n);
  56. #define BUBBLE_SORT_SOURCE(type, Type, greaterThan) \
  57. void bubbleSort##Type(type* data, size_t n) { \
  58. bool swapped = true; \
  59. while(swapped && n > 0) { \
  60. swapped = false; \
  61. n--; \
  62. for(size_t i = 0; i < n; i++) { \
  63. if(greaterThan(data[i], data[i + 1])) { \
  64. swap(data + i, data + i + 1); \
  65. swapped = true; \
  66. } \
  67. } \
  68. } \
  69. }
  70. #endif