Bug 550611: Make nsTArray optionally infallible. sr=bsmedberg a=blocking

--HG--
rename : xpcom/glue/nsTArray.cpp => xpcom/glue/nsTArray-inl.h
This commit is contained in:
Chris Jones 2010-11-08 20:48:59 -06:00
Родитель a3e7d64ff6
Коммит 52d0f01838
18 изменённых файлов: 1432 добавлений и 1188 удалений

Просмотреть файл

@ -738,7 +738,7 @@ public:
nsSlots* s = GetSlots();
if (s) {
NS_ASSERTION(s->mMutationObservers.IndexOf(aMutationObserver) ==
nsTArray_base::NoIndex,
nsTArray<int>::NoIndex,
"Observer already in the list");
s->mMutationObservers.AppendElement(aMutationObserver);
}

Просмотреть файл

@ -58,8 +58,9 @@ class nsIAtom;
class nsICSSStyleRule;
class nsISVGValue;
class nsIDocument;
template<class E> class nsTArray;
template<class E> class nsTPtrArray;
template<class E, class A> class nsTArray;
template<class E, class A> class nsTPtrArray;
struct nsTArrayDefaultAllocator;
#define NS_ATTRVALUE_MAX_STRINGLENGTH_ATOM 12
@ -381,7 +382,7 @@ private:
PRBool aCanBePercent = PR_FALSE,
PRBool* aIsPercent = nsnull) const;
static nsTPtrArray<const EnumTable>* sEnumTableArray;
static nsTPtrArray<const EnumTable, nsTArrayDefaultAllocator>* sEnumTableArray;
PtrBits mBits;
};

Просмотреть файл

