nsTObserverArray.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #ifndef nsTObserverArray_h___
  6. #define nsTObserverArray_h___
  7. #include "mozilla/MemoryReporting.h"
  8. #include "nsTArray.h"
  9. #include "nsCycleCollectionNoteChild.h"
  10. /**
  11. * An array of observers. Like a normal array, but supports iterators that are
  12. * stable even if the array is modified during iteration.
  13. * The template parameter T is the observer type the array will hold;
  14. * N is the number of built-in storage slots that come with the array.
  15. * NOTE: You probably want to use nsTObserverArray, unless you specifically
  16. * want built-in storage. See below.
  17. * @see nsTObserverArray, nsTArray
  18. */
  19. class nsTObserverArray_base
  20. {
  21. public:
  22. typedef size_t index_type;
  23. typedef size_t size_type;
  24. typedef ptrdiff_t diff_type;
  25. protected:
  26. class Iterator_base
  27. {
  28. protected:
  29. friend class nsTObserverArray_base;
  30. Iterator_base(index_type aPosition, Iterator_base* aNext)
  31. : mPosition(aPosition)
  32. , mNext(aNext)
  33. {
  34. }
  35. // The current position of the iterator. Its exact meaning differs
  36. // depending on iterator. See nsTObserverArray<T>::ForwardIterator.
  37. index_type mPosition;
  38. // The next iterator currently iterating the same array
  39. Iterator_base* mNext;
  40. };
  41. nsTObserverArray_base() : mIterators(nullptr) {}
  42. ~nsTObserverArray_base()
  43. {
  44. NS_ASSERTION(mIterators == nullptr, "iterators outlasting array");
  45. }
  46. /**
  47. * Adjusts iterators after an element has been inserted or removed
  48. * from the array.
  49. * @param aModPos Position where elements were added or removed.
  50. * @param aAdjustment -1 if an element was removed, 1 if an element was
  51. * added.
  52. */
  53. void AdjustIterators(index_type aModPos, diff_type aAdjustment);
  54. /**
  55. * Clears iterators when the array is destroyed.
  56. */
  57. void ClearIterators();
  58. mutable Iterator_base* mIterators;
  59. };
  60. template<class T, size_t N>
  61. class nsAutoTObserverArray : protected nsTObserverArray_base
  62. {
  63. public:
  64. typedef T elem_type;
  65. typedef nsTArray<T> array_type;
  66. nsAutoTObserverArray() {}
  67. //
  68. // Accessor methods
  69. //
  70. // @return The number of elements in the array.
  71. size_type Length() const { return mArray.Length(); }
  72. // @return True if the array is empty or false otherwise.
  73. bool IsEmpty() const { return mArray.IsEmpty(); }
  74. // This method provides direct access to an element of the array. The given
  75. // index must be within the array bounds. If the underlying array may change
  76. // during iteration, use an iterator instead of this function.
  77. // @param aIndex The index of an element in the array.
  78. // @return A reference to the i'th element of the array.
  79. elem_type& ElementAt(index_type aIndex)
  80. {
  81. return mArray.ElementAt(aIndex);
  82. }
  83. // Same as above, but readonly.
  84. const elem_type& ElementAt(index_type aIndex) const
  85. {
  86. return mArray.ElementAt(aIndex);
  87. }
  88. // This method provides direct access to an element of the array in a bounds
  89. // safe manner. If the requested index is out of bounds the provided default
  90. // value is returned.
  91. // @param aIndex The index of an element in the array.
  92. // @param aDef The value to return if the index is out of bounds.
  93. elem_type& SafeElementAt(index_type aIndex, elem_type& aDef)
  94. {
  95. return mArray.SafeElementAt(aIndex, aDef);
  96. }
  97. // Same as above, but readonly.
  98. const elem_type& SafeElementAt(index_type aIndex, const elem_type& aDef) const
  99. {
  100. return mArray.SafeElementAt(aIndex, aDef);
  101. }
  102. // No operator[] is provided because the point of this class is to support
  103. // allow modifying the array during iteration, and ElementAt() is not safe
  104. // in those conditions.
  105. //
  106. // Search methods
  107. //
  108. // This method searches, starting from the beginning of the array,
  109. // for the first element in this array that is equal to the given element.
  110. // 'operator==' must be defined for elem_type.
  111. // @param aItem The item to search for.
  112. // @return true if the element was found.
  113. template<class Item>
  114. bool Contains(const Item& aItem) const
  115. {
  116. return IndexOf(aItem) != array_type::NoIndex;
  117. }
  118. // This method searches for the offset of the first element in this
  119. // array that is equal to the given element.
  120. // 'operator==' must be defined for elem_type.
  121. // @param aItem The item to search for.
  122. // @param aStart The index to start from.
  123. // @return The index of the found element or NoIndex if not found.
  124. template<class Item>
  125. index_type IndexOf(const Item& aItem, index_type aStart = 0) const
  126. {
  127. return mArray.IndexOf(aItem, aStart);
  128. }
  129. //
  130. // Mutation methods
  131. //
  132. // Insert a given element at the given index.
  133. // @param aIndex The index at which to insert item.
  134. // @param aItem The item to insert,
  135. // @return A pointer to the newly inserted element, or a null on DOM
  136. template<class Item>
  137. elem_type* InsertElementAt(index_type aIndex, const Item& aItem)
  138. {
  139. elem_type* item = mArray.InsertElementAt(aIndex, aItem);
  140. AdjustIterators(aIndex, 1);
  141. return item;
  142. }
  143. // Same as above but without copy constructing.
  144. // This is useful to avoid temporaries.
  145. elem_type* InsertElementAt(index_type aIndex)
  146. {
  147. elem_type* item = mArray.InsertElementAt(aIndex);
  148. AdjustIterators(aIndex, 1);
  149. return item;
  150. }
  151. // Prepend an element to the array unless it already exists in the array.
  152. // 'operator==' must be defined for elem_type.
  153. // @param aItem The item to prepend.
  154. // @return true if the element was found, or inserted successfully.
  155. template<class Item>
  156. bool PrependElementUnlessExists(const Item& aItem)
  157. {
  158. if (Contains(aItem)) {
  159. return true;
  160. }
  161. bool inserted = mArray.InsertElementAt(0, aItem) != nullptr;
  162. AdjustIterators(0, 1);
  163. return inserted;
  164. }
  165. // Append an element to the array.
  166. // @param aItem The item to append.
  167. // @return A pointer to the newly appended element, or null on OOM.
  168. template<class Item>
  169. elem_type* AppendElement(const Item& aItem)
  170. {
  171. return mArray.AppendElement(aItem);
  172. }
  173. // Same as above, but without copy-constructing. This is useful to avoid
  174. // temporaries.
  175. elem_type* AppendElement()
  176. {
  177. return mArray.AppendElement();
  178. }
  179. // Append an element to the array unless it already exists in the array.
  180. // 'operator==' must be defined for elem_type.
  181. // @param aItem The item to append.
  182. // @return true if the element was found, or inserted successfully.
  183. template<class Item>
  184. bool AppendElementUnlessExists(const Item& aItem)
  185. {
  186. return Contains(aItem) || AppendElement(aItem) != nullptr;
  187. }
  188. // Remove an element from the array.
  189. // @param aIndex The index of the item to remove.
  190. void RemoveElementAt(index_type aIndex)
  191. {
  192. NS_ASSERTION(aIndex < mArray.Length(), "invalid index");
  193. mArray.RemoveElementAt(aIndex);
  194. AdjustIterators(aIndex, -1);
  195. }
  196. // This helper function combines IndexOf with RemoveElementAt to "search
  197. // and destroy" the first element that is equal to the given element.
  198. // 'operator==' must be defined for elem_type.
  199. // @param aItem The item to search for.
  200. // @return true if the element was found and removed.
  201. template<class Item>
  202. bool RemoveElement(const Item& aItem)
  203. {
  204. index_type index = mArray.IndexOf(aItem, 0);
  205. if (index == array_type::NoIndex) {
  206. return false;
  207. }
  208. mArray.RemoveElementAt(index);
  209. AdjustIterators(index, -1);
  210. return true;
  211. }
  212. // See nsTArray::RemoveElementsBy.
  213. void RemoveElementsBy(mozilla::function<bool(const elem_type&)> aPredicate)
  214. {
  215. index_type i = 0;
  216. mArray.RemoveElementsBy([&](const elem_type& aItem) {
  217. if (aPredicate(aItem)) {
  218. // This element is going to be removed.
  219. AdjustIterators(i, -1);
  220. return true;
  221. }
  222. ++i;
  223. return false;
  224. });
  225. }
  226. // Removes all observers and collapses all iterators to the beginning of
  227. // the array. The result is that forward iterators will see all elements
  228. // in the array.
  229. void Clear()
  230. {
  231. mArray.Clear();
  232. ClearIterators();
  233. }
  234. // Compact the array to minimize the memory it uses
  235. void Compact() { mArray.Compact(); }
  236. // Returns the number of bytes on the heap taken up by this object, not
  237. // including sizeof(*this). If you want to measure anything hanging off the
  238. // array, you must iterate over the elements and measure them individually;
  239. // hence the "Shallow" prefix.
  240. size_t ShallowSizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const
  241. {
  242. return mArray.ShallowSizeOfExcludingThis(aMallocSizeOf);
  243. }
  244. //
  245. // Iterators
  246. //
  247. // Base class for iterators. Do not use this directly.
  248. class Iterator : public Iterator_base
  249. {
  250. protected:
  251. friend class nsAutoTObserverArray;
  252. typedef nsAutoTObserverArray<T, N> array_type;
  253. Iterator(index_type aPosition, const array_type& aArray)
  254. : Iterator_base(aPosition, aArray.mIterators)
  255. , mArray(const_cast<array_type&>(aArray))
  256. {
  257. aArray.mIterators = this;
  258. }
  259. ~Iterator()
  260. {
  261. NS_ASSERTION(mArray.mIterators == this,
  262. "Iterators must currently be destroyed in opposite order "
  263. "from the construction order. It is suggested that you "
  264. "simply put them on the stack");
  265. mArray.mIterators = mNext;
  266. }
  267. // The array we're iterating
  268. array_type& mArray;
  269. };
  270. // Iterates the array forward from beginning to end. mPosition points
  271. // to the element that will be returned on next call to GetNext.
  272. // Elements:
  273. // - prepended to the array during iteration *will not* be traversed
  274. // - appended during iteration *will* be traversed
  275. // - removed during iteration *will not* be traversed.
  276. // @see EndLimitedIterator
  277. class ForwardIterator : protected Iterator
  278. {
  279. public:
  280. typedef nsAutoTObserverArray<T, N> array_type;
  281. typedef Iterator base_type;
  282. explicit ForwardIterator(const array_type& aArray)
  283. : Iterator(0, aArray)
  284. {
  285. }
  286. ForwardIterator(const array_type& aArray, index_type aPos)
  287. : Iterator(aPos, aArray)
  288. {
  289. }
  290. bool operator<(const ForwardIterator& aOther) const
  291. {
  292. NS_ASSERTION(&this->mArray == &aOther.mArray,
  293. "not iterating the same array");
  294. return base_type::mPosition < aOther.mPosition;
  295. }
  296. // Returns true if there are more elements to iterate.
  297. // This must precede a call to GetNext(). If false is
  298. // returned, GetNext() must not be called.
  299. bool HasMore() const
  300. {
  301. return base_type::mPosition < base_type::mArray.Length();
  302. }
  303. // Returns the next element and steps one step. This must
  304. // be preceded by a call to HasMore().
  305. // @return The next observer.
  306. elem_type& GetNext()
  307. {
  308. NS_ASSERTION(HasMore(), "iterating beyond end of array");
  309. return base_type::mArray.ElementAt(base_type::mPosition++);
  310. }
  311. };
  312. // EndLimitedIterator works like ForwardIterator, but will not iterate new
  313. // observers appended to the array after the iterator was created.
  314. class EndLimitedIterator : protected ForwardIterator
  315. {
  316. public:
  317. typedef nsAutoTObserverArray<T, N> array_type;
  318. typedef Iterator base_type;
  319. explicit EndLimitedIterator(const array_type& aArray)
  320. : ForwardIterator(aArray)
  321. , mEnd(aArray, aArray.Length())
  322. {
  323. }
  324. // Returns true if there are more elements to iterate.
  325. // This must precede a call to GetNext(). If false is
  326. // returned, GetNext() must not be called.
  327. bool HasMore() const { return *this < mEnd; }
  328. // Returns the next element and steps one step. This must
  329. // be preceded by a call to HasMore().
  330. // @return The next observer.
  331. elem_type& GetNext()
  332. {
  333. NS_ASSERTION(HasMore(), "iterating beyond end of array");
  334. return base_type::mArray.ElementAt(base_type::mPosition++);
  335. }
  336. private:
  337. ForwardIterator mEnd;
  338. };
  339. // Iterates the array backward from end to start. mPosition points
  340. // to the element that was returned last.
  341. // Elements:
  342. // - prepended to the array during iteration *will* be traversed,
  343. // unless the iteration already arrived at the first element
  344. // - appended during iteration *will not* be traversed
  345. // - removed during iteration *will not* be traversed.
  346. class BackwardIterator : protected Iterator
  347. {
  348. public:
  349. typedef nsAutoTObserverArray<T, N> array_type;
  350. typedef Iterator base_type;
  351. explicit BackwardIterator(const array_type& aArray)
  352. : Iterator(aArray.Length(), aArray)
  353. {
  354. }
  355. // Returns true if there are more elements to iterate.
  356. // This must precede a call to GetNext(). If false is
  357. // returned, GetNext() must not be called.
  358. bool HasMore() const { return base_type::mPosition > 0; }
  359. // Returns the next element and steps one step. This must
  360. // be preceded by a call to HasMore().
  361. // @return The next observer.
  362. elem_type& GetNext()
  363. {
  364. NS_ASSERTION(HasMore(), "iterating beyond start of array");
  365. return base_type::mArray.ElementAt(--base_type::mPosition);
  366. }
  367. // Removes the element at the current iterator position.
  368. // (the last element returned from |GetNext()|)
  369. // This will not affect the next call to |GetNext()|
  370. void Remove()
  371. {
  372. return base_type::mArray.RemoveElementAt(base_type::mPosition);
  373. }
  374. };
  375. protected:
  376. AutoTArray<T, N> mArray;
  377. };
  378. template<class T>
  379. class nsTObserverArray : public nsAutoTObserverArray<T, 0>
  380. {
  381. public:
  382. typedef nsAutoTObserverArray<T, 0> base_type;
  383. typedef nsTObserverArray_base::size_type size_type;
  384. //
  385. // Initialization methods
  386. //
  387. nsTObserverArray() {}
  388. // Initialize this array and pre-allocate some number of elements.
  389. explicit nsTObserverArray(size_type aCapacity)
  390. {
  391. base_type::mArray.SetCapacity(aCapacity);
  392. }
  393. };
  394. template<typename T, size_t N>
  395. inline void
  396. ImplCycleCollectionUnlink(nsAutoTObserverArray<T, N>& aField)
  397. {
  398. aField.Clear();
  399. }
  400. template<typename T, size_t N>
  401. inline void
  402. ImplCycleCollectionTraverse(nsCycleCollectionTraversalCallback& aCallback,
  403. nsAutoTObserverArray<T, N>& aField,
  404. const char* aName,
  405. uint32_t aFlags = 0)
  406. {
  407. aFlags |= CycleCollectionEdgeNameArrayFlag;
  408. size_t length = aField.Length();
  409. for (size_t i = 0; i < length; ++i) {
  410. ImplCycleCollectionTraverse(aCallback, aField.ElementAt(i), aName, aFlags);
  411. }
  412. }
  413. // XXXbz I wish I didn't have to pass in the observer type, but I
  414. // don't see a way to get it out of array_.
  415. // Note that this macro only works if the array holds pointers to XPCOM objects.
  416. #define NS_OBSERVER_ARRAY_NOTIFY_XPCOM_OBSERVERS(array_, obstype_, func_, params_) \
  417. PR_BEGIN_MACRO \
  418. nsTObserverArray<obstype_ *>::ForwardIterator iter_(array_); \
  419. RefPtr<obstype_> obs_; \
  420. while (iter_.HasMore()) { \
  421. obs_ = iter_.GetNext(); \
  422. obs_ -> func_ params_ ; \
  423. } \
  424. PR_END_MACRO
  425. // Note that this macro only works if the array holds pointers to XPCOM objects.
  426. #define NS_OBSERVER_ARRAY_NOTIFY_OBSERVERS(array_, obstype_, func_, params_) \
  427. PR_BEGIN_MACRO \
  428. nsTObserverArray<obstype_ *>::ForwardIterator iter_(array_); \
  429. obstype_* obs_; \
  430. while (iter_.HasMore()) { \
  431. obs_ = iter_.GetNext(); \
  432. obs_ -> func_ params_ ; \
  433. } \
  434. PR_END_MACRO
  435. #define NS_OBSERVER_ARRAY_NOTIFY_OBSERVERS_WITH_QI(array_, basetype_, obstype_, func_, params_) \
  436. PR_BEGIN_MACRO \
  437. nsTObserverArray<basetype_ *>::ForwardIterator iter_(array_); \
  438. basetype_* obsbase_; \
  439. while (iter_.HasMore()) { \
  440. obsbase_ = iter_.GetNext(); \
  441. nsCOMPtr<obstype_> obs_ = do_QueryInterface(obsbase_); \
  442. if (obs_) { \
  443. obs_ -> func_ params_ ; \
  444. } \
  445. } \
  446. PR_END_MACRO
  447. #endif // nsTObserverArray_h___