TestVolatileBuffer.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. #include "gtest/gtest.h"
  5. #include "mozilla/VolatileBuffer.h"
  6. #include <string.h>
  7. #ifdef XP_DARWIN
  8. #include <mach/mach.h>
  9. #endif
  10. using namespace mozilla;
  11. TEST(VolatileBufferTest, HeapVolatileBuffersWork)
  12. {
  13. RefPtr<VolatileBuffer> heapbuf = new VolatileBuffer();
  14. ASSERT_TRUE(heapbuf) << "Failed to create VolatileBuffer";
  15. ASSERT_TRUE(heapbuf->Init(512)) << "Failed to initialize VolatileBuffer";
  16. VolatileBufferPtr<char> ptr(heapbuf);
  17. EXPECT_FALSE(ptr.WasBufferPurged())
  18. << "Buffer should not be purged immediately after initialization";
  19. EXPECT_TRUE(ptr) << "Couldn't get pointer from VolatileBufferPtr";
  20. }
  21. TEST(VolatileBufferTest, RealVolatileBuffersWork)
  22. {
  23. RefPtr<VolatileBuffer> buf = new VolatileBuffer();
  24. ASSERT_TRUE(buf) << "Failed to create VolatileBuffer";
  25. ASSERT_TRUE(buf->Init(16384)) << "Failed to initialize VolatileBuffer";
  26. const char teststr[] = "foobar";
  27. {
  28. VolatileBufferPtr<char> ptr(buf);
  29. EXPECT_FALSE(ptr.WasBufferPurged())
  30. << "Buffer should not be purged immediately after initialization";
  31. EXPECT_TRUE(ptr) << "Couldn't get pointer from VolatileBufferPtr";
  32. {
  33. VolatileBufferPtr<char> ptr2(buf);
  34. EXPECT_FALSE(ptr.WasBufferPurged())
  35. << "Failed to lock buffer again while currently locked";
  36. ASSERT_TRUE(ptr2) << "Didn't get a pointer on the second lock";
  37. strcpy(ptr2, teststr);
  38. }
  39. }
  40. {
  41. VolatileBufferPtr<char> ptr(buf);
  42. EXPECT_FALSE(ptr.WasBufferPurged())
  43. << "Buffer was immediately purged after unlock";
  44. EXPECT_STREQ(ptr, teststr) << "Buffer failed to retain data after unlock";
  45. }
  46. // Test purging if we know how to
  47. #if defined(XP_DARWIN)
  48. int state;
  49. vm_purgable_control(mach_task_self(), (vm_address_t)NULL,
  50. VM_PURGABLE_PURGE_ALL, &state);
  51. #else
  52. return;
  53. #endif
  54. EXPECT_GT(buf->NonHeapSizeOfExcludingThis(), 0ul)
  55. << "Buffer should not be allocated on heap";
  56. {
  57. VolatileBufferPtr<char> ptr(buf);
  58. EXPECT_TRUE(ptr.WasBufferPurged())
  59. << "Buffer should not be unpurged after forced purge";
  60. EXPECT_STRNE(ptr, teststr) << "Purge did not actually purge data";
  61. }
  62. {
  63. VolatileBufferPtr<char> ptr(buf);
  64. EXPECT_FALSE(ptr.WasBufferPurged()) << "Buffer still purged after lock";
  65. }
  66. }