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.
23 * Similar to Python's enumerate(), folly::enumerate() can be used to
24 * iterate a range with a for-range loop, and it also allows to
25 * retrieve the count of iterations so far.
29 * for (auto it : folly::enumerate(vec)) {
30 * // *it is a reference to the current element. Const if vec is const.
31 * // it->member can be used as well.
32 * // it.index contains the iteration count.
35 * If the iteration variable is const, the reference is too.
37 * for (const auto it : folly::enumerate(vec)) {
38 * // *it is always a const reference.
41 * @author Giuseppe Ottaviano <ott@fb.com>
53 struct MakeConst<T&> {
54 using type = const T&;
57 struct MakeConst<T*> {
58 using type = const T*;
61 template <class Iterator>
64 explicit Enumerator(Iterator it) : it_(std::move(it)) {}
68 using difference_type = ssize_t;
69 using value_type = typename std::iterator_traits<Iterator>::value_type;
70 using reference = typename std::iterator_traits<Iterator>::reference;
71 using pointer = typename std::iterator_traits<Iterator>::pointer;
72 using iterator_category = std::input_iterator_tag;
74 explicit Proxy(const Enumerator* e) : it_(e->it_), index(e->idx_) {}
76 // Non-const Proxy: Forward constness from Iterator.
77 reference operator*() {
80 pointer operator->() {
81 return std::addressof(**this);
84 // Const Proxy: Force const references.
85 typename MakeConst<reference>::type operator*() const {
88 typename MakeConst<pointer>::type operator->() const {
89 return std::addressof(**this);
99 Proxy operator*() const {
103 Enumerator& operator++() {
109 bool operator==(const Enumerator& rhs) {
110 return it_ == rhs.it_;
113 bool operator!=(const Enumerator& rhs) {
114 return !(*this == rhs);
122 template <class Range>
123 class RangeEnumerator {
125 using Iterator = decltype(r_.begin());
128 explicit RangeEnumerator(Range&& r) : r_(std::forward<Range>(r)) {}
130 Enumerator<Iterator> begin() {
131 return Enumerator<Iterator>(r_.begin());
133 Enumerator<Iterator> end() {
134 return Enumerator<Iterator>(r_.end());
138 } // namespace detail
140 template <class Range>
141 detail::RangeEnumerator<Range> enumerate(Range&& r) {
142 return detail::RangeEnumerator<Range>(std::forward<Range>(r));