UtilityTests.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include <stdlib.h>
  2. #include "../../src/ErrorSimulator.hpp"
  3. #include "../Tests.hpp"
  4. #include "core/utils/Utility.hpp"
  5. static void testPopCount() {
  6. CORE_TEST_EQUAL(4, Core::popCount(0xF));
  7. CORE_TEST_EQUAL(0, Core::popCount(0x0));
  8. CORE_TEST_EQUAL(2, Core::popCount(0x6));
  9. CORE_TEST_EQUAL(7, Core::popCount(0x7F));
  10. CORE_TEST_EQUAL(3, Core::popCount(0x2A));
  11. CORE_TEST_EQUAL(32, Core::popCount(0xFFFFFFFF));
  12. CORE_TEST_EQUAL(64, Core::popCount(0xFFFFFFFFFFFFFFFFL));
  13. CORE_TEST_EQUAL(44, Core::popCount(0xFFFF0FFFFFFF));
  14. CORE_TEST_EQUAL(32, Core::popCount(-1));
  15. }
  16. static void testIf() {
  17. CORE_TEST_TRUE((Core::IsSame<Core::If<true, int, double>, int>));
  18. CORE_TEST_TRUE((Core::IsSame<Core::If<false, int, double>, double>));
  19. }
  20. static void onOutOfMemory(void* p) {
  21. *static_cast<bool*>(p) = true;
  22. }
  23. static void testAllocateFail() {
  24. #ifdef ERROR_SIMULATOR
  25. Core::Fail::alloc = true;
  26. bool check = false;
  27. Core::setOutOfMemoryHandler(onOutOfMemory, &check);
  28. void* p = Core::allocate(16);
  29. CORE_TEST_NOT_NULL(p);
  30. CORE_TEST_TRUE(check);
  31. Core::Fail::alloc = false;
  32. Core::setOutOfMemoryHandler(nullptr, nullptr);
  33. free(p);
  34. #endif
  35. }
  36. static void testZeroRellocate() {
  37. void* buffer = Core::reallocate(nullptr, 16);
  38. CORE_TEST_NOT_NULL(buffer);
  39. buffer = Core::reallocate(buffer, 0);
  40. CORE_TEST_NULL(buffer);
  41. }
  42. static void testReallocateFail() {
  43. #ifdef ERROR_SIMULATOR
  44. Core::Fail::alloc = true;
  45. bool check = false;
  46. Core::setOutOfMemoryHandler(onOutOfMemory, &check);
  47. void* p = Core::reallocate(nullptr, 16);
  48. CORE_TEST_NOT_NULL(p);
  49. CORE_TEST_TRUE(check);
  50. Core::Fail::alloc = false;
  51. Core::setOutOfMemoryHandler(nullptr, nullptr);
  52. free(p);
  53. #endif
  54. }
  55. void Core::testUtility() {
  56. testPopCount();
  57. testIf();
  58. testAllocateFail();
  59. testZeroRellocate();
  60. testReallocateFail();
  61. }