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.
17 #include <folly/Foreach.h>
19 #include <gtest/gtest.h>
25 using namespace folly;
26 using namespace folly::detail;
28 TEST(Foreach, ForEachRvalue) {
29 const char* const hello = "hello";
31 FOR_EACH(it, std::string(hello)) {
34 EXPECT_EQ(strlen(hello), n);
35 FOR_EACH_R(it, std::string(hello)) {
37 EXPECT_EQ(hello[n], *it);
42 TEST(Foreach, ForEachKV) {
43 std::map<std::string, int> testMap;
46 std::string keys = "";
49 FOR_EACH_KV (key, value, testMap) {
54 EXPECT_EQ("abcdef", keys);
56 EXPECT_EQ(2, numEntries);
59 TEST(Foreach, ForEachKVBreak) {
60 std::map<std::string, int> testMap;
63 std::string keys = "";
66 FOR_EACH_KV (key, value, testMap) {
72 EXPECT_EQ("abc", keys);
74 EXPECT_EQ(1, numEntries);
77 TEST(Foreach, ForEachKvWithMultiMap) {
78 std::multimap<std::string, int> testMap;
79 testMap.insert(std::make_pair("abc", 1));
80 testMap.insert(std::make_pair("abc", 2));
81 testMap.insert(std::make_pair("def", 3));
82 std::string keys = "";
85 FOR_EACH_KV (key, value, testMap) {
90 EXPECT_EQ("abcabcdef", keys);
92 EXPECT_EQ(3, numEntries);
95 TEST(Foreach, ForEachEnumerate) {
99 int numIterations = 0;
100 FOR_EACH_ENUMERATE(aa, iter, vv) {
106 EXPECT_EQ(sumIter, 0);
107 EXPECT_EQ(numIterations, 0);
112 FOR_EACH_ENUMERATE(aa, iter, vv) {
117 EXPECT_EQ(sumAA, 3); // 0 + 1 + 2
118 EXPECT_EQ(sumIter, 9); // 1 + 3 + 5
119 EXPECT_EQ(numIterations, 3);
122 TEST(Foreach, ForEachEnumerateBreak) {
126 int numIterations = 0;
131 FOR_EACH_ENUMERATE(aa, iter, vv) {
137 EXPECT_EQ(sumAA, 1); // 0 + 1
138 EXPECT_EQ(sumIter, 3); // 1 + 2
139 EXPECT_EQ(numIterations, 2);
142 TEST(Foreach, ForEachRangeR) {
145 FOR_EACH_RANGE_R (i, 0, 0) {
150 FOR_EACH_RANGE_R (i, 0, -1) {
155 FOR_EACH_RANGE_R (i, 0, 5) {
160 std::list<int> lst = { 0, 1, 2, 3, 4 };
162 FOR_EACH_RANGE_R (i, lst.begin(), lst.end()) {