VolatileBufferFallback.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 "VolatileBuffer.h"
  5. #include "mozilla/Assertions.h"
  6. #include "mozilla/mozalloc.h"
  7. #ifdef MOZ_MEMORY
  8. int posix_memalign(void** memptr, size_t alignment, size_t size);
  9. #endif
  10. namespace mozilla {
  11. VolatileBuffer::VolatileBuffer()
  12. : mMutex("VolatileBuffer")
  13. , mBuf(nullptr)
  14. , mSize(0)
  15. , mLockCount(0)
  16. {
  17. }
  18. bool VolatileBuffer::Init(size_t aSize, size_t aAlignment)
  19. {
  20. MOZ_ASSERT(!mSize && !mBuf, "Init called twice");
  21. MOZ_ASSERT(!(aAlignment % sizeof(void *)),
  22. "Alignment must be multiple of pointer size");
  23. mSize = aSize;
  24. #if defined(MOZ_MEMORY)
  25. if (posix_memalign(&mBuf, aAlignment, aSize) != 0) {
  26. return false;
  27. }
  28. #elif defined(HAVE_POSIX_MEMALIGN)
  29. if (moz_posix_memalign(&mBuf, aAlignment, aSize) != 0) {
  30. return false;
  31. }
  32. #else
  33. #error "No memalign implementation found"
  34. #endif
  35. return !!mBuf;
  36. }
  37. VolatileBuffer::~VolatileBuffer()
  38. {
  39. MOZ_ASSERT(mLockCount == 0, "Being destroyed with non-zero lock count?");
  40. free(mBuf);
  41. }
  42. bool
  43. VolatileBuffer::Lock(void** aBuf)
  44. {
  45. MutexAutoLock lock(mMutex);
  46. MOZ_ASSERT(mBuf, "Attempting to lock an uninitialized VolatileBuffer");
  47. *aBuf = mBuf;
  48. mLockCount++;
  49. return true;
  50. }
  51. void
  52. VolatileBuffer::Unlock()
  53. {
  54. MutexAutoLock lock(mMutex);
  55. mLockCount--;
  56. MOZ_ASSERT(mLockCount >= 0, "VolatileBuffer unlocked too many times!");
  57. }
  58. bool
  59. VolatileBuffer::OnHeap() const
  60. {
  61. return true;
  62. }
  63. size_t
  64. VolatileBuffer::HeapSizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const
  65. {
  66. return aMallocSizeOf(mBuf);
  67. }
  68. size_t
  69. VolatileBuffer::NonHeapSizeOfExcludingThis() const
  70. {
  71. return 0;
  72. }
  73. } // namespace mozilla