2 * Copyright 2016 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
22 #include <folly/portability/SysTypes.h>
25 * Similar to Python's enumerate(), folly::enumerate() can be used to
26 * iterate a range with a for-range loop, and it also allows to
27 * retrieve the count of iterations so far.
31 * for (auto it : folly::enumerate(vec)) {
32 * // *it is a reference to the current element. Const if vec is const.
33 * // it->member can be used as well.
34 * // it.index contains the iteration count.
37 * If the iteration variable is const, the reference is too.
39 * for (const auto it : folly::enumerate(vec)) {
40 * // *it is always a const reference.
43 * @author Giuseppe Ottaviano <ott@fb.com>
55 struct MakeConst<T&> {
56 using type = const T&;
59 struct MakeConst<T*> {
60 using type = const T*;
63 template <class Iterator>
66 explicit Enumerator(Iterator it) : it_(std::move(it)) {}
70 using difference_type = ssize_t;
71 using value_type = typename std::iterator_traits<Iterator>::value_type;
72 using reference = typename std::iterator_traits<Iterator>::reference;
73 using pointer = typename std::iterator_traits<Iterator>::pointer;
74 using iterator_category = std::input_iterator_tag;
76 explicit Proxy(const Enumerator* e) : it_(e->it_), index(e->idx_) {}
78 // Non-const Proxy: Forward constness from Iterator.
79 reference operator*() {
82 pointer operator->() {
83 return std::addressof(**this);
86 // Const Proxy: Force const references.
87 typename MakeConst<reference>::type operator*() const {
90 typename MakeConst<pointer>::type operator->() const {
91 return std::addressof(**this);
101 Proxy operator*() const {
105 Enumerator& operator++() {
111 bool operator==(const Enumerator& rhs) {
112 return it_ == rhs.it_;
115 bool operator!=(const Enumerator& rhs) {
116 return !(*this == rhs);
124 template <class Range>
125 class RangeEnumerator {
127 using Iterator = decltype(r_.begin());
130 explicit RangeEnumerator(Range&& r) : r_(std::forward<Range>(r)) {}
132 Enumerator<Iterator> begin() {
133 return Enumerator<Iterator>(r_.begin());
135 Enumerator<Iterator> end() {
136 return Enumerator<Iterator>(r_.end());
140 } // namespace detail
142 template <class Range>
143 detail::RangeEnumerator<Range> enumerate(Range&& r) {
144 return detail::RangeEnumerator<Range>(std::forward<Range>(r));