Bug 289010 - Move nsVoidArray/nsCOMArray to the XPCOM glue, and a few other things to make the glue easier to use, r=shaver+darin . The following files were CVS-copied from xpcom/ds to xpcom/glue: nsVoidArray.h nsVoidArray.cpp nsCOMArray.h nsCOMArray.cpp nsQuickSort.h nsQuickSort.cpp

This commit is contained in:
bsmedberg%covad.net 2005-11-02 20:39:39 +00:00
Родитель acf28ad4d1
Коммит 7112d805ca
6 изменённых файлов: 0 добавлений и 2540 удалений

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

@ -1,159 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** 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 a COM aware array class.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Alec Flett <alecf@netscape.com>
*
* 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 ***** */
#include "nsCOMArray.h"
#include "nsCOMPtr.h"
PR_STATIC_CALLBACK(PRBool) ReleaseObjects(void* aElement, void*);
// implementations of non-trivial methods in nsCOMArray_base
// copy constructor - we can't just memcpy here, because
// we have to make sure we own our own array buffer, and that each
// object gets another AddRef()
nsCOMArray_base::nsCOMArray_base(const nsCOMArray_base& aOther)
{
// make sure we do only one allocation
mArray.SizeTo(aOther.Count());
AppendObjects(aOther);
}
nsCOMArray_base::~nsCOMArray_base()
{
PRInt32 count = Count(), i;
for (i = 0; i < count; ++i) {
nsISupports* obj = ObjectAt(i);
NS_IF_RELEASE(obj);
}
}
PRInt32
nsCOMArray_base::IndexOfObject(nsISupports* aObject) const {
NS_ENSURE_TRUE(aObject, -1);
nsCOMPtr<nsISupports> supports = do_QueryInterface(aObject);
NS_ENSURE_TRUE(supports, -1);
PRInt32 i, count;
PRInt32 retval = -1;
count = mArray.Count();
for (i = 0; i < count; ++i) {
nsCOMPtr<nsISupports> arrayItem =
do_QueryInterface(NS_REINTERPRET_CAST(nsISupports*,mArray.ElementAt(i)));
if (arrayItem == supports) {
retval = i;
break;
}
}
return retval;
}
PRBool
nsCOMArray_base::InsertObjectAt(nsISupports* aObject, PRInt32 aIndex) {
PRBool result = mArray.InsertElementAt(aObject, aIndex);
if (result)
NS_IF_ADDREF(aObject);
return result;
}
PRBool
nsCOMArray_base::InsertObjectsAt(const nsCOMArray_base& aObjects, PRInt32 aIndex) {
PRBool result = mArray.InsertElementsAt(aObjects.mArray, aIndex);
if (result) {
// need to addref all these
PRInt32 count = aObjects.Count();
for (PRInt32 i = 0; i < count; ++i) {
NS_IF_ADDREF(aObjects.ObjectAt(i));
}
}
return result;
}
PRBool
nsCOMArray_base::ReplaceObjectAt(nsISupports* aObject, PRInt32 aIndex)
{
// its ok if oldObject is null here
nsISupports *oldObject =
NS_REINTERPRET_CAST(nsISupports*, mArray.SafeElementAt(aIndex));
PRBool result = mArray.ReplaceElementAt(aObject, aIndex);
// ReplaceElementAt could fail, such as if the array grows
// so only release the existing object if the replacement succeeded
if (result) {
// Make sure to addref first, in case aObject == oldObject
NS_IF_ADDREF(aObject);
NS_IF_RELEASE(oldObject);
}
return result;
}
PRBool
nsCOMArray_base::RemoveObject(nsISupports *aObject)
{
PRBool result = mArray.RemoveElement(aObject);
if (result)
NS_IF_RELEASE(aObject);
return result;
}
PRBool
nsCOMArray_base::RemoveObjectAt(PRInt32 aIndex)
{
nsISupports* element = ObjectAt(aIndex);
PRBool result = mArray.RemoveElementAt(aIndex);
if (result)
NS_IF_RELEASE(element);
return result;
}
// useful for destructors
PRBool
ReleaseObjects(void* aElement, void*)
{
nsISupports* element = NS_STATIC_CAST(nsISupports*, aElement);
NS_IF_RELEASE(element);
return PR_TRUE;
}
void
nsCOMArray_base::Clear()
{
mArray.EnumerateForwards(ReleaseObjects, nsnull);
mArray.Clear();
}

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

