1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #ifndef nsCOMArray_h__
8 #define nsCOMArray_h__
9 
10 #include "mozilla/Attributes.h"
11 #include "mozilla/ArrayIterator.h"
12 #include "mozilla/MemoryReporting.h"
13 #include "mozilla/ReverseIterator.h"
14 
15 #include "nsCycleCollectionNoteChild.h"
16 #include "nsTArray.h"
17 #include "nsISupports.h"
18 
19 // See below for the definition of nsCOMArray<T>
20 
21 // a class that's nsISupports-specific, so that we can contain the
22 // work of this class in the XPCOM dll
23 class nsCOMArray_base {
24   friend class nsArrayBase;
25 
26  protected:
nsCOMArray_base()27   nsCOMArray_base() {}
nsCOMArray_base(int32_t aCount)28   explicit nsCOMArray_base(int32_t aCount) : mArray(aCount) {}
29   nsCOMArray_base(const nsCOMArray_base& aOther);
30   ~nsCOMArray_base();
31 
32   int32_t IndexOf(nsISupports* aObject, uint32_t aStartIndex = 0) const;
Contains(nsISupports * aObject)33   bool Contains(nsISupports* aObject) const { return IndexOf(aObject) != -1; }
34 
35   int32_t IndexOfObject(nsISupports* aObject) const;
ContainsObject(nsISupports * aObject)36   bool ContainsObject(nsISupports* aObject) const {
37     return IndexOfObject(aObject) != -1;
38   }
39 
40   typedef bool (*nsBaseArrayEnumFunc)(void* aElement, void* aData);
41 
42   // enumerate through the array with a callback.
43   bool EnumerateForwards(nsBaseArrayEnumFunc aFunc, void* aData) const;
44 
45   bool EnumerateBackwards(nsBaseArrayEnumFunc aFunc, void* aData) const;
46 
47   typedef int (*nsBaseArrayComparatorFunc)(nsISupports* aElement1,
48                                            nsISupports* aElement2, void* aData);
49 
50   struct nsCOMArrayComparatorContext {
51     nsBaseArrayComparatorFunc mComparatorFunc;
52     void* mData;
53   };
54 
55   static int nsCOMArrayComparator(const void* aElement1, const void* aElement2,
56                                   void* aData);
57   void Sort(nsBaseArrayComparatorFunc aFunc, void* aData);
58 
59   bool InsertObjectAt(nsISupports* aObject, int32_t aIndex);
60   void InsertElementAt(uint32_t aIndex, nsISupports* aElement);
61   void InsertElementAt(uint32_t aIndex, already_AddRefed<nsISupports> aElement);
62   bool InsertObjectsAt(const nsCOMArray_base& aObjects, int32_t aIndex);
63   void InsertElementsAt(uint32_t aIndex, const nsCOMArray_base& aElements);
64   void InsertElementsAt(uint32_t aIndex, nsISupports* const* aElements,
65                         uint32_t aCount);
66   void ReplaceObjectAt(nsISupports* aObject, int32_t aIndex);
ReplaceElementAt(uint32_t aIndex,nsISupports * aElement)67   void ReplaceElementAt(uint32_t aIndex, nsISupports* aElement) {
68     nsISupports* oldElement = mArray[aIndex];
69     NS_IF_ADDREF(mArray[aIndex] = aElement);
70     NS_IF_RELEASE(oldElement);
71   }
AppendObject(nsISupports * aObject)72   bool AppendObject(nsISupports* aObject) {
73     return InsertObjectAt(aObject, Count());
74   }
AppendElement(nsISupports * aElement)75   void AppendElement(nsISupports* aElement) {
76     InsertElementAt(Length(), aElement);
77   }
AppendElement(already_AddRefed<nsISupports> aElement)78   void AppendElement(already_AddRefed<nsISupports> aElement) {
79     InsertElementAt(Length(), mozilla::Move(aElement));
80   }
81 
AppendObjects(const nsCOMArray_base & aObjects)82   bool AppendObjects(const nsCOMArray_base& aObjects) {
83     return InsertObjectsAt(aObjects, Count());
84   }
AppendElements(const nsCOMArray_base & aElements)85   void AppendElements(const nsCOMArray_base& aElements) {
86     return InsertElementsAt(Length(), aElements);
87   }
AppendElements(nsISupports * const * aElements,uint32_t aCount)88   void AppendElements(nsISupports* const* aElements, uint32_t aCount) {
89     return InsertElementsAt(Length(), aElements, aCount);
90   }
91   bool RemoveObject(nsISupports* aObject);
Elements()92   nsISupports** Elements() { return mArray.Elements(); }
SwapElements(nsCOMArray_base & aOther)93   void SwapElements(nsCOMArray_base& aOther) {
94     mArray.SwapElements(aOther.mArray);
95   }
96 
97   void Adopt(nsISupports** aElements, uint32_t aCount);
98   uint32_t Forget(nsISupports*** aElements);
99 
100  public:
101   // elements in the array (including null elements!)
Count()102   int32_t Count() const { return mArray.Length(); }
103   // nsTArray-compatible version
Length()104   uint32_t Length() const { return mArray.Length(); }
IsEmpty()105   bool IsEmpty() const { return mArray.IsEmpty(); }
106 
107   // If the array grows, the newly created entries will all be null;
108   // if the array shrinks, the excess entries will all be released.
109   bool SetCount(int32_t aNewCount);
110   // nsTArray-compatible version
TruncateLength(uint32_t aNewLength)111   void TruncateLength(uint32_t aNewLength) {
112     if (mArray.Length() > aNewLength) {
113       RemoveElementsAt(aNewLength, mArray.Length() - aNewLength);
114     }
115   }
116 
117   // remove all elements in the array, and call NS_RELEASE on each one
118   void Clear();
119 
ObjectAt(int32_t aIndex)120   nsISupports* ObjectAt(int32_t aIndex) const { return mArray[aIndex]; }
121   // nsTArray-compatible version
ElementAt(uint32_t aIndex)122   nsISupports* ElementAt(uint32_t aIndex) const { return mArray[aIndex]; }
123 
SafeObjectAt(int32_t aIndex)124   nsISupports* SafeObjectAt(int32_t aIndex) const {
125     return mArray.SafeElementAt(aIndex, nullptr);
126   }
127   // nsTArray-compatible version
SafeElementAt(uint32_t aIndex)128   nsISupports* SafeElementAt(uint32_t aIndex) const {
129     return mArray.SafeElementAt(aIndex, nullptr);
130   }
131 
132   nsISupports* operator[](int32_t aIndex) const { return mArray[aIndex]; }
133 
134   // remove an element at a specific position, shrinking the array
135   // as necessary
136   bool RemoveObjectAt(int32_t aIndex);
137   // nsTArray-compatible version
138   void RemoveElementAt(uint32_t aIndex);
139 
140   // remove a range of elements at a specific position, shrinking the array
141   // as necessary
142   bool RemoveObjectsAt(int32_t aIndex, int32_t aCount);
143   // nsTArray-compatible version
144   void RemoveElementsAt(uint32_t aIndex, uint32_t aCount);
145 
SwapElementsAt(uint32_t aIndex1,uint32_t aIndex2)146   void SwapElementsAt(uint32_t aIndex1, uint32_t aIndex2) {
147     nsISupports* tmp = mArray[aIndex1];
148     mArray[aIndex1] = mArray[aIndex2];
149     mArray[aIndex2] = tmp;
150   }
151 
152   // Ensures there is enough space to store a total of aCapacity objects.
153   // This method never deletes any objects.
SetCapacity(uint32_t aCapacity)154   void SetCapacity(uint32_t aCapacity) { mArray.SetCapacity(aCapacity); }
Capacity()155   uint32_t Capacity() { return mArray.Capacity(); }
156 
157   // Measures the size of the array's element storage. If you want to measure
158   // anything hanging off the array, you must iterate over the elements and
159   // measure them individually; hence the "Shallow" prefix. Note that because
160   // each element in an nsCOMArray<T> is actually a T* any such iteration
161   // should use a SizeOfIncludingThis() function on each element rather than a
162   // SizeOfExcludingThis() function, so that the memory taken by the T itself
163   // is included as well as anything it points to.
ShallowSizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf)164   size_t ShallowSizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const {
165     return mArray.ShallowSizeOfExcludingThis(aMallocSizeOf);
166   }
167 
168  private:
169   // the actual storage
170   nsTArray<nsISupports*> mArray;
171 
172   // don't implement these, defaults will muck with refcounts!
173   nsCOMArray_base& operator=(const nsCOMArray_base& aOther) = delete;
174 };
175 
ImplCycleCollectionUnlink(nsCOMArray_base & aField)176 inline void ImplCycleCollectionUnlink(nsCOMArray_base& aField) {
177   aField.Clear();
178 }
179 
180 inline void ImplCycleCollectionTraverse(
181     nsCycleCollectionTraversalCallback& aCallback, nsCOMArray_base& aField,
182     const char* aName, uint32_t aFlags = 0) {
183   aFlags |= CycleCollectionEdgeNameArrayFlag;
184   int32_t length = aField.Count();
185   for (int32_t i = 0; i < length; ++i) {
186     CycleCollectionNoteChild(aCallback, aField[i], aName, aFlags);
187   }
188 }
189 
190 // a non-XPCOM, refcounting array of XPCOM objects
191 // used as a member variable or stack variable - this object is NOT
192 // refcounted, but the objects that it holds are
193 //
194 // most of the read-only accessors like ObjectAt()/etc do NOT refcount
195 // on the way out. This means that you can do one of two things:
196 //
197 // * does an addref, but holds onto a reference
198 // nsCOMPtr<T> foo = array[i];
199 //
200 // * avoids the refcount, but foo might go stale if array[i] is ever
201 // * modified/removed. Be careful not to NS_RELEASE(foo)!
202 // T* foo = array[i];
203 //
204 // This array will accept null as an argument for any object, and will store
205 // null in the array. But that also means that methods like ObjectAt() may
206 // return null when referring to an existing, but null entry in the array.
207 template <class T>
208 class nsCOMArray : public nsCOMArray_base {
209  public:
210   typedef int32_t index_type;
211   typedef mozilla::ArrayIterator<T*, nsCOMArray> iterator;
212   typedef mozilla::ArrayIterator<const T*, nsCOMArray> const_iterator;
213   typedef mozilla::ReverseIterator<iterator> reverse_iterator;
214   typedef mozilla::ReverseIterator<const_iterator> const_reverse_iterator;
215 
nsCOMArray()216   nsCOMArray() {}
nsCOMArray(int32_t aCount)217   explicit nsCOMArray(int32_t aCount) : nsCOMArray_base(aCount) {}
nsCOMArray(const nsCOMArray<T> & aOther)218   explicit nsCOMArray(const nsCOMArray<T>& aOther) : nsCOMArray_base(aOther) {}
nsCOMArray(nsCOMArray<T> && aOther)219   nsCOMArray(nsCOMArray<T>&& aOther) { SwapElements(aOther); }
~nsCOMArray()220   ~nsCOMArray() {}
221 
222   // We have a move assignment operator, but no copy assignment operator.
223   nsCOMArray<T>& operator=(nsCOMArray<T>&& aOther) {
224     SwapElements(aOther);
225     return *this;
226   }
227 
228   // these do NOT refcount on the way out, for speed
ObjectAt(int32_t aIndex)229   T* ObjectAt(int32_t aIndex) const {
230     return static_cast<T*>(nsCOMArray_base::ObjectAt(aIndex));
231   }
232   // nsTArray-compatible version
ElementAt(uint32_t aIndex)233   T* ElementAt(uint32_t aIndex) const {
234     return static_cast<T*>(nsCOMArray_base::ElementAt(aIndex));
235   }
236 
237   // these do NOT refcount on the way out, for speed
SafeObjectAt(int32_t aIndex)238   T* SafeObjectAt(int32_t aIndex) const {
239     return static_cast<T*>(nsCOMArray_base::SafeObjectAt(aIndex));
240   }
241   // nsTArray-compatible version
SafeElementAt(uint32_t aIndex)242   T* SafeElementAt(uint32_t aIndex) const {
243     return static_cast<T*>(nsCOMArray_base::SafeElementAt(aIndex));
244   }
245 
246   // indexing operator for syntactic sugar
247   T* operator[](int32_t aIndex) const { return ObjectAt(aIndex); }
248 
249   // index of the element in question.. does NOT refcount
250   // note: this does not check COM object identity. Use
251   // IndexOfObject() for that purpose
252   int32_t IndexOf(T* aObject, uint32_t aStartIndex = 0) const {
253     return nsCOMArray_base::IndexOf(aObject, aStartIndex);
254   }
Contains(T * aObject)255   bool Contains(T* aObject) const { return nsCOMArray_base::Contains(aObject); }
256 
257   // index of the element in question.. be careful!
258   // this is much slower than IndexOf() because it uses
259   // QueryInterface to determine actual COM identity of the object
260   // if you need to do this frequently then consider enforcing
261   // COM object identity before adding/comparing elements
IndexOfObject(T * aObject)262   int32_t IndexOfObject(T* aObject) const {
263     return nsCOMArray_base::IndexOfObject(aObject);
264   }
ContainsObject(nsISupports * aObject)265   bool ContainsObject(nsISupports* aObject) const {
266     return nsCOMArray_base::ContainsObject(aObject);
267   }
268 
269   // inserts aObject at aIndex, shifting the objects at aIndex and
270   // later to make space
InsertObjectAt(T * aObject,int32_t aIndex)271   bool InsertObjectAt(T* aObject, int32_t aIndex) {
272     return nsCOMArray_base::InsertObjectAt(aObject, aIndex);
273   }
274   // nsTArray-compatible version
InsertElementAt(uint32_t aIndex,T * aElement)275   void InsertElementAt(uint32_t aIndex, T* aElement) {
276     nsCOMArray_base::InsertElementAt(aIndex, aElement);
277   }
278 
279   // inserts the objects from aObject at aIndex, shifting the
280   // objects at aIndex and later to make space
InsertObjectsAt(const nsCOMArray<T> & aObjects,int32_t aIndex)281   bool InsertObjectsAt(const nsCOMArray<T>& aObjects, int32_t aIndex) {
282     return nsCOMArray_base::InsertObjectsAt(aObjects, aIndex);
283   }
284   // nsTArray-compatible version
InsertElementsAt(uint32_t aIndex,const nsCOMArray<T> & aElements)285   void InsertElementsAt(uint32_t aIndex, const nsCOMArray<T>& aElements) {
286     nsCOMArray_base::InsertElementsAt(aIndex, aElements);
287   }
InsertElementsAt(uint32_t aIndex,T * const * aElements,uint32_t aCount)288   void InsertElementsAt(uint32_t aIndex, T* const* aElements, uint32_t aCount) {
289     nsCOMArray_base::InsertElementsAt(
290         aIndex, reinterpret_cast<nsISupports* const*>(aElements), aCount);
291   }
292 
293   // replaces an existing element. Warning: if the array grows,
294   // the newly created entries will all be null
ReplaceObjectAt(T * aObject,int32_t aIndex)295   void ReplaceObjectAt(T* aObject, int32_t aIndex) {
296     nsCOMArray_base::ReplaceObjectAt(aObject, aIndex);
297   }
298   // nsTArray-compatible version
ReplaceElementAt(uint32_t aIndex,T * aElement)299   void ReplaceElementAt(uint32_t aIndex, T* aElement) {
300     nsCOMArray_base::ReplaceElementAt(aIndex, aElement);
301   }
302 
303   typedef int (*nsCOMArrayComparatorFunc)(T* aElement1, T* aElement2,
304                                           void* aData);
305 
Sort(nsCOMArrayComparatorFunc aFunc,void * aData)306   void Sort(nsCOMArrayComparatorFunc aFunc, void* aData) {
307     nsCOMArray_base::Sort(nsBaseArrayComparatorFunc(aFunc), aData);
308   }
309 
310   // append an object, growing the array as necessary
AppendObject(T * aObject)311   bool AppendObject(T* aObject) {
312     return nsCOMArray_base::AppendObject(aObject);
313   }
314   // nsTArray-compatible version
AppendElement(T * aElement)315   void AppendElement(T* aElement) { nsCOMArray_base::AppendElement(aElement); }
AppendElement(already_AddRefed<T> aElement)316   void AppendElement(already_AddRefed<T> aElement) {
317     nsCOMArray_base::AppendElement(mozilla::Move(aElement));
318   }
319 
320   // append objects, growing the array as necessary
AppendObjects(const nsCOMArray<T> & aObjects)321   bool AppendObjects(const nsCOMArray<T>& aObjects) {
322     return nsCOMArray_base::AppendObjects(aObjects);
323   }
324   // nsTArray-compatible version
AppendElements(const nsCOMArray<T> & aElements)325   void AppendElements(const nsCOMArray<T>& aElements) {
326     return nsCOMArray_base::AppendElements(aElements);
327   }
AppendElements(T * const * aElements,uint32_t aCount)328   void AppendElements(T* const* aElements, uint32_t aCount) {
329     InsertElementsAt(Length(), aElements, aCount);
330   }
331 
332   // remove the first instance of the given object and shrink the
333   // array as necessary
334   // Warning: if you pass null here, it will remove the first null element
RemoveObject(T * aObject)335   bool RemoveObject(T* aObject) {
336     return nsCOMArray_base::RemoveObject(aObject);
337   }
338   // nsTArray-compatible version
RemoveElement(T * aElement)339   bool RemoveElement(T* aElement) {
340     return nsCOMArray_base::RemoveObject(aElement);
341   }
342 
Elements()343   T** Elements() { return reinterpret_cast<T**>(nsCOMArray_base::Elements()); }
SwapElements(nsCOMArray<T> & aOther)344   void SwapElements(nsCOMArray<T>& aOther) {
345     nsCOMArray_base::SwapElements(aOther);
346   }
347 
348   /**
349    * Adopt parameters that resulted from an XPIDL outparam. The aElements
350    * parameter will be freed as a result of the call.
351    *
352    * Example usage:
353    * nsCOMArray<nsISomeInterface> array;
354    * nsISomeInterface** elements;
355    * uint32_t length;
356    * ptr->GetSomeArray(&elements, &length);
357    * array.Adopt(elements, length);
358    */
Adopt(T ** aElements,uint32_t aSize)359   void Adopt(T** aElements, uint32_t aSize) {
360     nsCOMArray_base::Adopt(reinterpret_cast<nsISupports**>(aElements), aSize);
361   }
362 
363   /**
364    * Export the contents of this array to an XPIDL outparam. The array will be
365    * Clear()'d after this operation.
366    *
367    * Example usage:
368    * nsCOMArray<nsISomeInterface> array;
369    * *length = array.Forget(retval);
370    */
Forget(T *** aElements)371   uint32_t Forget(T*** aElements) {
372     return nsCOMArray_base::Forget(reinterpret_cast<nsISupports***>(aElements));
373   }
374 
375   // Methods for range-based for loops.
begin()376   iterator begin() { return iterator(*this, 0); }
begin()377   const_iterator begin() const { return const_iterator(*this, 0); }
cbegin()378   const_iterator cbegin() const { return begin(); }
end()379   iterator end() { return iterator(*this, Length()); }
end()380   const_iterator end() const { return const_iterator(*this, Length()); }
cend()381   const_iterator cend() const { return end(); }
382 
383   // Methods for reverse iterating.
rbegin()384   reverse_iterator rbegin() { return reverse_iterator(end()); }
rbegin()385   const_reverse_iterator rbegin() const {
386     return const_reverse_iterator(end());
387   }
crbegin()388   const_reverse_iterator crbegin() const { return rbegin(); }
rend()389   reverse_iterator rend() { return reverse_iterator(begin()); }
rend()390   const_reverse_iterator rend() const {
391     return const_reverse_iterator(begin());
392   }
crend()393   const_reverse_iterator crend() const { return rend(); }
394 
395  private:
396   // don't implement these!
397   nsCOMArray<T>& operator=(const nsCOMArray<T>& aOther) = delete;
398 };
399 
400 template <typename T>
ImplCycleCollectionUnlink(nsCOMArray<T> & aField)401 inline void ImplCycleCollectionUnlink(nsCOMArray<T>& aField) {
402   aField.Clear();
403 }
404 
405 template <typename E>
406 inline void ImplCycleCollectionTraverse(
407     nsCycleCollectionTraversalCallback& aCallback, nsCOMArray<E>& aField,
408     const char* aName, uint32_t aFlags = 0) {
409   aFlags |= CycleCollectionEdgeNameArrayFlag;
410   int32_t length = aField.Count();
411   for (int32_t i = 0; i < length; ++i) {
412     CycleCollectionNoteChild(aCallback, aField[i], aName, aFlags);
413   }
414 }
415 
416 #endif
417