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>
54 * for (auto i = c.begin(); i != c.end(); ++i)
55 * except that c is only evaluated once.
57 #define FOR_EACH(i, c) \
58 if (bool FOR_EACH_state1 = false) {} else \
59 for (auto && FOR_EACH_state2 = (c); \
60 !FOR_EACH_state1; FOR_EACH_state1 = true) \
61 for (auto i = FOR_EACH_state2.begin(); \
62 i != FOR_EACH_state2.end(); ++i)
65 * Similar to FOR_EACH, but iterates the container backwards by
66 * using rbegin() and rend().
68 #define FOR_EACH_R(i, c) \
69 if (bool FOR_EACH_R_state1 = false) {} else \
70 for (auto && FOR_EACH_R_state2 = (c); \
71 !FOR_EACH_R_state1; FOR_EACH_R_state1 = true) \
72 for (auto i = FOR_EACH_R_state2.rbegin(); \
73 i != FOR_EACH_R_state2.rend(); ++i)
76 * Similar to FOR_EACH but also allows client to specify a 'count' variable
77 * to track the current iteration in the loop (starting at zero).
78 * Similar to python's enumerate() function. For example:
79 * string commaSeparatedValues = "VALUES: ";
80 * FOR_EACH_ENUMERATE(ii, value, columns) { // don't want comma at the end!
81 * commaSeparatedValues += (ii == 0) ? *value : string(",") + *value;
84 #define FOR_EACH_ENUMERATE(count, i, c) \
85 if (bool FOR_EACH_state1 = false) {} else \
86 for (auto && FOR_EACH_state2 = (c); \
87 !FOR_EACH_state1; FOR_EACH_state1 = true) \
88 if (size_t FOR_EACH_privateCount = 0) {} else \
89 if (const size_t& count = FOR_EACH_privateCount) {} else \
90 for (auto i = FOR_EACH_state2.begin(); \
91 i != FOR_EACH_state2.end(); ++FOR_EACH_privateCount, ++i)
94 * Similar to FOR_EACH, but gives the user the key and value for each entry in
95 * the container, instead of just the iterator to the entry. For example:
96 * map<string, string> testMap;
97 * FOR_EACH_KV(key, value, testMap) {
98 * cout << key << " " << value;
101 #define FOR_EACH_KV(k, v, c) \
102 if (unsigned int FOR_EACH_state1 = 0) {} else \
103 for (auto && FOR_EACH_state2 = (c); \
104 !FOR_EACH_state1; FOR_EACH_state1 = 1) \
105 for (auto FOR_EACH_state3 = FOR_EACH_state2.begin(); \
106 FOR_EACH_state3 != FOR_EACH_state2.end(); \
107 FOR_EACH_state1 == 2 \
108 ? ((FOR_EACH_state1 = 0), ++FOR_EACH_state3) \
109 : (FOR_EACH_state3 = FOR_EACH_state2.end())) \
110 for (auto &k = FOR_EACH_state3->first; \
111 !FOR_EACH_state1; ++FOR_EACH_state1) \
112 for (auto &v = FOR_EACH_state3->second; \
113 !FOR_EACH_state1; ++FOR_EACH_state1)
115 namespace folly { namespace detail {
117 // Boost 1.48 lacks has_less, we emulate a subset of it here.
118 template <typename T, typename U>
120 struct BiggerThanChar { char unused[2]; };
121 template <typename C, typename D> static char test(decltype(C() < D())*);
122 template <typename, typename> static BiggerThanChar test(...);
124 enum { value = sizeof(test<T, U>(0)) == 1 };
128 * notThereYet helps the FOR_EACH_RANGE macro by opportunistically
129 * using "<" instead of "!=" whenever available when checking for loop
130 * termination. This makes e.g. examples such as FOR_EACH_RANGE (i,
131 * 10, 5) execute zero iterations instead of looping virtually
132 * forever. At the same time, some iterator types define "!=" but not
133 * "<". The notThereYet function will dispatch differently for those.
135 * Below is the correct implementation of notThereYet. It is disabled
136 * because of a bug in Boost 1.46: The filesystem::path::iterator
137 * defines operator< (via boost::iterator_facade), but that in turn
138 * uses distance_to which is undefined for that particular
139 * iterator. So HasLess (defined above) identifies
140 * boost::filesystem::path as properly comparable with <, but in fact
141 * attempting to do so will yield a compile-time error.
143 * The else branch (active) contains a conservative
149 template <class T, class U>
150 typename std::enable_if<HasLess<T, U>::value, bool>::type
151 notThereYet(T& iter, const U& end) {
155 template <class T, class U>
156 typename std::enable_if<!HasLess<T, U>::value, bool>::type
157 notThereYet(T& iter, const U& end) {
163 template <class T, class U>
164 typename std::enable_if<
165 (std::is_arithmetic<T>::value && std::is_arithmetic<U>::value) ||
166 (std::is_pointer<T>::value && std::is_pointer<U>::value),
168 notThereYet(T& iter, const U& end) {
172 template <class T, class U>
173 typename std::enable_if<
175 (std::is_arithmetic<T>::value && std::is_arithmetic<U>::value) ||
176 (std::is_pointer<T>::value && std::is_pointer<U>::value)
179 notThereYet(T& iter, const U& end) {
187 * downTo is similar to notThereYet, but in reverse - it helps the
188 * FOR_EACH_RANGE_R macro.
190 template <class T, class U>
191 typename std::enable_if<HasLess<U, T>::value, bool>::type
192 downTo(T& iter, const U& begin) {
193 return begin < iter--;
196 template <class T, class U>
197 typename std::enable_if<!HasLess<U, T>::value, bool>::type
198 downTo(T& iter, const U& begin) {
199 if (iter == begin) return false;
207 * Iteration with given limits. end is assumed to be reachable from
208 * begin. end is evaluated every pass through the loop.
210 * NOTE: The type of the loop variable should be the common type of "begin"
211 * and "end". e.g. If "begin" is "int" but "end" is "long", we want "i"
212 * to be "long". This is done by getting the type of (true ? begin : end)
214 #define FOR_EACH_RANGE(i, begin, end) \
215 for (auto i = (true ? (begin) : (end)); \
216 ::folly::detail::notThereYet(i, (end)); \
220 * Iteration with given limits. begin is assumed to be reachable from
221 * end by successive decrements. begin is evaluated every pass through
224 * NOTE: The type of the loop variable should be the common type of "begin"
225 * and "end". e.g. If "begin" is "int" but "end" is "long", we want "i"
226 * to be "long". This is done by getting the type of (false ? begin : end)
228 #define FOR_EACH_RANGE_R(i, begin, end) \
229 for (auto i = (false ? (begin) : (end)); ::folly::detail::downTo(i, (begin));)