@ -1,267 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** 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 a COM aware array class.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Alec Flett <alecf@netscape.com>
*
* 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 nsCOMArray_h__
#define nsCOMArray_h__
#include "nsVoidArray.h"
#include "nsISupports.h"
// See below for the definition of nsCOMArray<T>
// a class that's nsISupports-specific, so that we can contain the
// work of this class in the XPCOM dll
class NS_COM nsCOMArray_base
{
friend class nsArray;
protected:
nsCOMArray_base() {}
nsCOMArray_base(PRInt32 aCount) : mArray(aCount) {}
nsCOMArray_base(const nsCOMArray_base& other);
~nsCOMArray_base();
PRInt32 IndexOf(nsISupports* aObject) const {
return mArray.IndexOf(aObject);
}
PRInt32 IndexOfObject(nsISupports* aObject) const;
PRBool EnumerateForwards(nsVoidArrayEnumFunc aFunc, void* aData) {
return mArray.EnumerateForwards(aFunc, aData);
}
PRBool EnumerateBackwards(nsVoidArrayEnumFunc aFunc, void* aData) {
return mArray.EnumerateBackwards(aFunc, aData);
}
void Sort(nsVoidArrayComparatorFunc aFunc, void* aData) {
mArray.Sort(aFunc, aData);
}
// any method which is not a direct forward to mArray should
// avoid inline bodies, so that the compiler doesn't inline them
// all over the place
void Clear();
PRBool InsertObjectAt(nsISupports* aObject, PRInt32 aIndex);
PRBool InsertObjectsAt(const nsCOMArray_base& aObjects, PRInt32 aIndex);
PRBool ReplaceObjectAt(nsISupports* aObject, PRInt32 aIndex);
PRBool AppendObject(nsISupports *aObject) {
return InsertObjectAt(aObject, Count());
}
PRBool AppendObjects(const nsCOMArray_base& aObjects) {
return InsertObjectsAt(aObjects, Count());
}
PRBool RemoveObject(nsISupports *aObject);
PRBool RemoveObjectAt(PRInt32 aIndex);
public:
// override nsVoidArray stuff so that they can be accessed by
// consumers of nsCOMArray
PRInt32 Count() const {
return mArray.Count();
}
nsISupports* ObjectAt(PRInt32 aIndex) const {
return NS_STATIC_CAST(nsISupports*, mArray.FastElementAt(aIndex));
}
nsISupports* SafeObjectAt(PRInt32 aIndex) const {
return NS_STATIC_CAST(nsISupports*, mArray.SafeElementAt(aIndex));
}
nsISupports* operator[](PRInt32 aIndex) const {
return ObjectAt(aIndex);
}
private:
// the actual storage
nsVoidArray mArray;
// don't implement these, defaults will muck with refcounts!
nsCOMArray_base& operator=(const nsCOMArray_base& other);
};
// a non-XPCOM, refcounting array of XPCOM objects
// used as a member variable or stack variable - this object is NOT
// refcounted, but the objects that it holds are
//
// most of the read-only accessors like ObjectAt()/etc do NOT refcount
// on the way out. This means that you can do one of two things:
//
// * does an addref, but holds onto a reference
// nsCOMPtr<T> foo = array[i];
//
// * avoids the refcount, but foo might go stale if array[i] is ever
// * modified/removed. Be careful not to NS_RELEASE(foo)!
// T* foo = array[i];
//
// This array will accept null as an argument for any object, and will
// store null in the array, just like nsVoidArray. But that also means
// that methods like ObjectAt() may return null when referring to an
// existing, but null entry in the array.
template <class T>
class nsCOMArray : public nsCOMArray_base
{
public:
nsCOMArray() {}
nsCOMArray(PRInt32 aCount) : nsCOMArray_base(aCount) {}
// only to be used by trusted classes who are going to pass us the
// right type!
nsCOMArray(const nsCOMArray<T>& aOther) : nsCOMArray_base(aOther) { }
~nsCOMArray() {}
// these do NOT refcount on the way out, for speed
T* ObjectAt(PRInt32 aIndex) const {
return NS_STATIC_CAST(T*,nsCOMArray_base::ObjectAt(aIndex));
}
// these do NOT refcount on the way out, for speed
T* SafeObjectAt(PRInt32 aIndex) const {
return NS_STATIC_CAST(T*,nsCOMArray_base::SafeObjectAt(aIndex));
}
// indexing operator for syntactic sugar
T* operator[](PRInt32 aIndex) const {
return ObjectAt(aIndex);
}
// index of the element in question.. does NOT refcount
// note: this does not check COM object identity. Use
// IndexOfObject() for that purpose
PRInt32 IndexOf(T* aObject) const {
return nsCOMArray_base::IndexOf(NS_STATIC_CAST(nsISupports*, aObject));
}
// index of the element in question.. be careful!
// this is much slower than IndexOf() because it uses
// QueryInterface to determine actual COM identity of the object
// if you need to do this frequently then consider enforcing
// COM object identity before adding/comparing elements
PRInt32 IndexOfObject(T* aObject) const {
return nsCOMArray_base::IndexOfObject(NS_STATIC_CAST(nsISupports*, aObject));
}
// inserts aObject at aIndex, shifting the objects at aIndex and
// later to make space
PRBool InsertObjectAt(T* aObject, PRInt32 aIndex) {
return nsCOMArray_base::InsertObjectAt(NS_STATIC_CAST(nsISupports*, aObject), aIndex);
}
// inserts the objects from aObject at aIndex, shifting the
// objects at aIndex and later to make space
PRBool InsertObjectsAt(const nsCOMArray<T>& aObjects, PRInt32 aIndex) {
return nsCOMArray_base::InsertObjectsAt(aObjects, aIndex);
}
// replaces an existing element. Warning: if the array grows,
// the newly created entries will all be null
PRBool ReplaceObjectAt(T* aObject, PRInt32 aIndex) {
return nsCOMArray_base::ReplaceObjectAt(NS_STATIC_CAST(nsISupports*, aObject), aIndex);
}
// override nsVoidArray stuff so that they can be accessed by
// other methods
// elements in the array (including null elements!)
PRInt32 Count() const {
return nsCOMArray_base::Count();
}
// remove all elements in the array, and call NS_RELEASE on each one
void Clear() {
nsCOMArray_base::Clear();
}
// Enumerator callback function. Return PR_FALSE to stop
// Here's a more readable form:
// PRBool PR_CALLBACK enumerate(T* aElement, void* aData)
typedef PRBool (* PR_CALLBACK nsCOMArrayEnumFunc)
(T* aElement, void *aData);
// enumerate through the array with a callback.
PRBool EnumerateForwards(nsCOMArrayEnumFunc aFunc, void* aData) {
return nsCOMArray_base::EnumerateForwards(nsVoidArrayEnumFunc(aFunc),
aData);
}
PRBool EnumerateBackwards(nsCOMArrayEnumFunc aFunc, void* aData) {
return nsCOMArray_base::EnumerateBackwards(nsVoidArrayEnumFunc(aFunc),
aData);
}
typedef int (* PR_CALLBACK nsCOMArrayComparatorFunc)
(T* aElement1, T* aElement2, void* aData);
void Sort(nsCOMArrayComparatorFunc aFunc, void* aData) {
nsCOMArray_base::Sort(nsVoidArrayComparatorFunc(aFunc), aData);
}
// append an object, growing the array as necessary
PRBool AppendObject(T *aObject) {
return nsCOMArray_base::AppendObject(NS_STATIC_CAST(nsISupports*, aObject));
}
// append objects, growing the array as necessary
PRBool AppendObjects(const nsCOMArray<T>& aObjects) {
return nsCOMArray_base::AppendObjects(aObjects);
}
// remove the first instance of the given object and shrink the
// array as necessary
// Warning: if you pass null here, it will remove the first null element
PRBool RemoveObject(T *aObject) {
return nsCOMArray_base::RemoveObject(NS_STATIC_CAST(nsISupports*, aObject));
}
// remove an element at a specific position, shrinking the array
// as necessary
PRBool RemoveObjectAt(PRInt32 aIndex) {
return nsCOMArray_base::RemoveObjectAt(aIndex);
}
private:
// don't implement these!
nsCOMArray<T>& operator=(const nsCOMArray<T>& other);
};
#endif

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

