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 
nsHtml5OwningUTF16Buffer(char16_t * aBuffer)7 nsHtml5OwningUTF16Buffer::nsHtml5OwningUTF16Buffer(char16_t* aBuffer)
8   : nsHtml5UTF16Buffer(aBuffer, 0),
9     next(nullptr),
10     key(nullptr)
11 {
12   MOZ_COUNT_CTOR(nsHtml5OwningUTF16Buffer);
13 }
14 
nsHtml5OwningUTF16Buffer(void * aKey)15 nsHtml5OwningUTF16Buffer::nsHtml5OwningUTF16Buffer(void* aKey)
16   : nsHtml5UTF16Buffer(nullptr, 0),
17     next(nullptr),
18     key(aKey)
19 {
20   MOZ_COUNT_CTOR(nsHtml5OwningUTF16Buffer);
21 }
22 
~nsHtml5OwningUTF16Buffer()23 nsHtml5OwningUTF16Buffer::~nsHtml5OwningUTF16Buffer()
24 {
25   MOZ_COUNT_DTOR(nsHtml5OwningUTF16Buffer);
26   DeleteBuffer();
27 
28   // This is to avoid dtor recursion on 'next', bug 706932.
29   RefPtr<nsHtml5OwningUTF16Buffer> tail;
30   tail.swap(next);
31   while (tail && tail->mRefCnt == 1) {
32     RefPtr<nsHtml5OwningUTF16Buffer> tmp;
33     tmp.swap(tail->next);
34     tail.swap(tmp);
35   }
36 }
37 
38 // static
39 already_AddRefed<nsHtml5OwningUTF16Buffer>
FalliblyCreate(int32_t aLength)40 nsHtml5OwningUTF16Buffer::FalliblyCreate(int32_t aLength)
41 {
42   char16_t* newBuf = new (mozilla::fallible) char16_t[aLength];
43   if (!newBuf) {
44     return nullptr;
45   }
46   RefPtr<nsHtml5OwningUTF16Buffer> newObj =
47     new (mozilla::fallible) nsHtml5OwningUTF16Buffer(newBuf);
48   if (!newObj) {
49     delete[] newBuf;
50     return nullptr;
51   }
52   return newObj.forget();
53 }
54 
55 void
Swap(nsHtml5OwningUTF16Buffer * aOther)56 nsHtml5OwningUTF16Buffer::Swap(nsHtml5OwningUTF16Buffer* aOther)
57 {
58   nsHtml5UTF16Buffer::Swap(aOther);
59 }
60 
61 
62 // Not using macros for AddRef and Release in order to be able to refcount on
63 // and create on different threads.
64 
65 nsrefcnt
AddRef()66 nsHtml5OwningUTF16Buffer::AddRef()
67 {
68   NS_PRECONDITION(int32_t(mRefCnt) >= 0, "Illegal refcount.");
69   ++mRefCnt;
70   NS_LOG_ADDREF(this, mRefCnt, "nsHtml5OwningUTF16Buffer", sizeof(*this));
71   return mRefCnt;
72 }
73 
74 nsrefcnt
Release()75 nsHtml5OwningUTF16Buffer::Release()
76 {
77   NS_PRECONDITION(0 != mRefCnt, "Release without AddRef.");
78   --mRefCnt;
79   NS_LOG_RELEASE(this, mRefCnt, "nsHtml5OwningUTF16Buffer");
80   if (mRefCnt == 0) {
81     mRefCnt = 1; /* stabilize */
82     delete this;
83     return 0;
84   }
85   return mRefCnt;
86 }
87