@ -205,6 +205,8 @@ static NS_DEFINE_CID(kDOMEventGroupCID, NS_DOMEVENTGROUP_CID);
using namespace mozilla::dom;
typedef nsTArray<Link*> LinkArray;
#ifdef PR_LOGGING
static PRLogModuleInfo* gDocumentLeakPRLog;
@ -3902,7 +3904,7 @@ nsDocument::InternalAllowXULXBL()
void
nsDocument::AddObserver(nsIDocumentObserver* aObserver)
{
NS_ASSERTION(mObservers.IndexOf(aObserver) == nsTArray_base::NoIndex,
NS_ASSERTION(mObservers.IndexOf(aObserver) == nsTArray<int>::NoIndex,
"Observer already in the list");
mObservers.AppendElement(aObserver);
AddMutationObserver(aObserver);
@ -7546,7 +7548,7 @@ static
PLDHashOperator
EnumerateStyledLinks(nsPtrHashKey<Link>* aEntry, void* aArray)
{
nsTArray<Link*>* array = static_cast<nsTArray<Link*>*>(aArray);
LinkArray* array = static_cast<LinkArray*>(aArray);
(void)array->AppendElement(aEntry->GetKey());
return PL_DHASH_NEXT;
}
@ -7557,12 +7559,12 @@ nsDocument::RefreshLinkHrefs()
// Get a list of all links we know about. We will reset them, which will
// remove them from the document, so we need a copy of what is in the
// hashtable.
nsTArray<Link*> linksToNotify(mStyledLinks.Count());
LinkArray linksToNotify(mStyledLinks.Count());
(void)mStyledLinks.EnumerateEntries(EnumerateStyledLinks, &linksToNotify);
// Reset all of our styled links.
MOZ_AUTO_DOC_UPDATE(this, UPDATE_CONTENT_STATE, PR_TRUE);
for (nsTArray_base::size_type i = 0; i < linksToNotify.Length(); i++) {
for (LinkArray::size_type i = 0; i < linksToNotify.Length(); i++) {
linksToNotify[i]->ResetLinkState(true);
}
}

Просмотреть файл

@ -51,10 +51,11 @@ interface nsIDocShell;
#define NS_SHISTORY_INTERNAL_CONTRACTID "@mozilla.org/browser/shistory-internal;1"
template<class E> class nsTArray;
template<class E, class A> class nsTArray;
struct nsTArrayDefaultAllocator;
%}
[ref] native nsDocshellIDArray(nsTArray<PRUint64>);
[ref] native nsDocshellIDArray(nsTArray<PRUint64, nsTArrayDefaultAllocator>);
[scriptable, uuid(2dede933-25e1-47a3-8f61-0127c785ea01)]
interface nsISHistoryInternal: nsISupports

Просмотреть файл

@ -336,7 +336,7 @@ def _callCxxArrayClear(arr):
def _cxxArrayHasElementSorted(arr, elt):
return ExprBinary(
ExprVar('nsTArray_base::NoIndex'), '!=',
ExprSelect(arr, '.', 'NoIndex'), '!=',
ExprCall(ExprSelect(arr, '.', 'BinaryIndexOf'), args=[ elt ]))
def _otherSide(side):

Просмотреть файл

@ -327,7 +327,8 @@ protected:
* the layers in this array either have mContainerLayer as their parent,
* or no parent.
*/
nsAutoTArray<nsRefPtr<Layer>,1> mNewChildLayers;
typedef nsAutoTArray<nsRefPtr<Layer>,1> AutoLayersArray;
AutoLayersArray mNewChildLayers;
nsTArray<nsRefPtr<ThebesLayer> > mRecycledThebesLayers;
nsTArray<nsRefPtr<ColorLayer> > mRecycledColorLayers;
PRUint32 mNextFreeRecycledThebesLayer;
@ -803,8 +804,8 @@ ContainerState::PopThebesLayerData()
colorLayer->SetColor(data->mSolidColor);
NS_ASSERTION(!mNewChildLayers.Contains(colorLayer), "Layer already in list???");
nsTArray_base::index_type index = mNewChildLayers.IndexOf(data->mLayer);
NS_ASSERTION(index != nsTArray_base::NoIndex, "Thebes layer not found?");
AutoLayersArray::index_type index = mNewChildLayers.IndexOf(data->mLayer);
NS_ASSERTION(index != AutoLayersArray::NoIndex, "Thebes layer not found?");
mNewChildLayers.InsertElementAt(index + 1, colorLayer);
// Copy transform and clip rect

Просмотреть файл

@ -47,7 +47,7 @@
#include "nsIContent.h"
class nsIFrame;
template <class T> class nsTArray;
template <class T, class A> class nsTArray;
/**
* Any source for anonymous content can implement this interface to provide it.

Просмотреть файл

@ -64,7 +64,7 @@ class nsMediaList;
class nsMediaQueryResultCacheKey;
class nsCSSStyleSheet;
class nsPresContext;
template<class E> class nsTArray;
template<class E, class A> class nsTArray;
// -------------------------------
// CSS Style Sheet Inner Data Container

Просмотреть файл

@ -52,6 +52,8 @@
#endif
#define MOZALLOC_HAVE_XMALLOC
#if defined(MOZALLOC_EXPORT)
/* do nothing: it's been defined to __declspec(dllexport) by
* mozalloc*.cpp on platforms where that's required. */

Просмотреть файл

@ -42,10 +42,11 @@
%{C++
struct PrefTuple;
template<class E> class nsTArray;
template<class E, class A> class nsTArray;
struct nsTArrayDefaultAllocator;
%}
[ptr] native nsPreferencesArrayPtr(nsTArray<PrefTuple>);
[ptr] native nsPreferencesArrayPtr(nsTArray<PrefTuple, nsTArrayDefaultAllocator>);
[ptr] native nsPreferencePtr(PrefTuple);
[ptr] native nsPreferencePtrConst(const PrefTuple);

Просмотреть файл

@ -52,13 +52,15 @@ class StorageBaseStatementInternal;
class BindingParamsArray : public mozIStorageBindingParamsArray
{
typedef nsTArray< nsCOMPtr<mozIStorageBindingParams> > array_type;
public:
NS_DECL_ISUPPORTS
NS_DECL_MOZISTORAGEBINDINGPARAMSARRAY
BindingParamsArray(StorageBaseStatementInternal *aOwningStatement);
typedef nsTArray_base::size_type size_type;
typedef array_type::size_type size_type;
/**
* Locks the array and prevents further modification to it (such as adding
@ -132,7 +134,7 @@ public:
}
private:
nsCOMPtr<StorageBaseStatementInternal> mOwningStatement;
nsTArray< nsCOMPtr<mozIStorageBindingParams> > mArray;
array_type mArray;
bool mLocked;
friend class iterator;

Просмотреть файл

@ -61,10 +61,10 @@ nsMaybeWeakPtr_base::GetValueAs(const nsIID &iid) const
return nsnull;
}
/* static */ nsresult
nsMaybeWeakPtrArray_base::AppendWeakElementBase(nsTArray_base *aArray,
nsISupports *aElement,
PRBool aOwnsWeak)
nsresult
NS_AppendWeakElementBase(isupports_array_type *aArray,
nsISupports *aElement,
PRBool aOwnsWeak)
{
nsCOMPtr<nsISupports> ref;
if (aOwnsWeak) {
@ -75,24 +75,22 @@ nsMaybeWeakPtrArray_base::AppendWeakElementBase(nsTArray_base *aArray,
ref = aElement;
}
isupports_type *array = static_cast<isupports_type*>(aArray);
if (array->IndexOf(ref) != isupports_type::NoIndex) {
if (aArray->IndexOf(ref) != aArray->NoIndex) {
return NS_ERROR_INVALID_ARG; // already present
}
if (!array->AppendElement(ref)) {
if (!aArray->AppendElement(ref)) {
return NS_ERROR_OUT_OF_MEMORY;
}
return NS_OK;
}
/* static */ nsresult
nsMaybeWeakPtrArray_base::RemoveWeakElementBase(nsTArray_base *aArray,
nsISupports *aElement)
nsresult
NS_RemoveWeakElementBase(isupports_array_type *aArray,
nsISupports *aElement)
{
isupports_type *array = static_cast<isupports_type*>(aArray);
PRUint32 index = array->IndexOf(aElement);
if (index != isupports_type::NoIndex) {
array->RemoveElementAt(index);
PRUint32 index = aArray->IndexOf(aElement);
if (index != aArray->NoIndex) {
aArray->RemoveElementAt(index);
return NS_OK;
}
@ -105,11 +103,11 @@ nsMaybeWeakPtrArray_base::RemoveWeakElementBase(nsTArray_base *aArray,
nsresult rv = supWeakRef->GetWeakReference(getter_AddRefs(weakRef));
NS_ENSURE_SUCCESS(rv, rv);
index = array->IndexOf(weakRef);
if (index == isupports_type::NoIndex) {
index = aArray->IndexOf(weakRef);
if (index == aArray->NoIndex) {
return NS_ERROR_INVALID_ARG;
}
array->RemoveElementAt(index);
aArray->RemoveElementAt(index);
return NS_OK;
}

Просмотреть файл

@ -80,30 +80,26 @@ protected:
// grab a weak reference to a given object if requested. It only allows a
// given object to appear in the array once.
class nsMaybeWeakPtrArray_base
{
protected:
static nsresult AppendWeakElementBase(nsTArray_base *aArray,
nsISupports *aElement, PRBool aWeak);
static nsresult RemoveWeakElementBase(nsTArray_base *aArray,
nsISupports *aElement);
typedef nsTArray< nsMaybeWeakPtr<nsISupports> > isupports_type;
};
typedef nsTArray< nsMaybeWeakPtr<nsISupports> > isupports_array_type;
nsresult NS_AppendWeakElementBase(isupports_array_type *aArray,
nsISupports *aElement, PRBool aWeak);
nsresult NS_RemoveWeakElementBase(isupports_array_type *aArray,
nsISupports *aElement);
template<class T>
class nsMaybeWeakPtrArray : public nsTArray< nsMaybeWeakPtr<T> >,
private nsMaybeWeakPtrArray_base
class nsMaybeWeakPtrArray : public nsTArray< nsMaybeWeakPtr<T> >
{
public:
nsresult AppendWeakElement(T *aElement, PRBool aOwnsWeak)
{
return AppendWeakElementBase(this, aElement, aOwnsWeak);
return NS_AppendWeakElementBase(
reinterpret_cast<isupports_array_type*>(this), aElement, aOwnsWeak);
}
nsresult RemoveWeakElement(T *aElement)
{
return RemoveWeakElementBase(this, aElement);
return NS_RemoveWeakElementBase(
reinterpret_cast<isupports_array_type*>(this), aElement);
}
};

Просмотреть файл

@ -101,6 +101,7 @@ SDK_HEADERS = \
nsStringAPI.h \
nsStringGlue.h \
nsTArray.h \
nsTArray-inl.h \
nsTHashtable.h \
nsTObserverArray.h \
nsTPtrArray.h \

288
xpcom/glue/nsTArray-inl.h Normal file
Просмотреть файл

@ -0,0 +1,288 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et cindent: */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is C++ array template.
*
* The Initial Developer of the Original Code is Google Inc.
* Portions created by the Initial Developer are Copyright (C) 2005
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@meer.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef nsTArray_h__
# error "Don't include this file directly"
#endif
template<class Alloc>
nsTArray_base<Alloc>::nsTArray_base()
: mHdr(EmptyHdr()) {
MOZ_COUNT_CTOR(nsTArray_base);
}
template<class Alloc>
nsTArray_base<Alloc>::~nsTArray_base() {
if (mHdr != EmptyHdr() && !UsesAutoArrayBuffer()) {
Alloc::Free(mHdr);
}
MOZ_COUNT_DTOR(nsTArray_base);
}
template<class Alloc>
PRBool
nsTArray_base<Alloc>::EnsureCapacity(size_type capacity, size_type elemSize) {
// This should be the most common case so test this first
if (capacity <= mHdr->mCapacity)
return PR_TRUE;
// If the requested memory allocation exceeds size_type(-1)/2, then
// our doubling algorithm may not be able to allocate it.
// Additionally we couldn't fit in the Header::mCapacity
// member. Just bail out in cases like that. We don't want to be
// allocating 2 GB+ arrays anyway.
if ((PRUint64)capacity * elemSize > size_type(-1)/2) {
NS_ERROR("Attempting to allocate excessively large array");
return PR_FALSE;
}
if (mHdr == EmptyHdr()) {
// Malloc() new data
Header *header = static_cast<Header*>
(Alloc::Malloc(sizeof(Header) + capacity * elemSize));
if (!header)
return PR_FALSE;
header->mLength = 0;
header->mCapacity = capacity;
header->mIsAutoArray = 0;
mHdr = header;
return PR_TRUE;
}
// Use doubling algorithm when forced to increase available
// capacity. (Note that mCapacity is only 31 bits wide, so
// multiplication promotes its type. We use |2u| instead of |2|
// to make sure it's promoted to unsigned.)
capacity = PR_MAX(capacity, mHdr->mCapacity * 2u);
Header *header;
if (UsesAutoArrayBuffer()) {
// Malloc() and copy
header = static_cast<Header*>
(Alloc::Malloc(sizeof(Header) + capacity * elemSize));
if (!header)
return PR_FALSE;
memcpy(header, mHdr, sizeof(Header) + Length() * elemSize);
} else {
// Realloc() existing data
size_type size = sizeof(Header) + capacity * elemSize;
header = static_cast<Header*>(Alloc::Realloc(mHdr, size));
if (!header)
return PR_FALSE;
}
header->mCapacity = capacity;
mHdr = header;
return PR_TRUE;
}
template<class Alloc>
void
nsTArray_base<Alloc>::ShrinkCapacity(size_type elemSize) {
if (mHdr == EmptyHdr() || UsesAutoArrayBuffer())
return;
if (mHdr->mLength >= mHdr->mCapacity) // should never be greater than...
return;
size_type length = Length();
if (IsAutoArray() && GetAutoArrayBuffer()->mCapacity >= length) {
Header* header = GetAutoArrayBuffer();
// Copy data, but don't copy the header to avoid overwriting mCapacity
header->mLength = length;
memcpy(header + 1, mHdr + 1, length * elemSize);
Alloc::Free(mHdr);
mHdr = header;
return;
}
if (length == 0) {
NS_ASSERTION(!IsAutoArray(), "autoarray should have fit 0 elements");
Alloc::Free(mHdr);
mHdr = EmptyHdr();
return;
}
size_type size = sizeof(Header) + length * elemSize;
void *ptr = Alloc::Realloc(mHdr, size);
if (!ptr)
return;
mHdr = static_cast<Header*>(ptr);
mHdr->mCapacity = length;
}
template<class Alloc>
void
nsTArray_base<Alloc>::ShiftData(index_type start,
size_type oldLen, size_type newLen,
size_type elemSize) {
if (oldLen == newLen)
return;
// Determine how many elements need to be shifted
size_type num = mHdr->mLength - (start + oldLen);
// Compute the resulting length of the array
mHdr->mLength += newLen - oldLen;
if (mHdr->mLength == 0) {
ShrinkCapacity(elemSize);
} else {
// Maybe nothing needs to be shifted
if (num == 0)
return;
// Perform shift (change units to bytes first)
start *= elemSize;
newLen *= elemSize;
oldLen *= elemSize;
num *= elemSize;
char *base = reinterpret_cast<char*>(mHdr + 1) + start;
memmove(base + newLen, base + oldLen, num);
}
}
template<class Alloc>
PRBool
nsTArray_base<Alloc>::InsertSlotsAt(index_type index, size_type count,
size_type elementSize) {
NS_ASSERTION(index <= Length(), "Bogus insertion index");
size_type newLen = Length() + count;
EnsureCapacity(newLen, elementSize);
// Check for out of memory conditions
if (Capacity() < newLen)
return PR_FALSE;
// Move the existing elements as needed. Note that this will
// change our mLength, so no need to call IncrementLength.
ShiftData(index, 0, count, elementSize);
return PR_TRUE;
}
template<class Alloc>
template<class Allocator>
PRBool
nsTArray_base<Alloc>::SwapArrayElements(nsTArray_base<Allocator>& other,
size_type elemSize) {
#ifdef DEBUG
PRBool isAuto = IsAutoArray();
PRBool otherIsAuto = other.IsAutoArray();
#endif
if (!EnsureNotUsingAutoArrayBuffer(elemSize) ||
!other.EnsureNotUsingAutoArrayBuffer(elemSize)) {
return PR_FALSE;
}
NS_ASSERTION(isAuto == IsAutoArray(), "lost auto info");
NS_ASSERTION(otherIsAuto == other.IsAutoArray(), "lost auto info");
NS_ASSERTION(!UsesAutoArrayBuffer() && !other.UsesAutoArrayBuffer(),
"both should be using an alloced buffer now");
// If the two arrays have different mIsAutoArray values (i.e. one is
// an autoarray and one is not) then simply switching the buffers is
// going to make that bit wrong. We therefore adjust these
// mIsAutoArray bits before switching the buffers so that once the
// buffers are switched the mIsAutoArray bits are right again.
// However, we have to watch out so that we don't set the bit on
// sEmptyHeader. If an array (A) uses the empty header (and the
// other (B) therefore must be an nsAutoTArray) we make A point to
// the B's autobuffer so that when the buffers are switched B points
// to its own autobuffer.
// Adjust mIsAutoArray flags before swapping the buffers
if (IsAutoArray() && !other.IsAutoArray()) {
if (other.mHdr == EmptyHdr()) {
// Set other to use our built-in buffer so that we use it
// after the swap below.
other.mHdr = GetAutoArrayBuffer();
other.mHdr->mLength = 0;
}
else {
other.mHdr->mIsAutoArray = 1;
}
mHdr->mIsAutoArray = 0;
}
else if (!IsAutoArray() && other.IsAutoArray()) {
if (mHdr == EmptyHdr()) {
// Set us to use other's built-in buffer so that other use it
// after the swap below.
mHdr = other.GetAutoArrayBuffer();
mHdr->mLength = 0;
}
else {
mHdr->mIsAutoArray = 1;
}
other.mHdr->mIsAutoArray = 0;
}
// Swap the buffers
Header *h = other.mHdr;
other.mHdr = mHdr;
mHdr = h;
NS_ASSERTION(isAuto == IsAutoArray(), "lost auto info");
NS_ASSERTION(otherIsAuto == other.IsAutoArray(), "lost auto info");
return PR_TRUE;
}
template<class Alloc>
PRBool
nsTArray_base<Alloc>::EnsureNotUsingAutoArrayBuffer(size_type elemSize) {
if (UsesAutoArrayBuffer()) {
size_type size = sizeof(Header) + Length() * elemSize;
Header* header = static_cast<Header*>(Alloc::Malloc(size));
if (!header)
return PR_FALSE;
memcpy(header, mHdr, size);
header->mCapacity = Length();
mHdr = header;
}
return PR_TRUE;
}

Просмотреть файл

@ -41,239 +41,4 @@
#include "nsXPCOM.h"
#include "nsDebug.h"
nsTArray_base::Header nsTArray_base::sEmptyHdr = { 0, 0, 0 };
nsTArray_base::nsTArray_base()
: mHdr(&sEmptyHdr) {
MOZ_COUNT_CTOR(nsTArray_base);
}
nsTArray_base::~nsTArray_base() {
if (mHdr != &sEmptyHdr && !UsesAutoArrayBuffer()) {
NS_Free(mHdr);
}
MOZ_COUNT_DTOR(nsTArray_base);
}
PRBool
nsTArray_base::EnsureCapacity(size_type capacity, size_type elemSize) {
// This should be the most common case so test this first
if (capacity <= mHdr->mCapacity)
return PR_TRUE;
// If the requested memory allocation exceeds size_type(-1)/2, then our
// doubling algorithm may not be able to allocate it. Additionally we
// couldn't fit in the Header::mCapacity member. Just bail out in cases
// like that. We don't want to be allocating 2 GB+ arrays anyway.
if ((PRUint64)capacity * elemSize > size_type(-1)/2) {
NS_ERROR("Attempting to allocate excessively large array");
return PR_FALSE;
}
if (mHdr == &sEmptyHdr) {
// NS_Alloc new data
Header *header = static_cast<Header*>
(NS_Alloc(sizeof(Header) + capacity * elemSize));
if (!header)
return PR_FALSE;
header->mLength = 0;
header->mCapacity = capacity;
header->mIsAutoArray = 0;
mHdr = header;
return PR_TRUE;
}
// Use doubling algorithm when forced to increase available capacity.
// (Note that mCapacity is only 31 bits wide, so multiplication promotes its
// type. We use |2u| instead of |2| to make sure it's promoted to unsigned.)
capacity = PR_MAX(capacity, mHdr->mCapacity * 2u);
Header *header;
if (UsesAutoArrayBuffer()) {
// NS_Alloc and copy
header = static_cast<Header*>
(NS_Alloc(sizeof(Header) + capacity * elemSize));
if (!header)
return PR_FALSE;
memcpy(header, mHdr, sizeof(Header) + Length() * elemSize);
} else {
// NS_Realloc existing data
size_type size = sizeof(Header) + capacity * elemSize;
header = static_cast<Header*>(NS_Realloc(mHdr, size));
if (!header)
return PR_FALSE;
}
header->mCapacity = capacity;
mHdr = header;
return PR_TRUE;
}
void
nsTArray_base::ShrinkCapacity(size_type elemSize) {
if (mHdr == &sEmptyHdr || UsesAutoArrayBuffer())
return;
if (mHdr->mLength >= mHdr->mCapacity) // should never be greater than...
return;
size_type length = Length();
if (IsAutoArray() && GetAutoArrayBuffer()->mCapacity >= length) {
Header* header = GetAutoArrayBuffer();
// Copy data, but don't copy the header to avoid overwriting mCapacity
header->mLength = length;
memcpy(header + 1, mHdr + 1, length * elemSize);
NS_Free(mHdr);
mHdr = header;
return;
}
if (length == 0) {
NS_ASSERTION(!IsAutoArray(), "autoarray should have fit 0 elements");
NS_Free(mHdr);
mHdr = &sEmptyHdr;
return;
}
size_type size = sizeof(Header) + length * elemSize;
void *ptr = NS_Realloc(mHdr, size);
if (!ptr)
return;
mHdr = static_cast<Header*>(ptr);
mHdr->mCapacity = length;
}
void
nsTArray_base::ShiftData(index_type start, size_type oldLen, size_type newLen,
size_type elemSize) {
if (oldLen == newLen)
return;
// Determine how many elements need to be shifted
size_type num = mHdr->mLength - (start + oldLen);
// Compute the resulting length of the array
mHdr->mLength += newLen - oldLen;
if (mHdr->mLength == 0) {
ShrinkCapacity(elemSize);
} else {
// Maybe nothing needs to be shifted
if (num == 0)
return;
// Perform shift (change units to bytes first)
start *= elemSize;
newLen *= elemSize;
oldLen *= elemSize;
num *= elemSize;
char *base = reinterpret_cast<char*>(mHdr + 1) + start;
memmove(base + newLen, base + oldLen, num);
}
}
PRBool
nsTArray_base::InsertSlotsAt(index_type index, size_type count,
size_type elementSize) {
NS_ASSERTION(index <= Length(), "Bogus insertion index");
size_type newLen = Length() + count;
EnsureCapacity(newLen, elementSize);
// Check for out of memory conditions
if (Capacity() < newLen)
return PR_FALSE;
// Move the existing elements as needed. Note that this will
// change our mLength, so no need to call IncrementLength.
ShiftData(index, 0, count, elementSize);
return PR_TRUE;
}
PRBool
nsTArray_base::SwapArrayElements(nsTArray_base& other, size_type elemSize)
{
#ifdef DEBUG
PRBool isAuto = IsAutoArray();
PRBool otherIsAuto = other.IsAutoArray();
#endif
if (!EnsureNotUsingAutoArrayBuffer(elemSize) ||
!other.EnsureNotUsingAutoArrayBuffer(elemSize)) {
return PR_FALSE;
}
NS_ASSERTION(isAuto == IsAutoArray(), "lost auto info");
NS_ASSERTION(otherIsAuto == other.IsAutoArray(), "lost auto info");
NS_ASSERTION(!UsesAutoArrayBuffer() && !other.UsesAutoArrayBuffer(),
"both should be using an alloced buffer now");
// If the two arrays have different mIsAutoArray values (i.e. one is an
// autoarray and one is not) then simply switching the buffers is going to
// make that bit wrong. We therefore adjust these mIsAutoArray bits before
// switching the buffers so that once the buffers are switched the
// mIsAutoArray bits are right again.
// However, we have to watch out so that we don't set the bit on
// sEmptyHeader. If an array (A) uses the empty header (and the other (B)
// therefore must be an nsAutoTArray) we make A point to the B's autobuffer
// so that when the buffers are switched B points to its own autobuffer.
// Adjust mIsAutoArray flags before swapping the buffers
if (IsAutoArray() && !other.IsAutoArray()) {
if (other.mHdr == &sEmptyHdr) {
// Set other to use our built-in buffer so that we use it
// after the swap below.
other.mHdr = GetAutoArrayBuffer();
other.mHdr->mLength = 0;
}
else {
other.mHdr->mIsAutoArray = 1;
}
mHdr->mIsAutoArray = 0;
}
else if (!IsAutoArray() && other.IsAutoArray()) {
if (mHdr == &sEmptyHdr) {
// Set us to use other's built-in buffer so that other use it
// after the swap below.
mHdr = other.GetAutoArrayBuffer();
mHdr->mLength = 0;
}
else {
mHdr->mIsAutoArray = 1;
}
other.mHdr->mIsAutoArray = 0;
}
// Swap the buffers
Header *h = other.mHdr;
other.mHdr = mHdr;
mHdr = h;
NS_ASSERTION(isAuto == IsAutoArray(), "lost auto info");
NS_ASSERTION(otherIsAuto == other.IsAutoArray(), "lost auto info");
return PR_TRUE;
}
PRBool
nsTArray_base::EnsureNotUsingAutoArrayBuffer(size_type elemSize)
{
if (UsesAutoArrayBuffer()) {
size_type size = sizeof(Header) + Length() * elemSize;
Header* header = static_cast<Header*>(NS_Alloc(size));
if (!header)
return PR_FALSE;
memcpy(header, mHdr, size);
header->mCapacity = Length();
mHdr = header;
}
return PR_TRUE;
}
nsTArrayHeader nsTArrayHeader::sEmptyHdr = { 0, 0, 0 };

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -47,11 +47,11 @@
// nsTArray and has all the features of that class, in addition to an
// implementation of SafeElementAt that returns null for out of bounds access
//
template<class E>
class nsTPtrArray : public nsTArray<E*> {
template<class E, class Alloc=nsTArrayDefaultAllocator>
class nsTPtrArray : public nsTArray<E*, Alloc> {
public:
typedef nsTPtrArray<E> self_type;
typedef nsTArray<E*> base_type;
typedef nsTPtrArray<E, Alloc> self_type;
typedef nsTArray<E*, Alloc> base_type;
typedef typename base_type::size_type size_type;
typedef typename base_type::elem_type elem_type;
typedef typename base_type::index_type index_type;
@ -94,18 +94,18 @@ class nsTPtrArray : public nsTArray<E*> {
}
};
template<class E, PRUint32 N>
class nsAutoTPtrArray : public nsTPtrArray<E> {
template<class E, PRUint32 N, class Alloc=nsTArrayDefaultAllocator>
class nsAutoTPtrArray : public nsTPtrArray<E, Alloc> {
public:
typedef nsTPtrArray<E> base_type;
typedef nsTPtrArray<E, Alloc> base_type;
typedef typename base_type::Header Header;
typedef typename base_type::elem_type elem_type;
nsAutoTPtrArray() {
base_type::mHdr = reinterpret_cast<Header*>(&mAutoBuf);
base_type::mHdr->mLength = 0;
base_type::mHdr->mCapacity = N;
base_type::mHdr->mIsAutoArray = 1;
*base_type::PtrToHdr() = reinterpret_cast<Header*>(&mAutoBuf);
base_type::Hdr()->mLength = 0;
base_type::Hdr()->mCapacity = N;
base_type::Hdr()->mIsAutoArray = 1;
NS_ASSERTION(base_type::GetAutoArrayBuffer() ==
reinterpret_cast<Header*>(&mAutoBuf),