@ -1,182 +0,0 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*-
* Copyright (c) 1992, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/* We need this because Solaris' version of qsort is broken and
* causes array bounds reads.
*/
#include <stdlib.h>
#include "prtypes.h"
#include "nsQuickSort.h"
PR_BEGIN_EXTERN_C
#if !defined(DEBUG) && (defined(__cplusplus) || defined(__gcc))
# ifndef INLINE
# define INLINE inline
# endif
#else
# define INLINE
#endif
typedef int cmp_t(const void *, const void *, void *);
static INLINE char *med3(char *, char *, char *, cmp_t *, void *);
static INLINE void swapfunc(char *, char *, int, int);
/*
* Qsort routine from Bentley & McIlroy's "Engineering a Sort Function".
*/
#define swapcode(TYPE, parmi, parmj, n) { \
long i = (n) / sizeof (TYPE); \
register TYPE *pi = (TYPE *) (parmi); \
register TYPE *pj = (TYPE *) (parmj); \
do { \
register TYPE t = *pi; \
*pi++ = *pj; \
*pj++ = t; \
} while (--i > 0); \
}
#define SWAPINIT(a, es) swaptype = ((char *)a - (char *)0) % sizeof(long) || \
es % sizeof(long) ? 2 : es == sizeof(long)? 0 : 1;
static INLINE void
swapfunc(char *a, char *b, int n, int swaptype)
{
if(swaptype <= 1)
swapcode(long, a, b, n)
else
swapcode(char, a, b, n)
}
#define swap(a, b) \
if (swaptype == 0) { \
long t = *(long *)(a); \
*(long *)(a) = *(long *)(b); \
*(long *)(b) = t; \
} else \
swapfunc((char *)a, (char*)b, (int)es, swaptype)
#define vecswap(a, b, n) if ((n) > 0) swapfunc((char *)a, (char *)b, (int)n, swaptype)
static INLINE char *
med3(char *a, char *b, char *c, cmp_t* cmp, void *data)
{
return cmp(a, b, data) < 0 ?
(cmp(b, c, data) < 0 ? b : (cmp(a, c, data) < 0 ? c : a ))
:(cmp(b, c, data) > 0 ? b : (cmp(a, c, data) < 0 ? a : c ));
}
void NS_QuickSort (
void *a,
unsigned int n,
unsigned int es,
cmp_t *cmp,
void *data
)
{
char *pa, *pb, *pc, *pd, *pl, *pm, *pn;
int d, r, swaptype, swap_cnt;
loop: SWAPINIT(a, es);
swap_cnt = 0;
if (n < 7) {
for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
for (pl = pm; pl > (char *)a && cmp(pl - es, pl, data) > 0;
pl -= es)
swap(pl, pl - es);
return;
}
pm = (char *)a + (n / 2) * es;
if (n > 7) {
pl = (char *)a;
pn = (char *)a + (n - 1) * es;
if (n > 40) {
d = (n / 8) * es;
pl = med3(pl, pl + d, pl + 2 * d, cmp, data);
pm = med3(pm - d, pm, pm + d, cmp, data);
pn = med3(pn - 2 * d, pn - d, pn, cmp, data);
}
pm = med3(pl, pm, pn, cmp, data);
}
swap(a, pm);
pa = pb = (char *)a + es;
pc = pd = (char *)a + (n - 1) * es;
for (;;) {
while (pb <= pc && (r = cmp(pb, a, data)) <= 0) {
if (r == 0) {
swap_cnt = 1;
swap(pa, pb);
pa += es;
}
pb += es;
}
while (pb <= pc && (r = cmp(pc, a, data)) >= 0) {
if (r == 0) {
swap_cnt = 1;
swap(pc, pd);
pd -= es;
}
pc -= es;
}
if (pb > pc)
break;
swap(pb, pc);
swap_cnt = 1;
pb += es;
pc -= es;
}
if (swap_cnt == 0) { /* Switch to insertion sort */
for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
for (pl = pm; pl > (char *)a && cmp(pl - es, pl, data) > 0;
pl -= es)
swap(pl, pl - es);
return;
}
pn = (char *)a + n * es;
r = PR_MIN(pa - (char *)a, pb - pa);
vecswap(a, pb - r, r);
r = PR_MIN(pd - pc, (int)(pn - pd - es));
vecswap(pb, pn - r, r);
if ((r = pb - pa) > (int)es)
NS_QuickSort(a, r / es, es, cmp, data);
if ((r = pd - pc) > (int)es) {
/* Iterate rather than recurse to save stack space */
a = pn - r;
n = r / es;
goto loop;
}
/* NS_QuickSort(pn - r, r / es, es, cmp, data);*/
}
PR_END_EXTERN_C

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

