Remove superfluous std::move calls
[folly.git] / folly / gen / test / BaseTest.cpp
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 #include <glog/logging.h>
18 #include <gtest/gtest.h>
19 #include <iosfwd>
20 #include <random>
21 #include <set>
22 #include <vector>
23
24 #include <folly/FBVector.h>
25 #include <folly/MapUtil.h>
26 #include <folly/Memory.h>
27 #include <folly/dynamic.h>
28 #include <folly/gen/Base.h>
29 #include <folly/experimental/TestUtil.h>
30
31 using namespace folly::gen;
32 using namespace folly;
33 using std::make_tuple;
34 using std::ostream;
35 using std::pair;
36 using std::set;
37 using std::string;
38 using std::tuple;
39 using std::unique_ptr;
40 using std::vector;
41
42 #define EXPECT_SAME(A, B) \
43   static_assert(std::is_same<A, B>::value, "Mismatched: " #A ", " #B)
44 EXPECT_SAME(int&&, typename ArgumentReference<int>::type);
45 EXPECT_SAME(int&, typename ArgumentReference<int&>::type);
46 EXPECT_SAME(const int&, typename ArgumentReference<const int&>::type);
47 EXPECT_SAME(const int&, typename ArgumentReference<const int>::type);
48
49 template<typename T>
50 ostream& operator<<(ostream& os, const set<T>& values) {
51   return os << from(values);
52 }
53
54 template<typename T>
55 ostream& operator<<(ostream& os, const vector<T>& values) {
56   os << "[";
57   for (auto& value : values) {
58     if (&value != &values.front()) {
59       os << " ";
60     }
61     os << value;
62   }
63   return os << "]";
64 }
65
66 auto square = [](int x) { return x * x; };
67 auto add = [](int a, int b) { return a + b; };
68 auto multiply = [](int a, int b) { return a * b; };
69
70 auto product = foldl(1, multiply);
71
72 template<typename A, typename B>
73 ostream& operator<<(ostream& os, const pair<A, B>& pair) {
74   return os << "(" << pair.first << ", " << pair.second << ")";
75 }
76
77 TEST(Gen, Count) {
78   auto gen = seq(1, 10);
79   EXPECT_EQ(10, gen | count);
80   EXPECT_EQ(5, gen | take(5) | count);
81 }
82
83 TEST(Gen, Sum) {
84   auto gen = seq(1, 10);
85   EXPECT_EQ((1 + 10) * 10 / 2, gen | sum);
86   EXPECT_EQ((1 + 5) * 5 / 2, gen | take(5) | sum);
87 }
88
89 TEST(Gen, Foreach) {
90   auto gen = seq(1, 4);
91   int accum = 0;
92   gen | [&](int x) { accum += x; };
93   EXPECT_EQ(10, accum);
94   int accum2 = 0;
95   gen | take(3) | [&](int x) { accum2 += x; };
96   EXPECT_EQ(6, accum2);
97 }
98
99 TEST(Gen, Map) {
100   auto expected = vector<int>{4, 9, 16};
101   auto gen = from({2, 3, 4}) | map(square);
102   EXPECT_EQ((vector<int>{4, 9, 16}), gen | as<vector>());
103   EXPECT_EQ((vector<int>{4, 9}), gen | take(2) | as<vector>());
104 }
105
106 TEST(Gen, Member) {
107   struct Counter {
108     Counter(int start = 0)
109       : c(start)
110     {}
111
112     int count() const { return c; }
113     int incr() { return ++c; }
114
115     int& ref() { return c; }
116     const int& ref() const { return c; }
117    private:
118     int c;
119   };
120   auto counters = seq(1, 10) | eachAs<Counter>() | as<vector>();
121   EXPECT_EQ(10 * (1 + 10) / 2,
122             from(counters)
123           | member(&Counter::count)
124           | sum);
125   EXPECT_EQ(10 * (1 + 10) / 2,
126             from(counters)
127           | indirect
128           | member(&Counter::count)
129           | sum);
130   EXPECT_EQ(10 * (2 + 11) / 2,
131             from(counters)
132           | member(&Counter::incr)
133           | sum);
134   EXPECT_EQ(10 * (3 + 12) / 2,
135             from(counters)
136           | indirect
137           | member(&Counter::incr)
138           | sum);
139   EXPECT_EQ(10 * (3 + 12) / 2,
140             from(counters)
141           | member(&Counter::count)
142           | sum);
143
144   // type-verifications
145   auto m = empty<Counter&>();
146   auto c = empty<const Counter&>();
147   m | member(&Counter::incr) | assert_type<int&&>();
148   m | member(&Counter::count) | assert_type<int&&>();
149   m | member(&Counter::count) | assert_type<int&&>();
150   m | member<Const>(&Counter::ref) | assert_type<const int&>();
151   m | member<Mutable>(&Counter::ref) | assert_type<int&>();
152   c | member<Const>(&Counter::ref) | assert_type<const int&>();
153 }
154
155 TEST(Gen, Field) {
156   struct X {
157     X() : a(2), b(3), c(4), d(b) {}
158
159     const int a;
160     int b;
161     mutable int c;
162     int& d; // can't access this with a field pointer.
163   };
164
165   std::vector<X> xs(1);
166   EXPECT_EQ(2, from(xs)
167              | field(&X::a)
168              | sum);
169   EXPECT_EQ(3, from(xs)
170              | field(&X::b)
171              | sum);
172   EXPECT_EQ(4, from(xs)
173              | field(&X::c)
174              | sum);
175   EXPECT_EQ(2, seq(&xs[0], &xs[0])
176              | field(&X::a)
177              | sum);
178   // type-verification
179   empty<X&>() | field(&X::a) | assert_type<const int&>();
180   empty<X*>() | field(&X::a) | assert_type<const int&>();
181   empty<X&>() | field(&X::b) | assert_type<int&>();
182   empty<X*>() | field(&X::b) | assert_type<int&>();
183   empty<X&>() | field(&X::c) | assert_type<int&>();
184   empty<X*>() | field(&X::c) | assert_type<int&>();
185
186   empty<X&&>() | field(&X::a) | assert_type<const int&&>();
187   empty<X&&>() | field(&X::b) | assert_type<int&&>();
188   empty<X&&>() | field(&X::c) | assert_type<int&&>();
189   // references don't imply ownership so they're not moved
190
191   empty<const X&>() | field(&X::a) | assert_type<const int&>();
192   empty<const X*>() | field(&X::a) | assert_type<const int&>();
193   empty<const X&>() | field(&X::b) | assert_type<const int&>();
194   empty<const X*>() | field(&X::b) | assert_type<const int&>();
195   // 'mutable' has no effect on field pointers, by C++ spec
196   empty<const X&>() | field(&X::c) | assert_type<const int&>();
197   empty<const X*>() | field(&X::c) | assert_type<const int&>();
198
199   // can't form pointer-to-reference field: empty<X&>() | field(&X::d)
200 }
201
202 TEST(Gen, Seq) {
203   // cover the fenceposts of the loop unrolling
204   for (int n = 1; n < 100; ++n) {
205     EXPECT_EQ(n, seq(1, n) | count);
206     EXPECT_EQ(n + 1, seq(1) | take(n + 1) | count);
207   }
208 }
209
210 TEST(Gen, SeqWithStep) {
211   EXPECT_EQ(75, seq(5, 25, 5) | sum);
212 }
213
214 TEST(Gen, SeqWithStepArray) {
215   const std::array<int, 6> arr{{1, 2, 3, 4, 5, 6}};
216   EXPECT_EQ(9, seq(&arr[0], &arr[5], 2)
217              | map([](const int *i) { return *i; })
218              | sum);
219 }
220
221 TEST(Gen, Range) {
222   // cover the fenceposts of the loop unrolling
223   for (int n = 1; n < 100; ++n) {
224     EXPECT_EQ(gen::range(0, n) | count, n);
225   }
226 }
227
228 TEST(Gen, RangeWithStep) {
229   EXPECT_EQ(50, range(5, 25, 5) | sum);
230 }
231
232 TEST(Gen, FromIterators) {
233   vector<int> source {2, 3, 5, 7, 11};
234   auto gen = from(folly::range(source.begin() + 1, source.end() - 1));
235   EXPECT_EQ(3 * 5 * 7, gen | product);
236 }
237
238 TEST(Gen, FromMap) {
239   auto source = seq(0, 10)
240               | map([](int i) { return std::make_pair(i, i * i); })
241               | as<std::map<int, int>>();
242   auto gen = fromConst(source)
243            | map([&](const std::pair<const int, int>& p) {
244                return p.second - p.first;
245              });
246   EXPECT_EQ(330, gen | sum);
247 }
248
249 TEST(Gen, Filter) {
250   const auto expected = vector<int>{1, 2, 4, 5, 7, 8};
251   auto actual =
252       seq(1, 9)
253     | filter([](int x) { return x % 3; })
254     | as<vector<int>>();
255   EXPECT_EQ(expected, actual);
256 }
257
258 TEST(Gen, FilterDefault) {
259   {
260     // Default filter should remove 0s
261     const auto expected = vector<int>{1, 1, 2, 3};
262     auto actual =
263         from({0, 1, 1, 0, 2, 3, 0})
264       | filter()
265       | as<vector>();
266     EXPECT_EQ(expected, actual);
267   }
268   {
269     // Default filter should remove nullptrs
270     int a = 5;
271     int b = 3;
272     int c = 0;
273     const auto expected = vector<int*>{&a, &b, &c};
274     auto actual =
275         from({(int*)nullptr, &a, &b, &c, (int*)nullptr})
276       | filter()
277       | as<vector>();
278     EXPECT_EQ(expected, actual);
279   }
280   {
281     // Default filter on Optionals should remove folly::null
282     const auto expected =
283         vector<Optional<int>>{Optional<int>(5), Optional<int>(0)};
284     const auto actual =
285         from({Optional<int>(5), Optional<int>(), Optional<int>(0)})
286       | filter()
287       | as<vector>();
288     EXPECT_EQ(expected, actual);
289   }
290 }
291
292 TEST(Gen, Contains) {
293   {
294     auto gen =
295         seq(1, 9)
296       | map(square);
297     EXPECT_TRUE(gen | contains(49));
298     EXPECT_FALSE(gen | contains(50));
299   }
300   {
301     auto gen =
302         seq(1) // infinite, to prove laziness
303       | map(square)
304       | eachTo<std::string>();
305
306     // std::string gen, const char* needle
307     EXPECT_TRUE(gen | take(9999) | contains("49"));
308   }
309 }
310
311 TEST(Gen, Take) {
312   {
313     auto expected = vector<int>{1, 4, 9, 16};
314     auto actual =
315       seq(1, 1000)
316       | mapped([](int x) { return x * x; })
317       | take(4)
318       | as<vector<int>>();
319     EXPECT_EQ(expected, actual);
320   }
321   {
322     auto expected = vector<int>{ 0, 1, 4, 5, 8 };
323     auto actual
324       = ((seq(0) | take(2)) +
325          (seq(4) | take(2)) +
326          (seq(8) | take(2)))
327       | take(5)
328       | as<vector>();
329     EXPECT_EQ(expected, actual);
330   }
331   {
332     auto expected = vector<int>{ 0, 1, 4, 5, 8 };
333     auto actual
334       = seq(0)
335       | mapped([](int i) {
336           return seq(i * 4) | take(2);
337         })
338       | concat
339       | take(5)
340       | as<vector>();
341     EXPECT_EQ(expected, actual);
342   }
343 }
344
345
346 TEST(Gen, Stride) {
347   {
348     EXPECT_THROW(stride(0), std::invalid_argument);
349   }
350   {
351     auto expected = vector<int>{1, 2, 3, 4};
352     auto actual
353       = seq(1, 4)
354       | stride(1)
355       | as<vector<int>>();
356     EXPECT_EQ(expected, actual);
357   }
358   {
359     auto expected = vector<int>{1, 3, 5, 7};
360     auto actual
361       = seq(1, 8)
362       | stride(2)
363       | as<vector<int>>();
364     EXPECT_EQ(expected, actual);
365   }
366   {
367     auto expected = vector<int>{1, 4, 7, 10};
368     auto actual
369       = seq(1, 12)
370       | stride(3)
371       | as<vector<int>>();
372     EXPECT_EQ(expected, actual);
373   }
374   {
375     auto expected = vector<int>{1, 3, 5, 7, 9, 1, 4, 7, 10};
376     auto actual
377       = ((seq(1, 10) | stride(2)) +
378          (seq(1, 10) | stride(3)))
379       | as<vector<int>>();
380     EXPECT_EQ(expected, actual);
381   }
382   EXPECT_EQ(500, seq(1) | take(1000) | stride(2) | count);
383   EXPECT_EQ(10, seq(1) | take(1000) | stride(2) | take(10) | count);
384 }
385
386 TEST(Gen, Sample) {
387   std::mt19937 rnd(42);
388
389   auto sampler =
390       seq(1, 100)
391     | sample(50, rnd);
392   std::unordered_map<int,int> hits;
393   const int kNumIters = 80;
394   for (int i = 0; i < kNumIters; i++) {
395     auto vec = sampler | as<vector<int>>();
396     EXPECT_EQ(vec.size(), 50);
397     auto uniq = fromConst(vec) | as<set<int>>();
398     EXPECT_EQ(uniq.size(), vec.size());  // sampling without replacement
399     for (auto v: vec) {
400       ++hits[v];
401     }
402   }
403
404   // In 80 separate samples of our range, we should have seen every value
405   // at least once and no value all 80 times. (The odds of either of those
406   // events is 1/2^80).
407   EXPECT_EQ(hits.size(), 100);
408   for (auto hit: hits) {
409     EXPECT_GT(hit.second, 0);
410     EXPECT_LT(hit.second, kNumIters);
411   }
412
413   auto small =
414       seq(1, 5)
415     | sample(10);
416   EXPECT_EQ((small | sum), 15);
417   EXPECT_EQ((small | take(3) | count), 3);
418 }
419
420 TEST(Gen, Skip) {
421   auto gen =
422       seq(1, 1000)
423     | mapped([](int x) { return x * x; })
424     | skip(4)
425     | take(4);
426   EXPECT_EQ((vector<int>{25, 36, 49, 64}), gen | as<vector>());
427 }
428
429 TEST(Gen, Until) {
430   {
431     auto expected = vector<int>{1, 4, 9, 16};
432     auto actual
433       = seq(1, 1000)
434       | mapped([](int x) { return x * x; })
435       | until([](int x) { return x > 20; })
436       | as<vector<int>>();
437     EXPECT_EQ(expected, actual);
438   }
439   {
440     auto expected = vector<int>{ 0, 1, 4, 5, 8 };
441     auto actual
442       = ((seq(0) | until([](int i) { return i > 1; })) +
443          (seq(4) | until([](int i) { return i > 5; })) +
444          (seq(8) | until([](int i) { return i > 9; })))
445       | until([](int i) { return i > 8; })
446       | as<vector<int>>();
447     EXPECT_EQ(expected, actual);
448   }
449   /*
450   {
451     auto expected = vector<int>{ 0, 1, 5, 6, 10 };
452     auto actual
453       = seq(0)
454       | mapped([](int i) {
455           return seq(i * 5) | until([=](int j) { return j > i * 5 + 1; });
456         })
457       | concat
458       | until([](int i) { return i > 10; })
459       | as<vector<int>>();
460     EXPECT_EQ(expected, actual);
461   }
462   */
463 }
464
465 TEST(Gen, Composed) {
466   // Operator, Operator
467   auto valuesOf =
468       filter([](Optional<int>& o) { return o.hasValue(); })
469     | map([](Optional<int>& o) -> int& { return o.value(); });
470   std::vector<Optional<int>> opts {
471     none, 4, none, 6, none
472   };
473   EXPECT_EQ(4 * 4 + 6 * 6, from(opts) | valuesOf | map(square) | sum);
474   // Operator, Sink
475   auto sumOpt = valuesOf | sum;
476   EXPECT_EQ(10, from(opts) | sumOpt);
477 }
478
479 TEST(Gen, Chain) {
480   std::vector<int> nums {2, 3, 5, 7};
481   std::map<int, int> mappings { { 3, 9}, {5, 25} };
482   auto gen = from(nums) + (from(mappings) | get<1>());
483   EXPECT_EQ(51, gen | sum);
484   EXPECT_EQ(5, gen | take(2) | sum);
485   EXPECT_EQ(26, gen | take(5) | sum);
486 }
487
488 TEST(Gen, Concat) {
489   std::vector<std::vector<int>> nums {{2, 3}, {5, 7}};
490   auto gen = from(nums) | rconcat;
491   EXPECT_EQ(17, gen | sum);
492   EXPECT_EQ(10, gen | take(3) | sum);
493 }
494
495 TEST(Gen, ConcatGen) {
496   auto gen = seq(1, 10)
497            | map([](int i) { return seq(1, i); })
498            | concat;
499   EXPECT_EQ(220, gen | sum);
500   EXPECT_EQ(10, gen | take(6) | sum);
501 }
502
503 TEST(Gen, ConcatAlt) {
504   std::vector<std::vector<int>> nums {{2, 3}, {5, 7}};
505   auto actual = from(nums)
506               | map([](std::vector<int>& v) { return from(v); })
507               | concat
508               | sum;
509   auto expected = 17;
510   EXPECT_EQ(expected, actual);
511 }
512
513 TEST(Gen, Order) {
514   auto expected = vector<int>{0, 3, 5, 6, 7, 8, 9};
515   auto actual =
516       from({8, 6, 7, 5, 3, 0, 9})
517     | order
518     | as<vector>();
519   EXPECT_EQ(expected, actual);
520 }
521
522 TEST(Gen, OrderMoved) {
523   auto expected = vector<int>{0, 9, 25, 36, 49, 64, 81};
524   auto actual =
525       from({8, 6, 7, 5, 3, 0, 9})
526     | move
527     | order
528     | map(square)
529     | as<vector>();
530   EXPECT_EQ(expected, actual);
531 }
532
533 TEST(Gen, OrderTake) {
534   auto expected = vector<int>{9, 8, 7};
535   auto actual =
536       from({8, 6, 7, 5, 3, 0, 9})
537     | orderByDescending(square)
538     | take(3)
539     | as<vector>();
540   EXPECT_EQ(expected, actual);
541 }
542
543 TEST(Gen, Distinct) {
544   auto expected = vector<int>{3, 1, 2};
545   auto actual =
546       from({3, 1, 3, 2, 1, 2, 3})
547     | distinct
548     | as<vector>();
549   EXPECT_EQ(expected, actual);
550 }
551
552 TEST(Gen, DistinctBy) {   //  0  1  4  9  6  5  6  9  4  1  0
553   auto expected = vector<int>{0, 1, 2, 3, 4, 5};
554   auto actual =
555       seq(0, 100)
556     | distinctBy([](int i) { return i * i % 10; })
557     | as<vector>();
558   EXPECT_EQ(expected, actual);
559 }
560
561 TEST(Gen, DistinctMove) {   //  0  1  4  9  6  5  6  9  4  1  0
562   auto expected = vector<int>{0, 1, 2, 3, 4, 5};
563   auto actual =
564       seq(0, 100)
565     | mapped([](int i) { return std::unique_ptr<int>(new int(i)); })
566       // see comment below about selector parameters for Distinct
567     | distinctBy([](const std::unique_ptr<int>& pi) { return *pi * *pi % 10; })
568     | mapped([](std::unique_ptr<int> pi) { return *pi; })
569     | as<vector>();
570
571   // NOTE(tjackson): the following line intentionally doesn't work:
572   //  | distinctBy([](std::unique_ptr<int> pi) { return *pi * *pi % 10; })
573   // This is because distinctBy because the selector intentionally requires a
574   // const reference.  If it required a move-reference, the value might get
575   // gutted by the selector before said value could be passed to downstream
576   // operators.
577   EXPECT_EQ(expected, actual);
578 }
579
580 TEST(Gen, DistinctInfinite) {
581   // distinct should be able to handle an infinite sequence, provided that, of
582   // of cource, is it eventually made finite before returning the result.
583   auto expected = seq(0) | take(5) | as<vector>(); // 0 1 2 3 4
584
585   auto actual =
586       seq(0)                              // 0 1 2 3 4 5 6 7 ...
587     | mapped([](int i) { return i / 2; }) // 0 0 1 1 2 2 3 3 ...
588     | distinct                            // 0 1 2 3 4 5 6 7 ...
589     | take(5)                             // 0 1 2 3 4
590     | as<vector>();
591
592   EXPECT_EQ(expected, actual);
593 }
594
595 TEST(Gen, DistinctByInfinite) {
596   // Similarly to the DistinctInfinite test case, distinct by should be able to
597   // handle infinite sequences. Note that depending on how many values we take()
598   // at the end, the sequence may infinite loop. This is fine becasue we cannot
599   // solve the halting problem.
600   auto expected = vector<int>{1, 2};
601   auto actual =
602       seq(1)                                    // 1 2 3 4 5 6 7 8 ...
603     | distinctBy([](int i) { return i % 2; })   // 1 2 (but might by infinite)
604     | take(2)                                   // 1 2
605     | as<vector>();
606   // Note that if we had take(3), this would infinite loop
607
608   EXPECT_EQ(expected, actual);
609 }
610
611 TEST(Gen, MinBy) {
612   EXPECT_EQ(7, seq(1, 10)
613              | minBy([](int i) -> double {
614                  double d = i - 6.8;
615                  return d * d;
616                })
617              | unwrap);
618 }
619
620 TEST(Gen, MaxBy) {
621   auto gen = from({"three", "eleven", "four"});
622
623   EXPECT_EQ("eleven", gen | maxBy(&strlen) | unwrap);
624 }
625
626 TEST(Gen, Min) {
627   auto odds = seq(2,10) | filter([](int i){ return i % 2; });
628
629   EXPECT_EQ(3, odds | min);
630 }
631
632 TEST(Gen, Max) {
633   auto odds = seq(2,10) | filter([](int i){ return i % 2; });
634
635   EXPECT_EQ(9, odds | max);
636 }
637
638 TEST(Gen, Append) {
639   string expected = "facebook";
640   string actual = "face";
641   from(StringPiece("book")) | appendTo(actual);
642   EXPECT_EQ(expected, actual);
643 }
644
645 TEST(Gen, FromRValue) {
646   {
647     // AFAICT The C++ Standard does not specify what happens to the rvalue
648     // reference of a std::vector when it is used as the 'other' for an rvalue
649     // constructor.  Use fbvector because we're sure its size will be zero in
650     // this case.
651     fbvector<int> v({1,2,3,4});
652     auto q1 = from(v);
653     EXPECT_EQ(v.size(), 4);  // ensure that the lvalue version was called!
654     auto expected = 1 * 2 * 3 * 4;
655     EXPECT_EQ(expected, q1 | product);
656
657     auto q2 = from(std::move(v));
658     EXPECT_EQ(v.size(), 0);  // ensure that rvalue version was called
659     EXPECT_EQ(expected, q2 | product);
660   }
661   {
662     auto expected = 7;
663     auto q = from([] {return vector<int>({3,7,5}); }());
664     EXPECT_EQ(expected, q | max);
665   }
666   {
667     for (auto size: {5, 1024, 16384, 1<<20}) {
668       auto q1 = from(vector<int>(size, 2));
669       auto q2 = from(vector<int>(size, 3));
670       // If the rvalue specialization is broken/gone, then the compiler will
671       // (disgustingly!) just store a *reference* to the temporary object,
672       // which is bad.  Try to catch this by allocating two temporary vectors
673       // of the same size, so that they'll probably use the same underlying
674       // buffer if q1's vector is destructed before q2's vector is constructed.
675       EXPECT_EQ(size * 2 + size * 3, (q1 | sum) + (q2 | sum));
676     }
677   }
678   {
679     auto q = from(set<int>{1,2,3,2,1});
680     EXPECT_EQ(q | sum, 6);
681   }
682 }
683
684 TEST(Gen, OrderBy) {
685   auto expected = vector<int>{5, 6, 4, 7, 3, 8, 2, 9, 1, 10};
686   auto actual =
687       seq(1, 10)
688     | orderBy([](int x) { return (5.1 - x) * (5.1 - x); })
689     | as<vector>();
690   EXPECT_EQ(expected, actual);
691
692   expected = seq(1, 10) | as<vector>();
693   actual =
694       from(expected)
695     | map([] (int x) { return 11 - x; })
696     | orderBy()
697     | as<vector>();
698   EXPECT_EQ(expected, actual);
699 }
700
701 TEST(Gen, Foldl) {
702   int expected = 2 * 3 * 4 * 5;
703   auto actual =
704       seq(2, 5)
705     | foldl(1, multiply);
706   EXPECT_EQ(expected, actual);
707 }
708
709 TEST(Gen, Reduce) {
710   int expected = 2 + 3 + 4 + 5;
711   auto actual = seq(2, 5) | reduce(add);
712   EXPECT_EQ(expected, actual | unwrap);
713 }
714
715 TEST(Gen, ReduceBad) {
716   auto gen = seq(1) | take(0);
717   auto actual = gen | reduce(add);
718   EXPECT_FALSE(actual); // Empty sequences are okay, they just yeild 'none'
719 }
720
721 TEST(Gen, Moves) {
722   std::vector<unique_ptr<int>> ptrs;
723   ptrs.emplace_back(new int(1));
724   EXPECT_NE(ptrs.front().get(), nullptr);
725   auto ptrs2 = from(ptrs) | move | as<vector>();
726   EXPECT_EQ(ptrs.front().get(), nullptr);
727   EXPECT_EQ(**ptrs2.data(), 1);
728 }
729
730 TEST(Gen, First) {
731   auto gen = seq(0) | filter([](int x) { return x > 3; });
732   EXPECT_EQ(4, gen | first | unwrap);
733 }
734
735 TEST(Gen, FromCopy) {
736   vector<int> v {3, 5};
737   auto src = from(v);
738   auto copy = fromCopy(v);
739   EXPECT_EQ(8, src | sum);
740   EXPECT_EQ(8, copy | sum);
741   v[1] = 7;
742   EXPECT_EQ(10, src | sum);
743   EXPECT_EQ(8, copy | sum);
744 }
745
746 TEST(Gen, Get) {
747   std::map<int, int> pairs {
748     {1, 1},
749     {2, 4},
750     {3, 9},
751     {4, 16},
752   };
753   auto pairSrc = from(pairs);
754   auto keys = pairSrc | get<0>();
755   auto values = pairSrc | get<1>();
756   EXPECT_EQ(10, keys | sum);
757   EXPECT_EQ(30, values | sum);
758   EXPECT_EQ(30, keys | map(square) | sum);
759   pairs[5] = 25;
760   EXPECT_EQ(15, keys | sum);
761   EXPECT_EQ(55, values | sum);
762
763   vector<tuple<int, int, int>> tuples {
764     make_tuple(1, 1, 1),
765     make_tuple(2, 4, 8),
766     make_tuple(3, 9, 27),
767   };
768   EXPECT_EQ(36, from(tuples) | get<2>() | sum);
769 }
770
771 TEST(Gen, notEmpty) {
772   EXPECT_TRUE(seq(0, 1) | notEmpty);
773   EXPECT_TRUE(just(1) | notEmpty);
774   EXPECT_FALSE(gen::range(0, 0) | notEmpty);
775   EXPECT_FALSE(from({1}) | take(0) | notEmpty);
776 }
777
778 TEST(Gen, isEmpty) {
779   EXPECT_FALSE(seq(0, 1) | isEmpty);
780   EXPECT_FALSE(just(1) | isEmpty);
781   EXPECT_TRUE(gen::range(0, 0) | isEmpty);
782   EXPECT_TRUE(from({1}) | take(0) | isEmpty);
783 }
784
785 TEST(Gen, Any) {
786   EXPECT_TRUE(seq(0, 10) | any([](int i) { return i == 7; }));
787   EXPECT_FALSE(seq(0, 10) | any([](int i) { return i == 11; }));
788 }
789
790 TEST(Gen, All) {
791   EXPECT_TRUE(seq(0, 10) | all([](int i) { return i < 11; }));
792   EXPECT_FALSE(seq(0, 10) | all([](int i) { return i < 5; }));
793   EXPECT_FALSE(seq(0) | take(9999) | all([](int i) { return i < 10; }));
794
795   // empty lists satisfies all
796   EXPECT_TRUE(seq(0) | take(0) | all([](int i) { return i < 50; }));
797   EXPECT_TRUE(seq(0) | take(0) | all([](int i) { return i > 50; }));
798 }
799
800 TEST(Gen, Yielders) {
801   auto gen = GENERATOR(int) {
802     for (int i = 1; i <= 5; ++i) {
803       yield(i);
804     }
805     yield(7);
806     for (int i = 3; ; ++i) {
807       yield(i * i);
808     }
809   };
810   vector<int> expected {
811     1, 2, 3, 4, 5, 7, 9, 16, 25
812   };
813   EXPECT_EQ(expected, gen | take(9) | as<vector>());
814 }
815
816 TEST(Gen, NestedYield) {
817   auto nums = GENERATOR(int) {
818     for (int i = 1; ; ++i) {
819       yield(i);
820     }
821   };
822   auto gen = GENERATOR(int) {
823     nums | take(10) | yield;
824     seq(1, 5) | [&](int i) {
825       yield(i);
826     };
827   };
828   EXPECT_EQ(70, gen | sum);
829 }
830
831 TEST(Gen, MapYielders) {
832   auto gen = seq(1, 5)
833            | map([](int n) {
834                return GENERATOR(int) {
835                  int i;
836                  for (i = 1; i < n; ++i)
837                    yield(i);
838                  for (; i >= 1; --i)
839                    yield(i);
840                };
841              })
842            | concat;
843   vector<int> expected {
844                 1,
845              1, 2, 1,
846           1, 2, 3, 2, 1,
847        1, 2, 3, 4, 3, 2, 1,
848     1, 2, 3, 4, 5, 4, 3, 2, 1,
849   };
850   EXPECT_EQ(expected, gen | as<vector>());
851 }
852
853 TEST(Gen, VirtualGen) {
854   VirtualGen<int> v(seq(1, 10));
855   EXPECT_EQ(55, v | sum);
856   v = v | map(square);
857   EXPECT_EQ(385, v | sum);
858   v = v | take(5);
859   EXPECT_EQ(55, v | sum);
860   EXPECT_EQ(30, v | take(4) | sum);
861 }
862
863
864 TEST(Gen, CustomType) {
865   struct Foo{
866     int y;
867   };
868   auto gen = from({Foo{2}, Foo{3}})
869            | map([](const Foo& f) { return f.y; });
870   EXPECT_EQ(5, gen | sum);
871 }
872
873 TEST(Gen, NoNeedlessCopies) {
874   auto gen = seq(1, 5)
875            | map([](int x) { return unique_ptr<int>(new int(x)); })
876            | map([](unique_ptr<int> p) { return p; })
877            | map([](unique_ptr<int>&& p) { return std::move(p); })
878            | map([](const unique_ptr<int>& p) { return *p; });
879   EXPECT_EQ(15, gen | sum);
880   EXPECT_EQ(6, gen | take(3) | sum);
881 }
882
883 namespace {
884
885 class TestIntSeq : public GenImpl<int, TestIntSeq> {
886  public:
887   TestIntSeq() { }
888
889   template <class Body>
890   bool apply(Body&& body) const {
891     for (int i = 1; i < 6; ++i) {
892       if (!body(i)) {
893         return false;
894       }
895     }
896     return true;
897   }
898
899   TestIntSeq(TestIntSeq&&) noexcept = default;
900   TestIntSeq& operator=(TestIntSeq&&) noexcept = default;
901   TestIntSeq(const TestIntSeq&) = delete;
902   TestIntSeq& operator=(const TestIntSeq&) = delete;
903 };
904
905 }  // namespace
906
907 TEST(Gen, NoGeneratorCopies) {
908   EXPECT_EQ(15, TestIntSeq() | sum);
909   auto x = TestIntSeq() | take(3);
910   EXPECT_EQ(6, std::move(x) | sum);
911 }
912
913 TEST(Gen, FromArray) {
914   int source[] = {2, 3, 5, 7};
915   auto gen = from(source);
916   EXPECT_EQ(2 * 3 * 5 * 7, gen | product);
917 }
918
919 TEST(Gen, FromStdArray) {
920   std::array<int,4> source {{2, 3, 5, 7}};
921   auto gen = from(source);
922   EXPECT_EQ(2 * 3 * 5 * 7, gen | product);
923 }
924
925 TEST(Gen, StringConcat) {
926   auto gen = seq(1, 10)
927            | eachTo<string>()
928            | rconcat;
929   EXPECT_EQ("12345678910", gen | as<string>());
930 }
931
932 struct CopyCounter {
933   static int alive;
934   int copies;
935   int moves;
936
937   CopyCounter() : copies(0), moves(0) {
938     ++alive;
939   }
940
941   CopyCounter(CopyCounter&& source) noexcept {
942     *this = std::move(source);
943     ++alive;
944   }
945
946   CopyCounter(const CopyCounter& source) {
947     *this = source;
948     ++alive;
949   }
950
951   ~CopyCounter() {
952     --alive;
953   }
954
955   CopyCounter& operator=(const CopyCounter& source) {
956     this->copies = source.copies + 1;
957     this->moves = source.moves;
958     return *this;
959   }
960
961   CopyCounter& operator=(CopyCounter&& source) {
962     this->copies = source.copies;
963     this->moves = source.moves + 1;
964     return *this;
965   }
966 };
967
968 int CopyCounter::alive = 0;
969
970 TEST(Gen, CopyCount) {
971   vector<CopyCounter> originals;
972   originals.emplace_back();
973   EXPECT_EQ(1, originals.size());
974   EXPECT_EQ(0, originals.back().copies);
975
976   vector<CopyCounter> copies = from(originals) | as<vector>();
977   EXPECT_EQ(1, copies.back().copies);
978   EXPECT_EQ(0, copies.back().moves);
979
980   vector<CopyCounter> moves = from(originals) | move | as<vector>();
981   EXPECT_EQ(0, moves.back().copies);
982   EXPECT_EQ(1, moves.back().moves);
983 }
984
985 // test dynamics with various layers of nested arrays.
986 TEST(Gen, Dynamic) {
987   dynamic array1 = {1, 2};
988   EXPECT_EQ(dynamic(3), from(array1) | sum);
989   dynamic array2 = {{1}, {1, 2}};
990   EXPECT_EQ(dynamic(4), from(array2) | rconcat | sum);
991   dynamic array3 = {{{1}}, {{1}, {1, 2}}};
992   EXPECT_EQ(dynamic(5), from(array3) | rconcat | rconcat | sum);
993 }
994
995 TEST(Gen, DynamicObject) {
996   const dynamic obj = dynamic::object(1, 2)(3, 4);
997   EXPECT_EQ(dynamic(4), from(obj.keys()) | sum);
998   EXPECT_EQ(dynamic(6), from(obj.values()) | sum);
999   EXPECT_EQ(dynamic(4), from(obj.items()) | get<0>() | sum);
1000   EXPECT_EQ(dynamic(6), from(obj.items()) | get<1>() | sum);
1001 }
1002
1003 TEST(Gen, Collect) {
1004   auto s = from({7, 6, 5, 4, 3}) | as<set<int>>();
1005   EXPECT_EQ(s.size(), 5);
1006 }
1007
1008
1009 TEST(Gen, Cycle) {
1010   {
1011     auto s = from({1, 2});
1012     EXPECT_EQ((vector<int> { 1, 2, 1, 2, 1 }),
1013               s | cycle | take(5) | as<vector>());
1014   }
1015   {
1016     auto s = from({1, 2});
1017     EXPECT_EQ((vector<int> { 1, 2, 1, 2 }),
1018               s | cycle(2) | as<vector>());
1019   }
1020   {
1021     auto s = from({1, 2, 3});
1022     EXPECT_EQ((vector<int> { 1, 2, 1, 2, 1 }),
1023               s | take(2) | cycle | take(5) | as<vector>());
1024   }
1025   {
1026     auto s = empty<int>();
1027     EXPECT_EQ((vector<int> { }),
1028               s | cycle | take(4) | as<vector>());
1029   }
1030   {
1031     int count = 3;
1032     int* pcount = &count;
1033     auto countdown = GENERATOR(int) {
1034       ASSERT_GE(*pcount, 0)
1035         << "Cycle should have stopped when it didnt' get values!";
1036       for (int i = 1; i <= *pcount; ++i) {
1037         yield(i);
1038       }
1039       --*pcount;
1040     };
1041     auto s = countdown;
1042     EXPECT_EQ((vector<int> { 1, 2, 3, 1, 2, 1}),
1043               s | cycle | take(7) | as<vector>());
1044     // take necessary as cycle returns an infinite generator
1045   }
1046 }
1047
1048 TEST(Gen, Dereference) {
1049   {
1050     const int x = 4, y = 2;
1051     auto s = from(std::initializer_list<const int*>({&x, nullptr, &y}));
1052     EXPECT_EQ(6, s | dereference | sum);
1053   }
1054   {
1055     vector<int> a { 1, 2 };
1056     vector<int> b { 3, 4 };
1057     vector<vector<int>*> pv { &a, nullptr, &b };
1058     from(pv)
1059       | dereference
1060       | [&](vector<int>& v) {
1061           v.push_back(5);
1062         };
1063     EXPECT_EQ(3, a.size());
1064     EXPECT_EQ(3, b.size());
1065     EXPECT_EQ(5, a.back());
1066     EXPECT_EQ(5, b.back());
1067   }
1068   {
1069     vector<std::map<int, int>> maps {
1070       {
1071         { 2, 31 },
1072         { 3, 41 },
1073       },
1074       {
1075         { 3, 52 },
1076         { 4, 62 },
1077       },
1078       {
1079         { 4, 73 },
1080         { 5, 83 },
1081       },
1082     };
1083     EXPECT_EQ(
1084       93,
1085       from(maps)
1086       | map([](std::map<int, int>& m) {
1087           return get_ptr(m, 3);
1088         })
1089       | dereference
1090       | sum);
1091   }
1092   {
1093     vector<unique_ptr<int>> ups;
1094     ups.emplace_back(new int(3));
1095     ups.emplace_back();
1096     ups.emplace_back(new int(7));
1097     EXPECT_EQ(10, from(ups) | dereference | sum);
1098     EXPECT_EQ(10, from(ups) | move | dereference | sum);
1099   }
1100 }
1101
1102 TEST(Gen, Indirect) {
1103   vector<int> vs{1};
1104   EXPECT_EQ(&vs[0], from(vs) | indirect | first | unwrap);
1105 }
1106
1107 TEST(Gen, Guard) {
1108   using std::runtime_error;
1109   EXPECT_THROW(from({"1", "a", "3"})
1110                | eachTo<int>()
1111                | sum,
1112                runtime_error);
1113   EXPECT_EQ(4,
1114             from({"1", "a", "3"})
1115             | guard<runtime_error>([](runtime_error&, const char*) {
1116                 return true; // continue
1117               })
1118             | eachTo<int>()
1119             | sum);
1120   EXPECT_EQ(1,
1121             from({"1", "a", "3"})
1122             | guard<runtime_error>([](runtime_error&, const char*) {
1123                 return false; // break
1124               })
1125             | eachTo<int>()
1126             | sum);
1127   EXPECT_THROW(from({"1", "a", "3"})
1128                 | guard<runtime_error>([](runtime_error&, const char* v) {
1129                     if (v[0] == 'a') {
1130                       throw;
1131                     }
1132                     return true;
1133                   })
1134                | eachTo<int>()
1135                | sum,
1136                runtime_error);
1137 }
1138
1139 TEST(Gen, Batch) {
1140   EXPECT_EQ((vector<vector<int>> { {1} }),
1141             seq(1, 1) | batch(5) | as<vector>());
1142   EXPECT_EQ((vector<vector<int>> { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11} }),
1143             seq(1, 11) | batch(3) | as<vector>());
1144   EXPECT_THROW(seq(1, 1) | batch(0) | as<vector>(),
1145                std::invalid_argument);
1146 }
1147
1148 TEST(Gen, BatchMove) {
1149   auto expected = vector<vector<int>>{ {0, 1}, {2, 3}, {4} };
1150   auto actual =
1151       seq(0, 4)
1152     | mapped([](int i) { return std::unique_ptr<int>(new int(i)); })
1153     | batch(2)
1154     | mapped([](std::vector<std::unique_ptr<int>>& pVector) {
1155         std::vector<int> iVector;
1156         for (const auto& p : pVector) {
1157           iVector.push_back(*p);
1158         };
1159         return iVector;
1160       })
1161     | as<vector>();
1162   EXPECT_EQ(expected, actual);
1163 }
1164
1165 TEST(Gen, Just) {
1166   {
1167     int x = 3;
1168     auto j = just(x);
1169     EXPECT_EQ(&x, j | indirect | first | unwrap);
1170     x = 4;
1171     EXPECT_EQ(4, j | sum);
1172   }
1173   {
1174     int x = 3;
1175     const int& cx = x;
1176     auto j = just(cx);
1177     EXPECT_EQ(&x, j | indirect | first | unwrap);
1178     x = 5;
1179     EXPECT_EQ(5, j | sum);
1180   }
1181   {
1182     int x = 3;
1183     auto j = just(std::move(x));
1184     EXPECT_NE(&x, j | indirect | first | unwrap);
1185     x = 5;
1186     EXPECT_EQ(3, j | sum);
1187   }
1188 }
1189
1190 TEST(Gen, GroupBy) {
1191   vector<string> strs{"zero", "one", "two",   "three", "four",
1192                       "five", "six", "seven", "eight", "nine"};
1193
1194   auto gb = from(strs) | groupBy([](const string& str) { return str.size(); });
1195
1196   EXPECT_EQ(10, gb | mapOp(count) | sum);
1197   EXPECT_EQ(3, gb | count);
1198
1199   vector<string> mode{"zero", "four", "five", "nine"};
1200   EXPECT_EQ(mode,
1201             gb | maxBy([](const Group<size_t, string>& g) { return g.size(); })
1202                | unwrap
1203                | as<vector>());
1204
1205   vector<string> largest{"three", "seven", "eight"};
1206   EXPECT_EQ(largest,
1207             gb | maxBy([](const Group<size_t, string>& g) { return g.key(); })
1208                | unwrap
1209                | as<vector>());
1210 }
1211
1212 TEST(Gen, Unwrap) {
1213   Optional<int> o(4);
1214   Optional<int> e;
1215   EXPECT_EQ(4, o | unwrap);
1216   EXPECT_THROW(e | unwrap, OptionalEmptyException);
1217
1218   auto oup = folly::make_optional(folly::make_unique<int>(5));
1219   // optional has a value, and that value is non-null
1220   EXPECT_TRUE(oup | unwrap);
1221   EXPECT_EQ(5, *(oup | unwrap));
1222   EXPECT_TRUE(oup.hasValue()); // still has a pointer (null or not)
1223   EXPECT_TRUE(oup.value()); // that value isn't null
1224
1225   auto moved1 = std::move(oup) | unwrapOr(folly::make_unique<int>(6));
1226   // oup still has a value, but now it's now nullptr since the pointer was moved
1227   // into moved1
1228   EXPECT_TRUE(oup.hasValue());
1229   EXPECT_FALSE(oup.value());
1230   EXPECT_TRUE(moved1);
1231   EXPECT_EQ(5, *moved1);
1232
1233   auto moved2 = std::move(oup) | unwrapOr(folly::make_unique<int>(7));
1234   // oup's still-valid nullptr value wins here, the pointer to 7 doesn't apply
1235   EXPECT_FALSE(moved2);
1236
1237   oup.clear();
1238   auto moved3 = std::move(oup) | unwrapOr(folly::make_unique<int>(8));
1239   // oup is empty now, so the unwrapOr comes into play.
1240   EXPECT_TRUE(moved3);
1241   EXPECT_EQ(8, *moved3);
1242
1243   {
1244   // mixed types, with common type matching optional
1245     Optional<double> full(3.3);
1246     decltype(full) empty;
1247     auto fallback = unwrapOr(4);
1248     EXPECT_EQ(3.3, full | fallback);
1249     EXPECT_EQ(3.3, std::move(full) | fallback);
1250     EXPECT_EQ(3.3, full | std::move(fallback));
1251     EXPECT_EQ(3.3, std::move(full) | std::move(fallback));
1252     EXPECT_EQ(4.0, empty | fallback);
1253     EXPECT_EQ(4.0, std::move(empty) | fallback);
1254     EXPECT_EQ(4.0, empty | std::move(fallback));
1255     EXPECT_EQ(4.0, std::move(empty) | std::move(fallback));
1256   }
1257
1258   {
1259   // mixed types, with common type matching fallback
1260     Optional<int> full(3);
1261     decltype(full) empty;
1262     auto fallback = unwrapOr(5.0); // type: double
1263     // if we chose 'int' as the common type, we'd see truncation here
1264     EXPECT_EQ(1.5, (full | fallback) / 2);
1265     EXPECT_EQ(1.5, (std::move(full) | fallback) / 2);
1266     EXPECT_EQ(1.5, (full | std::move(fallback)) / 2);
1267     EXPECT_EQ(1.5, (std::move(full) | std::move(fallback)) / 2);
1268     EXPECT_EQ(2.5, (empty | fallback) / 2);
1269     EXPECT_EQ(2.5, (std::move(empty) | fallback) / 2);
1270     EXPECT_EQ(2.5, (empty | std::move(fallback)) / 2);
1271     EXPECT_EQ(2.5, (std::move(empty) | std::move(fallback)) / 2);
1272   }
1273
1274   {
1275     auto opt = folly::make_optional(std::make_shared<int>(8));
1276     auto fallback = unwrapOr(folly::make_unique<int>(9));
1277     // fallback must be std::move'd to be used
1278     EXPECT_EQ(8, *(opt | std::move(fallback)));
1279     EXPECT_TRUE(opt.value()); // shared_ptr copied out, not moved
1280     EXPECT_TRUE(opt); // value still present
1281     EXPECT_TRUE(fallback.value()); // fallback value not needed
1282
1283     EXPECT_EQ(8, *(std::move(opt) | std::move(fallback)));
1284     EXPECT_FALSE(opt.value()); // shared_ptr moved out
1285     EXPECT_TRUE(opt); // gutted value still present
1286     EXPECT_TRUE(fallback.value()); // fallback value not needed
1287
1288     opt.clear();
1289
1290     EXPECT_FALSE(opt); // opt is empty now
1291     EXPECT_EQ(9, *(std::move(opt) | std::move(fallback)));
1292     EXPECT_FALSE(fallback.value()); // fallback moved out!
1293   }
1294
1295   {
1296     // test with nullptr
1297     vector<int> v{1, 2};
1298     EXPECT_EQ(&v[1], from(v) | indirect | max | unwrap);
1299     v.clear();
1300     EXPECT_FALSE(from(v) | indirect | max | unwrapOr(nullptr));
1301   }
1302
1303   {
1304     // mixed type determined by fallback
1305     Optional<std::nullptr_t> empty;
1306     int x = 3;
1307     EXPECT_EQ(&x, empty | unwrapOr(&x));
1308   }
1309 }
1310
1311 int main(int argc, char *argv[]) {
1312   testing::InitGoogleTest(&argc, argv);
1313   gflags::ParseCommandLineFlags(&argc, &argv, true);
1314   return RUN_ALL_TESTS();
1315 }