SafePointerTest.cpp 2.1 KB

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