442336d60d5c53a6b29e446428905a2eabe9528a
[folly.git] / folly / Foreach.h
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #ifndef FOLLY_BASE_FOREACH_H_
18 #define FOLLY_BASE_FOREACH_H_
19
20 /*
21  * Iterim macros (until we have C++0x range-based for) that simplify
22  * writing loops of the form
23  *
24  * for (Container<data>::iterator i = c.begin(); i != c.end(); ++i) statement
25  *
26  * Just replace the above with:
27  *
28  * FOR_EACH (i, c) statement
29  *
30  * and everything is taken care of.
31  *
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.
41  *
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
44  * nested.
45  *
46  * In optimized builds g++ eliminates the extra gymnastics entirely and
47  * generates code 100% identical to the handwritten loop.
48  */
49
50 #include <boost/type_traits/remove_cv.hpp>
51 #include <type_traits>
52
53 /*
54  * Shorthand for:
55  *   for (auto i = c.begin(); i != c.end(); ++i)
56  * except that c is only evaluated once.
57  */
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)
64
65 /*
66  * Similar to FOR_EACH, but iterates the container backwards by
67  * using rbegin() and rend().
68  */
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)
75
76 /*
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;
83  * }
84  */
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)
93
94 /**
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;
100  *   }
101  */
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)
115
116 namespace folly { namespace detail {
117
118 // Boost 1.48 lacks has_less, we emulate a subset of it here.
119 template <typename T, typename U>
120 class HasLess {
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(...);
124 public:
125   enum { value = sizeof(test<T, U>(0)) == 1 };
126 };
127
128 /**
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.
135  *
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.
143  *
144  * The else branch (active) contains a conservative
145  * implementation.
146  */
147
148 #if 0
149
150 template <class T, class U>
151 typename std::enable_if<HasLess<T, U>::value, bool>::type
152 notThereYet(T& iter, const U& end) {
153   return iter < end;
154 }
155
156 template <class T, class U>
157 typename std::enable_if<!HasLess<T, U>::value, bool>::type
158 notThereYet(T& iter, const U& end) {
159   return iter != end;
160 }
161
162 #else
163
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),
168   bool>::type
169 notThereYet(T& iter, const U& end) {
170   return iter < end;
171 }
172
173 template <class T, class U>
174 typename std::enable_if<
175   !(
176     (std::is_arithmetic<T>::value && std::is_arithmetic<U>::value) ||
177     (std::is_pointer<T>::value && std::is_pointer<U>::value)
178   ),
179   bool>::type
180 notThereYet(T& iter, const U& end) {
181   return iter != end;
182 }
183
184 #endif
185
186
187 /**
188  * downTo is similar to notThereYet, but in reverse - it helps the
189  * FOR_EACH_RANGE_R macro.
190  */
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--;
195 }
196
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;
201   --iter;
202   return true;
203 }
204
205 } }
206
207 /*
208  * Iteration with given limits. end is assumed to be reachable from
209  * begin. end is evaluated every pass through the loop.
210  *
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)
214  */
215 #define FOR_EACH_RANGE(i, begin, end)           \
216   for (auto i = (true ? (begin) : (end));       \
217        ::folly::detail::notThereYet(i, (end));  \
218        ++i)
219
220 /*
221  * Iteration with given limits. begin is assumed to be reachable from
222  * end by successive decrements. begin is evaluated every pass through
223  * the loop.
224  *
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)
228  */
229 #define FOR_EACH_RANGE_R(i, begin, end) \
230   for (auto i = (false ? (begin) : (end)); ::folly::detail::downTo(i, (begin));)
231
232 #endif