@ -1,67 +0,0 @@
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** 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 mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either of 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 ***** */
/* We need this because Solaris' version of qsort is broken and
* causes array bounds reads.
*/
#ifndef nsQuickSort_h___
#define nsQuickSort_h___
#include "prtypes.h"
PR_BEGIN_EXTERN_C
/**
* Parameters:
* 1. the array to sort
* 2. the number of elements in the array
* 3. the size of each array element
* 4. comparison function taking two elements and parameter #5 and
* returning an integer:
* + less than zero if the first element should be before the second
* + 0 if the order of the elements does not matter
* + greater than zero if the second element should be before the first
* 5. extra data to pass to comparison function
*/
PR_EXTERN(void) NS_QuickSort(void *, unsigned int, unsigned int,
int (*)(const void *, const void *, void *),
void *);
PR_END_EXTERN_C
#endif /* nsQuickSort_h___ */

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

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

@ -1,429 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2; c-file-offsets: ((substatement-open . 0)) -*- */
/* ***** 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 mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either of 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 nsVoidArray_h___
#define nsVoidArray_h___
//#define DEBUG_VOIDARRAY 1
#include "nscore.h"
#include "nsAString.h"
// Comparator callback function for sorting array values.
typedef int (* PR_CALLBACK nsVoidArrayComparatorFunc)
(const void* aElement1, const void* aElement2, void* aData);
// Enumerator callback function. Return PR_FALSE to stop
typedef PRBool (* PR_CALLBACK nsVoidArrayEnumFunc)(void* aElement, void *aData);
/// A basic zero-based array of void*'s that manages its own memory
class NS_COM nsVoidArray {
public:
nsVoidArray();
nsVoidArray(PRInt32 aCount); // initial count of aCount elements set to nsnull
~nsVoidArray();
nsVoidArray& operator=(const nsVoidArray& other);
inline PRInt32 Count() const {
return mImpl ? mImpl->mCount : 0;
}
// returns the max number that can be held without allocating
inline PRInt32 GetArraySize() const {
return mImpl ? (PRInt32(mImpl->mBits) & kArraySizeMask) : 0;
}
void* FastElementAt(PRInt32 aIndex) const
{
NS_ASSERTION(0 <= aIndex && aIndex < Count(), "index out of range");
return mImpl->mArray[aIndex];
}
// This both asserts and bounds-checks, because (1) we don't want
// people to write bad code, but (2) we don't want to change it to
// crashing for backwards compatibility. See bug 96108.
void* ElementAt(PRInt32 aIndex) const
{
NS_ASSERTION(0 <= aIndex && aIndex < Count(), "index out of range");
return SafeElementAt(aIndex);
}
// bounds-checked version
void* SafeElementAt(PRInt32 aIndex) const
{
if (PRUint32(aIndex) >= PRUint32(Count())) // handles aIndex < 0 too
{
return nsnull;
}
// The bounds check ensures mImpl is non-null.
return mImpl->mArray[aIndex];
}
void* operator[](PRInt32 aIndex) const { return ElementAt(aIndex); }
PRInt32 IndexOf(void* aPossibleElement) const;
PRBool InsertElementAt(void* aElement, PRInt32 aIndex);
PRBool InsertElementsAt(const nsVoidArray &other, PRInt32 aIndex);
PRBool ReplaceElementAt(void* aElement, PRInt32 aIndex);
// useful for doing LRU arrays, sorting, etc
PRBool MoveElement(PRInt32 aFrom, PRInt32 aTo);
PRBool AppendElement(void* aElement) {
return InsertElementAt(aElement, Count());
}
PRBool AppendElements(nsVoidArray& aElements) {
return InsertElementsAt(aElements, Count());
}
PRBool RemoveElement(void* aElement);
PRBool RemoveElementsAt(PRInt32 aIndex, PRInt32 aCount);
PRBool RemoveElementAt(PRInt32 aIndex) { return RemoveElementsAt(aIndex,1); }
void Clear();
PRBool SizeTo(PRInt32 aMin);
// Subtly different - Compact() tries to be smart about whether we
// should reallocate the array; SizeTo() always reallocates.
void Compact();
void Sort(nsVoidArrayComparatorFunc aFunc, void* aData);
PRBool EnumerateForwards(nsVoidArrayEnumFunc aFunc, void* aData);
PRBool EnumerateBackwards(nsVoidArrayEnumFunc aFunc, void* aData);
protected:
PRBool GrowArrayBy(PRInt32 aGrowBy);
struct Impl {
/**
* Packed bits. The low 30 bits are the array's size.
* The two highest bits indicate whether or not we "own" mImpl and
* must free() it when destroyed, and whether we have a preallocated
* nsAutoVoidArray buffer.
*/
PRUint32 mBits;
/**
* The number of elements in the array
*/
PRInt32 mCount;
/**
* Array data, padded out to the actual size of the array.
*/
void* mArray[1];
};
Impl* mImpl;
#if DEBUG_VOIDARRAY
PRInt32 mMaxCount;
PRInt32 mMaxSize;
PRBool mIsAuto;
#endif
enum {
kArrayOwnerMask = 1 << 31,
kArrayHasAutoBufferMask = 1 << 30,
kArraySizeMask = ~(kArrayOwnerMask | kArrayHasAutoBufferMask)
};
enum { kAutoBufSize = 8 };
// bit twiddlers
void SetArray(Impl *newImpl, PRInt32 aSize, PRInt32 aCount, PRBool aOwner,
PRBool aHasAuto);
inline PRBool IsArrayOwner() const {
return mImpl && (mImpl->mBits & kArrayOwnerMask);
}
inline PRBool HasAutoBuffer() const {
return mImpl && (mImpl->mBits & kArrayHasAutoBufferMask);
}
private:
/// Copy constructors are not allowed
nsVoidArray(const nsVoidArray& other);
};
// A zero-based array with a bit of automatic internal storage
class NS_COM nsAutoVoidArray : public nsVoidArray {
public:
nsAutoVoidArray();
void ResetToAutoBuffer()
{
SetArray(NS_REINTERPRET_CAST(Impl*, mAutoBuf), kAutoBufSize, 0, PR_FALSE,
PR_TRUE);
}
protected:
// The internal storage
char mAutoBuf[sizeof(Impl) + (kAutoBufSize - 1) * sizeof(void*)];
};
class nsString;
typedef int (* PR_CALLBACK nsStringArrayComparatorFunc)
(const nsString* aElement1, const nsString* aElement2, void* aData);
typedef PRBool (*nsStringArrayEnumFunc)(nsString& aElement, void *aData);
class NS_COM nsStringArray: private nsVoidArray
{
public:
nsStringArray(void);
nsStringArray(PRInt32 aCount); // Storage for aCount elements will be pre-allocated
~nsStringArray(void);
nsStringArray& operator=(const nsStringArray& other);
PRInt32 Count(void) const {
return nsVoidArray::Count();
}
void StringAt(PRInt32 aIndex, nsAString& aString) const;
nsString* StringAt(PRInt32 aIndex) const;
nsString* operator[](PRInt32 aIndex) const { return StringAt(aIndex); }
PRInt32 IndexOf(const nsAString& aPossibleString) const;
PRBool InsertStringAt(const nsAString& aString, PRInt32 aIndex);
PRBool ReplaceStringAt(const nsAString& aString, PRInt32 aIndex);
PRBool AppendString(const nsAString& aString) {
return InsertStringAt(aString, Count());
}
PRBool RemoveString(const nsAString& aString);
PRBool RemoveStringAt(PRInt32 aIndex);
void Clear(void);
void Compact(void) {
nsVoidArray::Compact();
}
void Sort(void);
void Sort(nsStringArrayComparatorFunc aFunc, void* aData);
PRBool EnumerateForwards(nsStringArrayEnumFunc aFunc, void* aData);
PRBool EnumerateBackwards(nsStringArrayEnumFunc aFunc, void* aData);
private:
/// Copy constructors are not allowed
nsStringArray(const nsStringArray& other);
};
class nsCString;
typedef int (* PR_CALLBACK nsCStringArrayComparatorFunc)
(const nsCString* aElement1, const nsCString* aElement2, void* aData);
typedef PRBool (*nsCStringArrayEnumFunc)(nsCString& aElement, void *aData);
class NS_COM nsCStringArray: private nsVoidArray
{
public:
nsCStringArray(void);
nsCStringArray(PRInt32 aCount); // Storage for aCount elements will be pre-allocated
~nsCStringArray(void);
nsCStringArray& operator=(const nsCStringArray& other);
// Parses a given string using the delimiter passed in. If the array
// already has some elements, items parsed from string will be appended
// to array. For example, array.ParseString("a,b,c", ","); will add strings
// "a", "b" and "c" to the array. Parsing process has the same tokenizing
// behavior as strtok().
void ParseString(const char* string, const char* delimiter);
PRInt32 Count(void) const {
return nsVoidArray::Count();
}
void CStringAt(PRInt32 aIndex, nsACString& aCString) const;
nsCString* CStringAt(PRInt32 aIndex) const;
nsCString* operator[](PRInt32 aIndex) const { return CStringAt(aIndex); }
PRInt32 IndexOf(const nsACString& aPossibleString) const;
PRInt32 IndexOfIgnoreCase(const nsACString& aPossibleString) const;
PRBool InsertCStringAt(const nsACString& aCString, PRInt32 aIndex);
PRBool ReplaceCStringAt(const nsACString& aCString, PRInt32 aIndex);
PRBool AppendCString(const nsACString& aCString) {
return InsertCStringAt(aCString, Count());
}
PRBool RemoveCString(const nsACString& aCString);
PRBool RemoveCStringIgnoreCase(const nsACString& aCString);
PRBool RemoveCStringAt(PRInt32 aIndex);
void Clear(void);
void Compact(void) {
nsVoidArray::Compact();
}
void Sort(void);
void SortIgnoreCase(void);
void Sort(nsCStringArrayComparatorFunc aFunc, void* aData);
PRBool EnumerateForwards(nsCStringArrayEnumFunc aFunc, void* aData);
PRBool EnumerateBackwards(nsCStringArrayEnumFunc aFunc, void* aData);
private:
/// Copy constructors are not allowed
nsCStringArray(const nsCStringArray& other);
};
//===================================================================
// nsSmallVoidArray is not a general-purpose replacement for
// ns(Auto)VoidArray because there is (some) extra CPU overhead for arrays
// larger than 1 element, though not a lot. It is appropriate for
// space-sensitive uses where sizes of 0 or 1 are moderately common or
// more, and where we're NOT storing arbitrary integers or arbitrary
// pointers.
// NOTE: nsSmallVoidArray can ONLY be used for holding items that always
// have the low bit as a 0 - i.e. element & 1 == 0. This happens to be
// true for allocated and object pointers for all the architectures we run
// on, but conceivably there might be some architectures/compilers for
// which it is NOT true. We know this works for all existing architectures
// because if it didn't then nsCheapVoidArray would have failed. Also note
// that we will ASSERT if this assumption is violated in DEBUG builds.
// XXX we're really re-implementing the whole nsVoidArray interface here -
// some form of abstract class would be useful
// I disagree on the abstraction here. If the point of this class is to be
// as small as possible, and no one will ever derive from it, as I found
// today, there should not be any virtualness to it to avoid the vtable
// ptr overhead.
class NS_COM nsSmallVoidArray : private nsVoidArray
{
public:
~nsSmallVoidArray();
nsSmallVoidArray& operator=(nsSmallVoidArray& other);
void* operator[](PRInt32 aIndex) const { return ElementAt(aIndex); }
PRInt32 GetArraySize() const;
PRInt32 Count() const;
void* FastElementAt(PRInt32 aIndex) const;
// This both asserts and bounds-checks, because (1) we don't want
// people to write bad code, but (2) we don't want to change it to
// crashing for backwards compatibility. See bug 96108.
void* ElementAt(PRInt32 aIndex) const
{
NS_ASSERTION(0 <= aIndex && aIndex < Count(), "index out of range");
return SafeElementAt(aIndex);
}
void* SafeElementAt(PRInt32 aIndex) const {
// let compiler inline; it may be able to remove these checks
if (PRUint32(aIndex) >= PRUint32(Count())) // handles aIndex < 0 too
{
return nsnull;
}
return FastElementAt(aIndex);
}
PRInt32 IndexOf(void* aPossibleElement) const;
PRBool InsertElementAt(void* aElement, PRInt32 aIndex);
PRBool InsertElementsAt(const nsVoidArray &other, PRInt32 aIndex);
PRBool ReplaceElementAt(void* aElement, PRInt32 aIndex);
PRBool MoveElement(PRInt32 aFrom, PRInt32 aTo);
PRBool AppendElement(void* aElement);
PRBool AppendElements(nsVoidArray& aElements) {
return InsertElementsAt(aElements, Count());
}
PRBool RemoveElement(void* aElement);
PRBool RemoveElementsAt(PRInt32 aIndex, PRInt32 aCount);
PRBool RemoveElementAt(PRInt32 aIndex);
void Clear();
PRBool SizeTo(PRInt32 aMin);
void Compact();
void Sort(nsVoidArrayComparatorFunc aFunc, void* aData);
PRBool EnumerateForwards(nsVoidArrayEnumFunc aFunc, void* aData);
PRBool EnumerateBackwards(nsVoidArrayEnumFunc aFunc, void* aData);
private:
PRBool HasSingle() const
{
return NS_REINTERPRET_CAST(PRWord, mImpl) & 0x1;
}
void* GetSingle() const
{
NS_ASSERTION(HasSingle(), "wrong type");
return NS_REINTERPRET_CAST(void*,
NS_REINTERPRET_CAST(PRWord, mImpl) & ~0x1);
}
void SetSingle(void *aChild)
{
NS_ASSERTION(HasSingle() || !mImpl, "overwriting array");
mImpl = NS_REINTERPRET_CAST(Impl*,
NS_REINTERPRET_CAST(PRWord, aChild) | 0x1);
}
PRBool IsEmpty() const
{
// Note that this isn't the same as Count()==0
return !mImpl;
}
const nsVoidArray* AsArray() const
{
NS_ASSERTION(!HasSingle(), "This is a single");
return this;
}
nsVoidArray* AsArray()
{
NS_ASSERTION(!HasSingle(), "This is a single");
return this;
}
PRBool EnsureArray();
};
#endif /* nsVoidArray_h___ */