no bug - Bumping Firefox l10n changesets r=release a=l10n-bump DONTBUILD CLOSED TREE
[gecko.git] / xpcom / ds / SimpleEnumerator.h
blob463b9ecaed7de47a8749743a8bffef4c2bb1dfd4
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 #ifndef mozilla_SimpleEnumerator_h
8 #define mozilla_SimpleEnumerator_h
10 #include "nsCOMPtr.h"
11 #include "nsISimpleEnumerator.h"
13 namespace mozilla {
15 /**
16 * A wrapper class around nsISimpleEnumerator to support ranged iteration. This
17 * requires every element in the enumeration to implement the same interface, T.
18 * If any element does not implement this interface, the enumeration ends at
19 * that element, and triggers an assertion in debug builds.
21 * Typical usage looks something like:
23 * for (auto& docShell : SimpleEnumerator<nsIDocShell>(docShellEnum)) {
24 * docShell.LoadURI(...);
25 * }
28 template <typename T>
29 class SimpleEnumerator final {
30 public:
31 explicit SimpleEnumerator(nsISimpleEnumerator* aEnum) : mEnum(aEnum) {}
33 class Entry {
34 public:
35 explicit Entry(T* aPtr) : mPtr(aPtr) {}
37 explicit Entry(nsISimpleEnumerator& aEnum) : mEnum(&aEnum) { ++*this; }
39 const nsCOMPtr<T>& operator*() {
40 MOZ_ASSERT(mPtr);
41 return mPtr;
44 Entry& operator++() {
45 MOZ_ASSERT(mEnum);
46 nsCOMPtr<nsISupports> next;
47 if (NS_SUCCEEDED(mEnum->GetNext(getter_AddRefs(next)))) {
48 mPtr = do_QueryInterface(next);
49 MOZ_ASSERT(mPtr);
50 } else {
51 mPtr = nullptr;
53 return *this;
56 bool operator!=(const Entry& aOther) const { return mPtr != aOther.mPtr; }
58 private:
59 nsCOMPtr<T> mPtr;
60 nsCOMPtr<nsISimpleEnumerator> mEnum;
63 Entry begin() { return Entry(*mEnum); }
65 Entry end() { return Entry(nullptr); }
67 private:
68 nsCOMPtr<nsISimpleEnumerator> mEnum;
71 } // namespace mozilla
73 #endif // mozilla_SimpleEnumerator_h