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 
6 #ifndef MOZILLA_SHAREDBUFFER_H_
7 #define MOZILLA_SHAREDBUFFER_H_
8 
9 #include "mozilla/CheckedInt.h"
10 #include "mozilla/mozalloc.h"
11 #include "nsCOMPtr.h"
12 
13 namespace mozilla {
14 
15 class AudioBlockBuffer;
16 
17 /**
18  * Base class for objects with a thread-safe refcount and a virtual
19  * destructor.
20  */
21 class ThreadSharedObject {
22 public:
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(ThreadSharedObject)23   NS_INLINE_DECL_THREADSAFE_REFCOUNTING(ThreadSharedObject)
24 
25   bool IsShared() { return mRefCnt.get() > 1; }
26 
AsAudioBlockBuffer()27   virtual AudioBlockBuffer* AsAudioBlockBuffer() { return nullptr; };
28 
SizeOfExcludingThis(MallocSizeOf aMallocSizeOf)29   virtual size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const
30   {
31     return 0;
32   }
33 
SizeOfIncludingThis(MallocSizeOf aMallocSizeOf)34   virtual size_t SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const
35   {
36     return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
37   }
38 protected:
39   // Protected destructor, to discourage deletion outside of Release():
~ThreadSharedObject()40   virtual ~ThreadSharedObject() {}
41 };
42 
43 /**
44  * Heap-allocated chunk of arbitrary data with threadsafe refcounting.
45  * Typically you would allocate one of these, fill it in, and then treat it as
46  * immutable while it's shared.
47  * This only guarantees 4-byte alignment of the data. For alignment we simply
48  * assume that the memory from malloc is at least 4-byte aligned and the
49  * refcount's size is large enough that SharedBuffer's size is divisible by 4.
50  */
51 class SharedBuffer : public ThreadSharedObject {
52 public:
Data()53   void* Data() { return this + 1; }
54 
Create(size_t aSize)55   static already_AddRefed<SharedBuffer> Create(size_t aSize)
56   {
57     CheckedInt<size_t> size = sizeof(SharedBuffer);
58     size += aSize;
59     if (!size.isValid()) {
60       MOZ_CRASH();
61     }
62     void* m = moz_xmalloc(size.value());
63     RefPtr<SharedBuffer> p = new (m) SharedBuffer();
64     NS_ASSERTION((reinterpret_cast<char*>(p.get() + 1) - reinterpret_cast<char*>(p.get())) % 4 == 0,
65                  "SharedBuffers should be at least 4-byte aligned");
66     return p.forget();
67   }
68 
SizeOfIncludingThis(MallocSizeOf aMallocSizeOf)69   size_t SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const override
70   {
71     return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
72   }
73 
74 private:
SharedBuffer()75   SharedBuffer() {}
76 };
77 
78 } // namespace mozilla
79 
80 #endif /* MOZILLA_SHAREDBUFFER_H_ */
81