2 * Copyright 2014 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.
17 #ifndef FOLLY_BASE_FOREACH_H_
18 #define FOLLY_BASE_FOREACH_H_
21 * Iterim macros (until we have C++0x range-based for) that simplify
22 * writing loops of the form
24 * for (Container<data>::iterator i = c.begin(); i != c.end(); ++i) statement
26 * Just replace the above with:
28 * FOR_EACH (i, c) statement
30 * and everything is taken care of.
32 * The implementation is a bit convoluted to make sure the container is
33 * only evaluated once (however, keep in mind that c.end() is evaluated
34 * at every pass through the loop). To ensure the container is not
35 * evaluated multiple times, the macro defines one do-nothing if
36 * statement to inject the Boolean variable FOR_EACH_state1, and then a
37 * for statement that is executed only once, which defines the variable
38 * FOR_EACH_state2 holding a rvalue reference to the container being
39 * iterated. The workhorse is the last loop, which uses the just defined
40 * rvalue reference FOR_EACH_state2.
42 * The state variables are nested so they don't interfere; you can use
43 * FOR_EACH multiple times in the same scope, either at the same level or
46 * In optimized builds g++ eliminates the extra gymnastics entirely and
47 * generates code 100% identical to the handwritten loop.
50 #include <boost/type_traits/remove_cv.hpp>
51 #include <type_traits>
55 * for (auto i = c.begin(); i != c.end(); ++i)
56 * except that c is only evaluated once.
58 #define FOR_EACH(i, c) \
59 if (bool FOR_EACH_state1 = false) {} else \
60 for (auto && FOR_EACH_state2 = (c); \
61 !FOR_EACH_state1; FOR_EACH_state1 = true) \
62 for (auto i = FOR_EACH_state2.begin(); \
63 i != FOR_EACH_state2.end(); ++i)
66 * Similar to FOR_EACH, but iterates the container backwards by
67 * using rbegin() and rend().
69 #define FOR_EACH_R(i, c) \
70 if (bool FOR_EACH_R_state1 = false) {} else \
71 for (auto && FOR_EACH_R_state2 = (c); \
72 !FOR_EACH_R_state1; FOR_EACH_R_state1 = true) \
73 for (auto i = FOR_EACH_R_state2.rbegin(); \
74 i != FOR_EACH_R_state2.rend(); ++i)
77 * Similar to FOR_EACH but also allows client to specify a 'count' variable
78 * to track the current iteration in the loop (starting at zero).
79 * Similar to python's enumerate() function. For example:
80 * string commaSeparatedValues = "VALUES: ";
81 * FOR_EACH_ENUMERATE(ii, value, columns) { // don't want comma at the end!
82 * commaSeparatedValues += (ii == 0) ? *value : string(",") + *value;
85 #define FOR_EACH_ENUMERATE(count, i, c) \
86 if (bool FOR_EACH_state1 = false) {} else \
87 for (auto && FOR_EACH_state2 = (c); \
88 !FOR_EACH_state1; FOR_EACH_state1 = true) \
89 if (size_t FOR_EACH_privateCount = 0) {} else \
90 if (const size_t& count = FOR_EACH_privateCount) {} else \
91 for (auto i = FOR_EACH_state2.begin(); \
92 i != FOR_EACH_state2.end(); ++FOR_EACH_privateCount, ++i)
95 * Similar to FOR_EACH, but gives the user the key and value for each entry in
96 * the container, instead of just the iterator to the entry. For example:
97 * map<string, string> testMap;
98 * FOR_EACH_KV(key, value, testMap) {
99 * cout << key << " " << value;
102 #define FOR_EACH_KV(k, v, c) \
103 if (unsigned int FOR_EACH_state1 = 0) {} else \
104 for (auto && FOR_EACH_state2 = (c); \
105 !FOR_EACH_state1; FOR_EACH_state1 = 1) \
106 for (auto FOR_EACH_state3 = FOR_EACH_state2.begin(); \
107 FOR_EACH_state3 != FOR_EACH_state2.end(); \
108 FOR_EACH_state1 == 2 \
109 ? ((FOR_EACH_state1 = 0), ++FOR_EACH_state3) \
110 : (FOR_EACH_state3 = FOR_EACH_state2.end())) \
111 for (auto &k = FOR_EACH_state3->first; \
112 !FOR_EACH_state1; ++FOR_EACH_state1) \
113 for (auto &v = FOR_EACH_state3->second; \
114 !FOR_EACH_state1; ++FOR_EACH_state1)
116 namespace folly { namespace detail {
118 // Boost 1.48 lacks has_less, we emulate a subset of it here.
119 template <typename T, typename U>
121 struct BiggerThanChar { char unused[2]; };
122 template <typename C, typename D> static char test(decltype(C() < D())*);
123 template <typename, typename> static BiggerThanChar test(...);
125 enum { value = sizeof(test<T, U>(0)) == 1 };
129 * notThereYet helps the FOR_EACH_RANGE macro by opportunistically
130 * using "<" instead of "!=" whenever available when checking for loop
131 * termination. This makes e.g. examples such as FOR_EACH_RANGE (i,
132 * 10, 5) execute zero iterations instead of looping virtually
133 * forever. At the same time, some iterator types define "!=" but not
134 * "<". The notThereYet function will dispatch differently for those.
136 * Below is the correct implementation of notThereYet. It is disabled
137 * because of a bug in Boost 1.46: The filesystem::path::iterator
138 * defines operator< (via boost::iterator_facade), but that in turn
139 * uses distance_to which is undefined for that particular
140 * iterator. So HasLess (defined above) identifies
141 * boost::filesystem::path as properly comparable with <, but in fact
142 * attempting to do so will yield a compile-time error.
144 * The else branch (active) contains a conservative
150 template <class T, class U>
151 typename std::enable_if<HasLess<T, U>::value, bool>::type
152 notThereYet(T& iter, const U& end) {
156 template <class T, class U>
157 typename std::enable_if<!HasLess<T, U>::value, bool>::type
158 notThereYet(T& iter, const U& end) {
164 template <class T, class U>
165 typename std::enable_if<
166 (std::is_arithmetic<T>::value && std::is_arithmetic<U>::value) ||
167 (std::is_pointer<T>::value && std::is_pointer<U>::value),
169 notThereYet(T& iter, const U& end) {
173 template <class T, class U>
174 typename std::enable_if<
176 (std::is_arithmetic<T>::value && std::is_arithmetic<U>::value) ||
177 (std::is_pointer<T>::value && std::is_pointer<U>::value)
180 notThereYet(T& iter, const U& end) {
188 * downTo is similar to notThereYet, but in reverse - it helps the
189 * FOR_EACH_RANGE_R macro.
191 template <class T, class U>
192 typename std::enable_if<HasLess<U, T>::value, bool>::type
193 downTo(T& iter, const U& begin) {
194 return begin < iter--;
197 template <class T, class U>
198 typename std::enable_if<!HasLess<U, T>::value, bool>::type
199 downTo(T& iter, const U& begin) {
200 if (iter == begin) return false;
208 * Iteration with given limits. end is assumed to be reachable from
209 * begin. end is evaluated every pass through the loop.
211 * NOTE: The type of the loop variable should be the common type of "begin"
212 * and "end". e.g. If "begin" is "int" but "end" is "long", we want "i"
213 * to be "long". This is done by getting the type of (true ? begin : end)
215 #define FOR_EACH_RANGE(i, begin, end) \
216 for (auto i = (true ? (begin) : (end)); \
217 ::folly::detail::notThereYet(i, (end)); \
221 * Iteration with given limits. begin is assumed to be reachable from
222 * end by successive decrements. begin is evaluated every pass through
225 * NOTE: The type of the loop variable should be the common type of "begin"
226 * and "end". e.g. If "begin" is "int" but "end" is "long", we want "i"
227 * to be "long". This is done by getting the type of (false ? begin : end)
229 #define FOR_EACH_RANGE_R(i, begin, end) \
230 for (auto i = (false ? (begin) : (end)); ::folly::detail::downTo(i, (begin));)