1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4 
5 #include "nsHtml5OwningUTF16Buffer.h"
6 
7 #include "mozilla/Span.h"
8 
9 using namespace mozilla;
10 
nsHtml5OwningUTF16Buffer(char16_t * aBuffer)11 nsHtml5OwningUTF16Buffer::nsHtml5OwningUTF16Buffer(char16_t* aBuffer)
12     : nsHtml5UTF16Buffer(aBuffer, 0), next(nullptr), key(nullptr) {}
13 
nsHtml5OwningUTF16Buffer(void * aKey)14 nsHtml5OwningUTF16Buffer::nsHtml5OwningUTF16Buffer(void* aKey)
15     : nsHtml5UTF16Buffer(nullptr, 0), next(nullptr), key(aKey) {}
16 
~nsHtml5OwningUTF16Buffer()17 nsHtml5OwningUTF16Buffer::~nsHtml5OwningUTF16Buffer() {
18   DeleteBuffer();
19 
20   // This is to avoid dtor recursion on 'next', bug 706932.
21   RefPtr<nsHtml5OwningUTF16Buffer> tail;
22   tail.swap(next);
23   while (tail && tail->mRefCnt == 1) {
24     RefPtr<nsHtml5OwningUTF16Buffer> tmp;
25     tmp.swap(tail->next);
26     tail.swap(tmp);
27   }
28 }
29 
30 // static
31 already_AddRefed<nsHtml5OwningUTF16Buffer>
FalliblyCreate(int32_t aLength)32 nsHtml5OwningUTF16Buffer::FalliblyCreate(int32_t aLength) {
33   char16_t* newBuf = new (mozilla::fallible) char16_t[aLength];
34   if (!newBuf) {
35     return nullptr;
36   }
37   RefPtr<nsHtml5OwningUTF16Buffer> newObj =
38       new (mozilla::fallible) nsHtml5OwningUTF16Buffer(newBuf);
39   if (!newObj) {
40     delete[] newBuf;
41     return nullptr;
42   }
43   return newObj.forget();
44 }
45 
Swap(nsHtml5OwningUTF16Buffer * aOther)46 void nsHtml5OwningUTF16Buffer::Swap(nsHtml5OwningUTF16Buffer* aOther) {
47   nsHtml5UTF16Buffer::Swap(aOther);
48 }
49 
TailAsSpan(int32_t aBufferSize)50 Span<char16_t> nsHtml5OwningUTF16Buffer::TailAsSpan(int32_t aBufferSize) {
51   MOZ_ASSERT(aBufferSize >= getEnd());
52   return {getBuffer() + getEnd(), static_cast<size_t>(aBufferSize - getEnd())};
53 }
54 
AdvanceEnd(int32_t aNumberOfCodeUnits)55 void nsHtml5OwningUTF16Buffer::AdvanceEnd(int32_t aNumberOfCodeUnits) {
56   setEnd(getEnd() + aNumberOfCodeUnits);
57 }
58 
59 // Not using macros for AddRef and Release in order to be able to refcount on
60 // and create on different threads.
61 
AddRef()62 nsrefcnt nsHtml5OwningUTF16Buffer::AddRef() {
63   MOZ_ASSERT(int32_t(mRefCnt) >= 0, "Illegal refcount.");
64   ++mRefCnt;
65   NS_LOG_ADDREF(this, mRefCnt, "nsHtml5OwningUTF16Buffer", sizeof(*this));
66   return mRefCnt;
67 }
68 
Release()69 nsrefcnt nsHtml5OwningUTF16Buffer::Release() {
70   MOZ_ASSERT(0 != mRefCnt, "Release without AddRef.");
71   --mRefCnt;
72   NS_LOG_RELEASE(this, mRefCnt, "nsHtml5OwningUTF16Buffer");
73   if (mRefCnt == 0) {
74     mRefCnt = 1; /* stabilize */
75     delete this;
76     return 0;
77   }
78   return mRefCnt;
79 }
80