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