SafePointerTest.cpp 1.8 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. // Make sure that array bounds are tested if they are turned on using the debug mode
  17. #ifdef SAFE_POINTER_CHECKS
  18. ASSERT_CRASH(bufferA[-245654]);
  19. ASSERT_CRASH(bufferB[-65]);
  20. ASSERT_CRASH(bufferC[-1]);
  21. ASSERT_CRASH(bufferA[elements]);
  22. ASSERT_CRASH(bufferB[elements + 23]);
  23. ASSERT_CRASH(bufferC[elements + 673578]);
  24. #endif
  25. // Initialize
  26. for (int i = 0; i < elements; i++) {
  27. bufferA[i] = i % 13;
  28. bufferB[i] = i % 7;
  29. bufferC[i] = 0;
  30. }
  31. // Calculate
  32. const SafePointer<int32_t> readerA = bufferA;
  33. const SafePointer<int32_t> readerB = bufferB;
  34. for (int i = 0; i < elements; i++) {
  35. bufferC[i] = (*readerA * *readerB) + 5;
  36. readerA += 1; readerB += 1;
  37. }
  38. // Check results
  39. int errors = 0;
  40. for (int i = 0; i < elements; i++) {
  41. if (bufferC[i] != ((i % 13) * (i % 7)) + 5) {
  42. errors++;
  43. }
  44. }
  45. ASSERT(errors == 0);
  46. }
  47. #ifndef SAFE_POINTER_CHECKS
  48. printf("WARNING! SafePointer test ran without bound checks enabled.\n");
  49. #endif
  50. END_TEST