Line data Source code
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 0 : class ThreadSharedObject {
22 : public:
23 0 : NS_INLINE_DECL_THREADSAFE_REFCOUNTING(ThreadSharedObject)
24 :
25 0 : bool IsShared() { return mRefCnt.get() > 1; }
26 :
27 0 : virtual AudioBlockBuffer* AsAudioBlockBuffer() { return nullptr; };
28 :
29 0 : virtual size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const
30 : {
31 0 : return 0;
32 : }
33 :
34 0 : virtual size_t SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const
35 : {
36 0 : return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
37 : }
38 : protected:
39 : // Protected destructor, to discourage deletion outside of Release():
40 0 : 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 0 : class SharedBuffer : public ThreadSharedObject {
52 : public:
53 0 : void* Data() { return this + 1; }
54 :
55 0 : static already_AddRefed<SharedBuffer> Create(size_t aSize)
56 : {
57 0 : CheckedInt<size_t> size = sizeof(SharedBuffer);
58 0 : size += aSize;
59 0 : if (!size.isValid()) {
60 0 : MOZ_CRASH();
61 : }
62 0 : void* m = moz_xmalloc(size.value());
63 0 : RefPtr<SharedBuffer> p = new (m) SharedBuffer();
64 0 : 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 0 : return p.forget();
67 : }
68 :
69 0 : size_t SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const override
70 : {
71 0 : return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
72 : }
73 :
74 : private:
75 0 : SharedBuffer() {}
76 : };
77 :
78 : } // namespace mozilla
79 :
80 : #endif /* MOZILLA_SHAREDBUFFER_H_ */
|