1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/content/media/SharedBuffer.h Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,77 @@ 1.4 +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 1.5 +/* This Source Code Form is subject to the terms of the Mozilla Public 1.6 + * License, v. 2.0. If a copy of the MPL was not distributed with this file, 1.7 + * You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.8 + 1.9 +#ifndef MOZILLA_SHAREDBUFFER_H_ 1.10 +#define MOZILLA_SHAREDBUFFER_H_ 1.11 + 1.12 +#include "mozilla/CheckedInt.h" 1.13 +#include "mozilla/mozalloc.h" 1.14 +#include "nsCOMPtr.h" 1.15 +#include "nsAutoPtr.h" 1.16 + 1.17 +namespace mozilla { 1.18 + 1.19 +/** 1.20 + * Base class for objects with a thread-safe refcount and a virtual 1.21 + * destructor. 1.22 + */ 1.23 +class ThreadSharedObject { 1.24 +public: 1.25 + NS_INLINE_DECL_THREADSAFE_REFCOUNTING(ThreadSharedObject) 1.26 + 1.27 + bool IsShared() { return mRefCnt.get() > 1; } 1.28 + 1.29 + virtual size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const 1.30 + { 1.31 + return 0; 1.32 + } 1.33 + 1.34 + virtual size_t SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const 1.35 + { 1.36 + return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf); 1.37 + } 1.38 +protected: 1.39 + // Protected destructor, to discourage deletion outside of Release(): 1.40 + virtual ~ThreadSharedObject() {} 1.41 +}; 1.42 + 1.43 +/** 1.44 + * Heap-allocated chunk of arbitrary data with threadsafe refcounting. 1.45 + * Typically you would allocate one of these, fill it in, and then treat it as 1.46 + * immutable while it's shared. 1.47 + * This only guarantees 4-byte alignment of the data. For alignment we 1.48 + * simply assume that the refcount is at least 4-byte aligned and its size 1.49 + * is divisible by 4. 1.50 + */ 1.51 +class SharedBuffer : public ThreadSharedObject { 1.52 +public: 1.53 + void* Data() { return this + 1; } 1.54 + 1.55 + static already_AddRefed<SharedBuffer> Create(size_t aSize) 1.56 + { 1.57 + CheckedInt<size_t> size = sizeof(SharedBuffer); 1.58 + size += aSize; 1.59 + if (!size.isValid()) { 1.60 + MOZ_CRASH(); 1.61 + } 1.62 + void* m = moz_xmalloc(size.value()); 1.63 + nsRefPtr<SharedBuffer> p = new (m) SharedBuffer(); 1.64 + NS_ASSERTION((reinterpret_cast<char*>(p.get() + 1) - reinterpret_cast<char*>(p.get())) % 4 == 0, 1.65 + "SharedBuffers should be at least 4-byte aligned"); 1.66 + return p.forget(); 1.67 + } 1.68 + 1.69 + virtual size_t SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const MOZ_OVERRIDE 1.70 + { 1.71 + return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf); 1.72 + } 1.73 + 1.74 +private: 1.75 + SharedBuffer() {} 1.76 +}; 1.77 + 1.78 +} 1.79 + 1.80 +#endif /* MOZILLA_SHAREDBUFFER_H_ */