Bug 1744358 move MediaEngineDefault-specific MediaEngineSource classes out of header...
[gecko.git] / mfbt / LinkedList.h
blob0995af66da2e2017105b7074535bab71e31c8be1
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/. */
7 /* A type-safe doubly-linked list class. */
9 /*
10 * The classes LinkedList<T> and LinkedListElement<T> together form a
11 * convenient, type-safe doubly-linked list implementation.
13 * The class T which will be inserted into the linked list must inherit from
14 * LinkedListElement<T>. A given object may be in only one linked list at a
15 * time.
17 * A LinkedListElement automatically removes itself from the list upon
18 * destruction, and a LinkedList will fatally assert in debug builds if it's
19 * non-empty when it's destructed.
21 * For example, you might use LinkedList in a simple observer list class as
22 * follows.
24 * class Observer : public LinkedListElement<Observer>
25 * {
26 * public:
27 * void observe(char* aTopic) { ... }
28 * };
30 * class ObserverContainer
31 * {
32 * private:
33 * LinkedList<Observer> list;
35 * public:
36 * void addObserver(Observer* aObserver)
37 * {
38 * // Will assert if |aObserver| is part of another list.
39 * list.insertBack(aObserver);
40 * }
42 * void removeObserver(Observer* aObserver)
43 * {
44 * // Will assert if |aObserver| is not part of some list.
45 * aObserver.remove();
46 * // Or, will assert if |aObserver| is not part of |list| specifically.
47 * // aObserver.removeFrom(list);
48 * }
50 * void notifyObservers(char* aTopic)
51 * {
52 * for (Observer* o = list.getFirst(); o != nullptr; o = o->getNext()) {
53 * o->observe(aTopic);
54 * }
55 * }
56 * };
58 * Additionally, the class AutoCleanLinkedList<T> is a LinkedList<T> that will
59 * remove and delete each element still within itself upon destruction. Note
60 * that because each element is deleted, elements must have been allocated
61 * using |new|.
64 #ifndef mozilla_LinkedList_h
65 #define mozilla_LinkedList_h
67 #include <algorithm>
68 #include <utility>
70 #include "mozilla/Assertions.h"
71 #include "mozilla/Attributes.h"
72 #include "mozilla/MemoryReporting.h"
73 #include "mozilla/RefPtr.h"
75 #ifdef __cplusplus
77 namespace mozilla {
79 template <typename T>
80 class LinkedListElement;
82 namespace detail {
84 /**
85 * LinkedList supports refcounted elements using this adapter class. Clients
86 * using LinkedList<RefPtr<T>> will get a data structure that holds a strong
87 * reference to T as long as T is in the list.
89 template <typename T>
90 struct LinkedListElementTraits {
91 typedef T* RawType;
92 typedef const T* ConstRawType;
93 typedef T* ClientType;
94 typedef const T* ConstClientType;
96 // These static methods are called when an element is added to or removed from
97 // a linked list. It can be used to keep track ownership in lists that are
98 // supposed to own their elements. If elements are transferred from one list
99 // to another, no enter or exit calls happen since the elements still belong
100 // to a list.
101 static void enterList(LinkedListElement<T>* elt) {}
102 static void exitList(LinkedListElement<T>* elt) {}
104 // This method is called when AutoCleanLinkedList cleans itself
105 // during destruction. It can be used to call delete on elements if
106 // the list is the sole owner.
107 static void cleanElement(LinkedListElement<T>* elt) { delete elt->asT(); }
110 template <typename T>
111 struct LinkedListElementTraits<RefPtr<T>> {
112 typedef T* RawType;
113 typedef const T* ConstRawType;
114 typedef RefPtr<T> ClientType;
115 typedef RefPtr<const T> ConstClientType;
117 static void enterList(LinkedListElement<RefPtr<T>>* elt) {
118 elt->asT()->AddRef();
120 static void exitList(LinkedListElement<RefPtr<T>>* elt) {
121 elt->asT()->Release();
123 static void cleanElement(LinkedListElement<RefPtr<T>>* elt) {}
126 } /* namespace detail */
128 template <typename T>
129 class LinkedList;
131 template <typename T>
132 class LinkedListElement {
133 typedef typename detail::LinkedListElementTraits<T> Traits;
134 typedef typename Traits::RawType RawType;
135 typedef typename Traits::ConstRawType ConstRawType;
136 typedef typename Traits::ClientType ClientType;
137 typedef typename Traits::ConstClientType ConstClientType;
140 * It's convenient that we return nullptr when getNext() or getPrevious()
141 * hits the end of the list, but doing so costs an extra word of storage in
142 * each linked list node (to keep track of whether |this| is the sentinel
143 * node) and a branch on this value in getNext/getPrevious.
145 * We could get rid of the extra word of storage by shoving the "is
146 * sentinel" bit into one of the pointers, although this would, of course,
147 * have performance implications of its own.
149 * But the goal here isn't to win an award for the fastest or slimmest
150 * linked list; rather, we want a *convenient* linked list. So we won't
151 * waste time guessing which micro-optimization strategy is best.
154 * Speaking of unnecessary work, it's worth addressing here why we wrote
155 * mozilla::LinkedList in the first place, instead of using stl::list.
157 * The key difference between mozilla::LinkedList and stl::list is that
158 * mozilla::LinkedList stores the mPrev/mNext pointers in the object itself,
159 * while stl::list stores the mPrev/mNext pointers in a list element which
160 * itself points to the object being stored.
162 * mozilla::LinkedList's approach makes it harder to store an object in more
163 * than one list. But the upside is that you can call next() / prev() /
164 * remove() directly on the object. With stl::list, you'd need to store a
165 * pointer to its iterator in the object in order to accomplish this. Not
166 * only would this waste space, but you'd have to remember to update that
167 * pointer every time you added or removed the object from a list.
169 * In-place, constant-time removal is a killer feature of doubly-linked
170 * lists, and supporting this painlessly was a key design criterion.
173 private:
174 LinkedListElement* mNext;
175 LinkedListElement* mPrev;
176 const bool mIsSentinel;
178 public:
179 LinkedListElement() : mNext(this), mPrev(this), mIsSentinel(false) {}
182 * Moves |aOther| into |*this|. If |aOther| is already in a list, then
183 * |aOther| is removed from the list and replaced by |*this|.
185 LinkedListElement(LinkedListElement<T>&& aOther)
186 : mIsSentinel(aOther.mIsSentinel) {
187 adjustLinkForMove(std::move(aOther));
190 LinkedListElement& operator=(LinkedListElement<T>&& aOther) {
191 MOZ_ASSERT(mIsSentinel == aOther.mIsSentinel, "Mismatch NodeKind!");
192 MOZ_ASSERT(!isInList(),
193 "Assigning to an element in a list messes up that list!");
194 adjustLinkForMove(std::move(aOther));
195 return *this;
198 ~LinkedListElement() {
199 if (!mIsSentinel && isInList()) {
200 remove();
205 * Get the next element in the list, or nullptr if this is the last element
206 * in the list.
208 RawType getNext() { return mNext->asT(); }
209 ConstRawType getNext() const { return mNext->asT(); }
212 * Get the previous element in the list, or nullptr if this is the first
213 * element in the list.
215 RawType getPrevious() { return mPrev->asT(); }
216 ConstRawType getPrevious() const { return mPrev->asT(); }
219 * Insert aElem after this element in the list. |this| must be part of a
220 * linked list when you call setNext(); otherwise, this method will assert.
222 void setNext(RawType aElem) {
223 MOZ_ASSERT(isInList());
224 setNextUnsafe(aElem);
228 * Insert aElem before this element in the list. |this| must be part of a
229 * linked list when you call setPrevious(); otherwise, this method will
230 * assert.
232 void setPrevious(RawType aElem) {
233 MOZ_ASSERT(isInList());
234 setPreviousUnsafe(aElem);
238 * Remove this element from the list which contains it. If this element is
239 * not currently part of a linked list, this method asserts.
241 void remove() {
242 MOZ_ASSERT(isInList());
244 mPrev->mNext = mNext;
245 mNext->mPrev = mPrev;
246 mNext = this;
247 mPrev = this;
249 Traits::exitList(this);
253 * Remove this element from the list containing it. Returns a pointer to the
254 * element that follows this element (before it was removed). This method
255 * asserts if the element does not belong to a list. Note: In a refcounted
256 * list, |this| may be destroyed.
258 RawType removeAndGetNext() {
259 RawType r = getNext();
260 remove();
261 return r;
265 * Remove this element from the list containing it. Returns a pointer to the
266 * previous element in the containing list (before the removal). This method
267 * asserts if the element does not belong to a list. Note: In a refcounted
268 * list, |this| may be destroyed.
270 RawType removeAndGetPrevious() {
271 RawType r = getPrevious();
272 remove();
273 return r;
277 * Identical to remove(), but also asserts in debug builds that this element
278 * is in aList.
280 void removeFrom(const LinkedList<T>& aList) {
281 aList.assertContains(asT());
282 remove();
286 * Return true if |this| part is of a linked list, and false otherwise.
288 bool isInList() const {
289 MOZ_ASSERT((mNext == this) == (mPrev == this));
290 return mNext != this;
293 private:
294 friend class LinkedList<T>;
295 friend struct detail::LinkedListElementTraits<T>;
297 enum class NodeKind { Normal, Sentinel };
299 explicit LinkedListElement(NodeKind nodeKind)
300 : mNext(this), mPrev(this), mIsSentinel(nodeKind == NodeKind::Sentinel) {}
303 * Return |this| cast to T* if we're a normal node, or return nullptr if
304 * we're a sentinel node.
306 RawType asT() { return mIsSentinel ? nullptr : static_cast<RawType>(this); }
307 ConstRawType asT() const {
308 return mIsSentinel ? nullptr : static_cast<ConstRawType>(this);
312 * Insert aElem after this element, but don't check that this element is in
313 * the list. This is called by LinkedList::insertFront().
315 void setNextUnsafe(RawType aElem) {
316 LinkedListElement* listElem = static_cast<LinkedListElement*>(aElem);
317 MOZ_RELEASE_ASSERT(!listElem->isInList());
319 listElem->mNext = this->mNext;
320 listElem->mPrev = this;
321 this->mNext->mPrev = listElem;
322 this->mNext = listElem;
324 Traits::enterList(aElem);
328 * Insert aElem before this element, but don't check that this element is in
329 * the list. This is called by LinkedList::insertBack().
331 void setPreviousUnsafe(RawType aElem) {
332 LinkedListElement<T>* listElem = static_cast<LinkedListElement<T>*>(aElem);
333 MOZ_RELEASE_ASSERT(!listElem->isInList());
335 listElem->mNext = this;
336 listElem->mPrev = this->mPrev;
337 this->mPrev->mNext = listElem;
338 this->mPrev = listElem;
340 Traits::enterList(aElem);
344 * Adjust mNext and mPrev for implementing move constructor and move
345 * assignment.
347 void adjustLinkForMove(LinkedListElement<T>&& aOther) {
348 if (!aOther.isInList()) {
349 mNext = this;
350 mPrev = this;
351 return;
354 if (!mIsSentinel) {
355 Traits::enterList(this);
358 MOZ_ASSERT(aOther.mNext->mPrev == &aOther);
359 MOZ_ASSERT(aOther.mPrev->mNext == &aOther);
362 * Initialize |this| with |aOther|'s mPrev/mNext pointers, and adjust those
363 * element to point to this one.
365 mNext = aOther.mNext;
366 mPrev = aOther.mPrev;
368 mNext->mPrev = this;
369 mPrev->mNext = this;
372 * Adjust |aOther| so it doesn't think it's in a list. This makes it
373 * safely destructable.
375 aOther.mNext = &aOther;
376 aOther.mPrev = &aOther;
378 if (!mIsSentinel) {
379 Traits::exitList(&aOther);
383 LinkedListElement& operator=(const LinkedListElement<T>& aOther) = delete;
384 LinkedListElement(const LinkedListElement<T>& aOther) = delete;
387 template <typename T>
388 class LinkedList {
389 private:
390 typedef typename detail::LinkedListElementTraits<T> Traits;
391 typedef typename Traits::RawType RawType;
392 typedef typename Traits::ConstRawType ConstRawType;
393 typedef typename Traits::ClientType ClientType;
394 typedef typename Traits::ConstClientType ConstClientType;
395 typedef LinkedListElement<T>* ElementType;
396 typedef const LinkedListElement<T>* ConstElementType;
398 LinkedListElement<T> sentinel;
400 public:
401 template <typename Type, typename Element>
402 class Iterator {
403 Type mCurrent;
405 public:
406 using iterator_category = std::forward_iterator_tag;
407 using value_type = T;
408 using difference_type = std::ptrdiff_t;
409 using pointer = T*;
410 using reference = T&;
412 explicit Iterator(Type aCurrent) : mCurrent(aCurrent) {}
414 Type operator*() const { return mCurrent; }
416 const Iterator& operator++() {
417 mCurrent = static_cast<Element>(mCurrent)->getNext();
418 return *this;
421 bool operator!=(const Iterator& aOther) const {
422 return mCurrent != aOther.mCurrent;
426 LinkedList() : sentinel(LinkedListElement<T>::NodeKind::Sentinel) {}
428 LinkedList(LinkedList<T>&& aOther) : sentinel(std::move(aOther.sentinel)) {}
430 LinkedList& operator=(LinkedList<T>&& aOther) {
431 MOZ_ASSERT(isEmpty(),
432 "Assigning to a non-empty list leaks elements in that list!");
433 sentinel = std::move(aOther.sentinel);
434 return *this;
437 ~LinkedList() {
438 # ifdef DEBUG
439 if (!isEmpty()) {
440 MOZ_CRASH_UNSAFE_PRINTF(
441 "%s has a buggy user: "
442 "it should have removed all this list's elements before "
443 "the list's destruction",
444 __PRETTY_FUNCTION__);
446 # endif
450 * Add aElem to the front of the list.
452 void insertFront(RawType aElem) {
453 /* Bypass setNext()'s this->isInList() assertion. */
454 sentinel.setNextUnsafe(aElem);
458 * Add aElem to the back of the list.
460 void insertBack(RawType aElem) { sentinel.setPreviousUnsafe(aElem); }
463 * Get the first element of the list, or nullptr if the list is empty.
465 RawType getFirst() { return sentinel.getNext(); }
466 ConstRawType getFirst() const { return sentinel.getNext(); }
469 * Get the last element of the list, or nullptr if the list is empty.
471 RawType getLast() { return sentinel.getPrevious(); }
472 ConstRawType getLast() const { return sentinel.getPrevious(); }
475 * Get and remove the first element of the list. If the list is empty,
476 * return nullptr.
478 ClientType popFirst() {
479 ClientType ret = sentinel.getNext();
480 if (ret) {
481 static_cast<LinkedListElement<T>*>(RawType(ret))->remove();
483 return ret;
487 * Get and remove the last element of the list. If the list is empty,
488 * return nullptr.
490 ClientType popLast() {
491 ClientType ret = sentinel.getPrevious();
492 if (ret) {
493 static_cast<LinkedListElement<T>*>(RawType(ret))->remove();
495 return ret;
499 * Return true if the list is empty, or false otherwise.
501 bool isEmpty() const { return !sentinel.isInList(); }
504 * Returns whether the given element is in the list.
506 bool contains(ConstRawType aElm) const {
507 return std::find(begin(), end(), aElm) != end();
511 * Remove all the elements from the list.
513 * This runs in time linear to the list's length, because we have to mark
514 * each element as not in the list.
516 void clear() {
517 while (popFirst()) {
522 * Return the length of elements in the list.
524 size_t length() const { return std::distance(begin(), end()); }
527 * Allow range-based iteration:
529 * for (MyElementType* elt : myList) { ... }
531 Iterator<RawType, ElementType> begin() {
532 return Iterator<RawType, ElementType>(getFirst());
534 Iterator<ConstRawType, ConstElementType> begin() const {
535 return Iterator<ConstRawType, ConstElementType>(getFirst());
537 Iterator<RawType, ElementType> end() {
538 return Iterator<RawType, ElementType>(nullptr);
540 Iterator<ConstRawType, ConstElementType> end() const {
541 return Iterator<ConstRawType, ConstElementType>(nullptr);
545 * Measures the memory consumption of the list excluding |this|. Note that
546 * it only measures the list elements themselves. If the list elements
547 * contain pointers to other memory blocks, those blocks must be measured
548 * separately during a subsequent iteration over the list.
550 size_t sizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
551 size_t n = 0;
552 ConstRawType t = getFirst();
553 while (t) {
554 n += aMallocSizeOf(t);
555 t = static_cast<const LinkedListElement<T>*>(t)->getNext();
557 return n;
561 * Like sizeOfExcludingThis(), but measures |this| as well.
563 size_t sizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
564 return aMallocSizeOf(this) + sizeOfExcludingThis(aMallocSizeOf);
568 * In a debug build, make sure that the list is sane (no cycles, consistent
569 * mNext/mPrev pointers, only one sentinel). Has no effect in release builds.
571 void debugAssertIsSane() const {
572 # ifdef DEBUG
573 const LinkedListElement<T>* slow;
574 const LinkedListElement<T>* fast1;
575 const LinkedListElement<T>* fast2;
578 * Check for cycles in the forward singly-linked list using the
579 * tortoise/hare algorithm.
581 for (slow = sentinel.mNext, fast1 = sentinel.mNext->mNext,
582 fast2 = sentinel.mNext->mNext->mNext;
583 slow != &sentinel && fast1 != &sentinel && fast2 != &sentinel;
584 slow = slow->mNext, fast1 = fast2->mNext, fast2 = fast1->mNext) {
585 MOZ_ASSERT(slow != fast1);
586 MOZ_ASSERT(slow != fast2);
589 /* Check for cycles in the backward singly-linked list. */
590 for (slow = sentinel.mPrev, fast1 = sentinel.mPrev->mPrev,
591 fast2 = sentinel.mPrev->mPrev->mPrev;
592 slow != &sentinel && fast1 != &sentinel && fast2 != &sentinel;
593 slow = slow->mPrev, fast1 = fast2->mPrev, fast2 = fast1->mPrev) {
594 MOZ_ASSERT(slow != fast1);
595 MOZ_ASSERT(slow != fast2);
599 * Check that |sentinel| is the only node in the list with
600 * mIsSentinel == true.
602 for (const LinkedListElement<T>* elem = sentinel.mNext; elem != &sentinel;
603 elem = elem->mNext) {
604 MOZ_ASSERT(!elem->mIsSentinel);
607 /* Check that the mNext/mPrev pointers match up. */
608 const LinkedListElement<T>* prev = &sentinel;
609 const LinkedListElement<T>* cur = sentinel.mNext;
610 do {
611 MOZ_ASSERT(cur->mPrev == prev);
612 MOZ_ASSERT(prev->mNext == cur);
614 prev = cur;
615 cur = cur->mNext;
616 } while (cur != &sentinel);
617 # endif /* ifdef DEBUG */
620 private:
621 friend class LinkedListElement<T>;
623 void assertContains(const RawType aValue) const {
624 # ifdef DEBUG
625 for (ConstRawType elem = getFirst(); elem; elem = elem->getNext()) {
626 if (elem == aValue) {
627 return;
630 MOZ_CRASH("element wasn't found in this list!");
631 # endif
634 LinkedList& operator=(const LinkedList<T>& aOther) = delete;
635 LinkedList(const LinkedList<T>& aOther) = delete;
638 template <typename T>
639 inline void ImplCycleCollectionUnlink(LinkedList<RefPtr<T>>& aField) {
640 aField.clear();
643 template <typename T>
644 inline void ImplCycleCollectionTraverse(
645 nsCycleCollectionTraversalCallback& aCallback,
646 LinkedList<RefPtr<T>>& aField, const char* aName, uint32_t aFlags = 0) {
647 typedef typename detail::LinkedListElementTraits<T> Traits;
648 typedef typename Traits::RawType RawType;
649 for (RawType element : aField) {
650 // RefPtr is stored as a raw pointer in LinkedList.
651 // So instead of creating a new RefPtr from the raw
652 // pointer (which is not allowed), we simply call
653 // CycleCollectionNoteChild against the raw pointer
654 CycleCollectionNoteChild(aCallback, element, aName, aFlags);
658 template <typename T>
659 class AutoCleanLinkedList : public LinkedList<T> {
660 private:
661 using Traits = detail::LinkedListElementTraits<T>;
662 using ClientType = typename detail::LinkedListElementTraits<T>::ClientType;
664 public:
665 ~AutoCleanLinkedList() { clear(); }
667 AutoCleanLinkedList& operator=(AutoCleanLinkedList&& aOther) = default;
669 void clear() {
670 while (ClientType element = this->popFirst()) {
671 Traits::cleanElement(element);
676 } /* namespace mozilla */
678 #endif /* __cplusplus */
680 #endif /* mozilla_LinkedList_h */