SharedBuffer.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  4. * You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #ifndef MOZILLA_SHAREDBUFFER_H_
  6. #define MOZILLA_SHAREDBUFFER_H_
  7. #include "mozilla/CheckedInt.h"
  8. #include "mozilla/mozalloc.h"
  9. #include "nsCOMPtr.h"
  10. namespace mozilla {
  11. class AudioBlockBuffer;
  12. /**
  13. * Base class for objects with a thread-safe refcount and a virtual
  14. * destructor.
  15. */
  16. class ThreadSharedObject {
  17. public:
  18. NS_INLINE_DECL_THREADSAFE_REFCOUNTING(ThreadSharedObject)
  19. bool IsShared() { return mRefCnt.get() > 1; }
  20. virtual AudioBlockBuffer* AsAudioBlockBuffer() { return nullptr; };
  21. virtual size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const
  22. {
  23. return 0;
  24. }
  25. virtual size_t SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const
  26. {
  27. return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
  28. }
  29. protected:
  30. // Protected destructor, to discourage deletion outside of Release():
  31. virtual ~ThreadSharedObject() {}
  32. };
  33. /**
  34. * Heap-allocated chunk of arbitrary data with threadsafe refcounting.
  35. * Typically you would allocate one of these, fill it in, and then treat it as
  36. * immutable while it's shared.
  37. * This only guarantees 4-byte alignment of the data. For alignment we simply
  38. * assume that the memory from malloc is at least 4-byte aligned and the
  39. * refcount's size is large enough that SharedBuffer's size is divisible by 4.
  40. */
  41. class SharedBuffer : public ThreadSharedObject {
  42. public:
  43. void* Data() { return this + 1; }
  44. static already_AddRefed<SharedBuffer> Create(size_t aSize)
  45. {
  46. CheckedInt<size_t> size = sizeof(SharedBuffer);
  47. size += aSize;
  48. if (!size.isValid()) {
  49. MOZ_CRASH();
  50. }
  51. void* m = moz_xmalloc(size.value());
  52. RefPtr<SharedBuffer> p = new (m) SharedBuffer();
  53. NS_ASSERTION((reinterpret_cast<char*>(p.get() + 1) - reinterpret_cast<char*>(p.get())) % 4 == 0,
  54. "SharedBuffers should be at least 4-byte aligned");
  55. return p.forget();
  56. }
  57. size_t SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const override
  58. {
  59. return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
  60. }
  61. private:
  62. SharedBuffer() {}
  63. };
  64. } // namespace mozilla
  65. #endif /* MOZILLA_SHAREDBUFFER_H_ */