SafePointerTest.cpp 1.7 KB

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