SafePointerTest.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 
  2. #include "../testTools.h"
  3. #include "../../DFPSR/base/SafePointer.h"
  4. START_TEST(SafePointer)
  5. // Simulate unaligned memory
  6. const int elements = 100;
  7. const int dataSize = elements * sizeof(int32_t);
  8. const int alignment = 16;
  9. const int bufferSize = dataSize + alignment - 1;
  10. uint8_t allocation[3][bufferSize];
  11. // Run the algorithm for each byte offset relative to the alignment
  12. for (int offset = 0; offset < alignment; offset++) {
  13. // The SafePointer should be inlined into a raw pointer in relase mode while providing full bound checks in debug mode.
  14. SafePointer<int32_t> bufferA("bufferA", (int32_t*)(allocation[0] + offset), dataSize);
  15. SafePointer<int32_t> bufferB("bufferB", (int32_t*)(allocation[1] + offset), dataSize);
  16. SafePointer<int32_t> bufferC("bufferC", (int32_t*)(allocation[2] + offset), dataSize);
  17. // Initialize
  18. for (int i = 0; i < elements; i++) {
  19. bufferA[i] = i % 13;
  20. bufferB[i] = i % 7;
  21. bufferC[i] = 0;
  22. }
  23. // Calculate
  24. SafePointer<const int32_t> readerA = bufferA;
  25. SafePointer<const int32_t> readerB = bufferB;
  26. for (int i = 0; i < elements; i++) {
  27. bufferC[i] = (*readerA * *readerB) + 5;
  28. readerA += 1; readerB += 1;
  29. }
  30. // Check results
  31. int errors = 0;
  32. for (int i = 0; i < elements; i++) {
  33. if (bufferC[i] != ((i % 13) * (i % 7)) + 5) {
  34. errors++;
  35. }
  36. }
  37. ASSERT(errors == 0);
  38. // Make sure that array bounds are tested if they are turned on using the debug mode
  39. #ifdef SAFE_POINTER_CHECKS
  40. ASSERT_CRASH(bufferC[-1], U"SafePointer out of bound exception!");
  41. ASSERT_CRASH(bufferB[-65], U"SafePointer out of bound exception!");
  42. ASSERT_CRASH(bufferA[-245654], U"SafePointer out of bound exception!");
  43. ASSERT_CRASH(bufferA[elements], U"SafePointer out of bound exception!");
  44. ASSERT_CRASH(bufferA[elements + 1], U"SafePointer out of bound exception!");
  45. ASSERT_CRASH(bufferB[elements + 23], U"SafePointer out of bound exception!");
  46. ASSERT_CRASH(bufferC[elements + 673578], U"SafePointer out of bound exception!");
  47. #endif
  48. }
  49. #ifndef SAFE_POINTER_CHECKS
  50. #error "ERROR! SafePointer test ran without bound checks enabled!\n"
  51. #endif
  52. END_TEST