Utility.cppm 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. module;
  2. #include <cstddef>
  3. #include <source_location>
  4. export module Core.Utility;
  5. import Core.Meta;
  6. #define SOURCE const std::source_location& l = std::source_location::current()
  7. export namespace std {
  8. using std::source_location;
  9. }
  10. #ifdef CHECK_MEMORY
  11. export void* operator new(size_t count, const std::source_location& l);
  12. export void* operator new[](size_t count, const std::source_location& l);
  13. #endif
  14. export using ::operator new;
  15. export namespace Core {
  16. template<typename T, typename C = int>
  17. C popCount(const T& t) {
  18. static constexpr C map[16] = {0, 1, 1, 2, 1, 2, 2, 3,
  19. 1, 2, 2, 3, 2, 3, 3, 4};
  20. C sum = 0;
  21. for(size_t i = 0; i < sizeof(T) * 8; i += 4) {
  22. sum += map[(t >> i) & 0xF];
  23. }
  24. return sum;
  25. }
  26. using ExitHandler = void (*)(int, void*);
  27. [[noreturn]] void exitWithHandler(int value, SOURCE);
  28. void setExitHandler(ExitHandler h, void* data);
  29. using OutOfMemoryHandler = void (*)(void*);
  30. void setOutOfMemoryHandler(OutOfMemoryHandler h, void* data);
  31. #ifdef CHECK_MEMORY
  32. void* allocateRaw(size_t n, SOURCE);
  33. void* zeroAllocateRaw(size_t n, SOURCE);
  34. void* reallocateRaw(void* p, size_t n, SOURCE);
  35. void deallocateRaw(void* p, SOURCE);
  36. template<typename T, typename... Args>
  37. T* newWithSource(Args&&... args) {
  38. return new(std::source_location::current())
  39. T(Core::forward<Args>(args)...);
  40. }
  41. template<typename T>
  42. T* newWithSourceN(size_t n) {
  43. return new(std::source_location::current()) T[n];
  44. }
  45. #else
  46. void* allocateRaw(size_t n);
  47. void* zeroAllocateRaw(size_t n);
  48. void* reallocateRaw(void* p, size_t n);
  49. void deallocateRaw(void* p);
  50. template<typename T, typename... Args>
  51. T* newWithSource(Args&&... args) {
  52. return new T(Core::forward<Args>(args)...);
  53. }
  54. template<typename T>
  55. T* newWithSourceN(size_t n) {
  56. return new T[n];
  57. }
  58. #endif
  59. void printMemoryReport();
  60. template<typename T>
  61. void deleteWithSource(T* p) {
  62. delete p;
  63. }
  64. template<typename T>
  65. void deleteWithSourceN(T* p) {
  66. delete[] p;
  67. }
  68. template<typename T>
  69. void bubbleSort(T* data, size_t n) {
  70. bool swapped = true;
  71. while(swapped && n > 0) {
  72. swapped = false;
  73. n--;
  74. for(size_t i = 0; i < n; i++) {
  75. if(data[i] > data[i + 1]) {
  76. swap(data[i], data[i + 1]);
  77. swapped = true;
  78. }
  79. }
  80. }
  81. }
  82. }