2 * Copyright 2015 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 <glog/logging.h>
18 #include <gtest/gtest.h>
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>
31 using namespace folly::gen;
32 using namespace folly;
33 using std::make_tuple;
39 using std::unique_ptr;
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);
50 ostream& operator<<(ostream& os, const set<T>& values) {
51 return os << from(values);
55 ostream& operator<<(ostream& os, const vector<T>& values) {
57 for (auto& value : values) {
58 if (&value != &values.front()) {
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; };
70 auto product = foldl(1, multiply);
72 template<typename A, typename B>
73 ostream& operator<<(ostream& os, const pair<A, B>& pair) {
74 return os << "(" << pair.first << ", " << pair.second << ")";
78 auto gen = seq(1, 10);
79 EXPECT_EQ(10, gen | count);
80 EXPECT_EQ(5, gen | take(5) | count);
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);
92 gen | [&](int x) { accum += x; };
95 gen | take(3) | [&](int x) { accum2 += x; };
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>());
108 Counter(int start = 0)
112 int count() const { return c; }
113 int incr() { return ++c; }
115 int& ref() { return c; }
116 const int& ref() const { return c; }
120 auto counters = seq(1, 10) | eachAs<Counter>() | as<vector>();
121 EXPECT_EQ(10 * (1 + 10) / 2,
123 | member(&Counter::count)
125 EXPECT_EQ(10 * (1 + 10) / 2,
128 | member(&Counter::count)
130 EXPECT_EQ(10 * (2 + 11) / 2,
132 | member(&Counter::incr)
134 EXPECT_EQ(10 * (3 + 12) / 2,
137 | member(&Counter::incr)
139 EXPECT_EQ(10 * (3 + 12) / 2,
141 | member(&Counter::count)
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&>();
157 X() : a(2), b(3), c(4), d(b) {}
162 int& d; // can't access this with a field pointer.
165 std::vector<X> xs(1);
166 EXPECT_EQ(2, from(xs)
169 EXPECT_EQ(3, from(xs)
172 EXPECT_EQ(4, from(xs)
175 EXPECT_EQ(2, seq(&xs[0], &xs[0])
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&>();
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
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&>();
199 // can't form pointer-to-reference field: empty<X&>() | field(&X::d)
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);
210 TEST(Gen, SeqWithStep) {
211 EXPECT_EQ(75, seq(5, 25, 5) | sum);
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; })
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);
228 TEST(Gen, RangeWithStep) {
229 EXPECT_EQ(50, range(5, 25, 5) | sum);
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);
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;
246 EXPECT_EQ(330, gen | sum);
250 const auto expected = vector<int>{1, 2, 4, 5, 7, 8};
253 | filter([](int x) { return x % 3; })
255 EXPECT_EQ(expected, actual);
258 TEST(Gen, FilterDefault) {
260 // Default filter should remove 0s
261 const auto expected = vector<int>{1, 1, 2, 3};
263 from({0, 1, 1, 0, 2, 3, 0})
266 EXPECT_EQ(expected, actual);
269 // Default filter should remove nullptrs
273 const auto expected = vector<int*>{&a, &b, &c};
275 from({(int*)nullptr, &a, &b, &c, (int*)nullptr})
278 EXPECT_EQ(expected, actual);
281 // Default filter on Optionals should remove folly::null
282 const auto expected =
283 vector<Optional<int>>{Optional<int>(5), Optional<int>(0)};
285 from({Optional<int>(5), Optional<int>(), Optional<int>(0)})
288 EXPECT_EQ(expected, actual);
292 TEST(Gen, Contains) {
297 EXPECT_TRUE(gen | contains(49));
298 EXPECT_FALSE(gen | contains(50));
302 seq(1) // infinite, to prove laziness
304 | eachTo<std::string>();
306 // std::string gen, const char* needle
307 EXPECT_TRUE(gen | take(9999) | contains("49"));
313 auto expected = vector<int>{1, 4, 9, 16};
316 | mapped([](int x) { return x * x; })
319 EXPECT_EQ(expected, actual);
322 auto expected = vector<int>{ 0, 1, 4, 5, 8 };
324 = ((seq(0) | take(2)) +
329 EXPECT_EQ(expected, actual);
332 auto expected = vector<int>{ 0, 1, 4, 5, 8 };
336 return seq(i * 4) | take(2);
341 EXPECT_EQ(expected, actual);
348 EXPECT_THROW(stride(0), std::invalid_argument);
351 auto expected = vector<int>{1, 2, 3, 4};
356 EXPECT_EQ(expected, actual);
359 auto expected = vector<int>{1, 3, 5, 7};
364 EXPECT_EQ(expected, actual);
367 auto expected = vector<int>{1, 4, 7, 10};
372 EXPECT_EQ(expected, actual);
375 auto expected = vector<int>{1, 3, 5, 7, 9, 1, 4, 7, 10};
377 = ((seq(1, 10) | stride(2)) +
378 (seq(1, 10) | stride(3)))
380 EXPECT_EQ(expected, actual);
382 EXPECT_EQ(500, seq(1) | take(1000) | stride(2) | count);
383 EXPECT_EQ(10, seq(1) | take(1000) | stride(2) | take(10) | count);
387 std::mt19937 rnd(42);
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
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);
416 EXPECT_EQ((small | sum), 15);
417 EXPECT_EQ((small | take(3) | count), 3);
423 | mapped([](int x) { return x * x; })
426 EXPECT_EQ((vector<int>{25, 36, 49, 64}), gen | as<vector>());
431 auto expected = vector<int>{1, 4, 9, 16};
434 | mapped([](int x) { return x * x; })
435 | until([](int x) { return x > 20; })
437 EXPECT_EQ(expected, actual);
440 auto expected = vector<int>{ 0, 1, 4, 5, 8 };
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; })
447 EXPECT_EQ(expected, actual);
451 auto expected = vector<int>{ 0, 1, 5, 6, 10 };
455 return seq(i * 5) | until([=](int j) { return j > i * 5 + 1; });
458 | until([](int i) { return i > 10; })
460 EXPECT_EQ(expected, actual);
465 TEST(Gen, Composed) {
466 // Operator, Operator
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
473 EXPECT_EQ(4 * 4 + 6 * 6, from(opts) | valuesOf | map(square) | sum);
475 auto sumOpt = valuesOf | sum;
476 EXPECT_EQ(10, from(opts) | sumOpt);
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);
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);
495 TEST(Gen, ConcatGen) {
496 auto gen = seq(1, 10)
497 | map([](int i) { return seq(1, i); })
499 EXPECT_EQ(220, gen | sum);
500 EXPECT_EQ(10, gen | take(6) | sum);
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); })
510 EXPECT_EQ(expected, actual);
514 auto expected = vector<int>{0, 3, 5, 6, 7, 8, 9};
516 from({8, 6, 7, 5, 3, 0, 9})
519 EXPECT_EQ(expected, actual);
522 TEST(Gen, OrderMoved) {
523 auto expected = vector<int>{0, 9, 25, 36, 49, 64, 81};
525 from({8, 6, 7, 5, 3, 0, 9})
530 EXPECT_EQ(expected, actual);
533 TEST(Gen, OrderTake) {
534 auto expected = vector<int>{9, 8, 7};
536 from({8, 6, 7, 5, 3, 0, 9})
537 | orderByDescending(square)
540 EXPECT_EQ(expected, actual);
543 TEST(Gen, Distinct) {
544 auto expected = vector<int>{3, 1, 2};
546 from({3, 1, 3, 2, 1, 2, 3})
549 EXPECT_EQ(expected, actual);
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};
556 | distinctBy([](int i) { return i * i % 10; })
558 EXPECT_EQ(expected, actual);
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};
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; })
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
577 EXPECT_EQ(expected, actual);
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
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
592 EXPECT_EQ(expected, actual);
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};
602 seq(1) // 1 2 3 4 5 6 7 8 ...
603 | distinctBy([](int i) { return i % 2; }) // 1 2 (but might by infinite)
606 // Note that if we had take(3), this would infinite loop
608 EXPECT_EQ(expected, actual);
612 EXPECT_EQ(7, seq(1, 10)
613 | minBy([](int i) -> double {
621 auto gen = from({"three", "eleven", "four"});
623 EXPECT_EQ("eleven", gen | maxBy(&strlen) | unwrap);
627 auto odds = seq(2,10) | filter([](int i){ return i % 2; });
629 EXPECT_EQ(3, odds | min);
633 auto odds = seq(2,10) | filter([](int i){ return i % 2; });
635 EXPECT_EQ(9, odds | max);
639 string expected = "facebook";
640 string actual = "face";
641 from(StringPiece("book")) | appendTo(actual);
642 EXPECT_EQ(expected, actual);
645 TEST(Gen, FromRValue) {
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
651 fbvector<int> v({1,2,3,4});
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);
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);
663 auto q = from([] {return vector<int>({3,7,5}); }());
664 EXPECT_EQ(expected, q | max);
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));
679 auto q = from(set<int>{1,2,3,2,1});
680 EXPECT_EQ(q | sum, 6);
685 auto expected = vector<int>{5, 6, 4, 7, 3, 8, 2, 9, 1, 10};
688 | orderBy([](int x) { return (5.1 - x) * (5.1 - x); })
690 EXPECT_EQ(expected, actual);
692 expected = seq(1, 10) | as<vector>();
695 | map([] (int x) { return 11 - x; })
698 EXPECT_EQ(expected, actual);
702 int expected = 2 * 3 * 4 * 5;
705 | foldl(1, multiply);
706 EXPECT_EQ(expected, actual);
710 int expected = 2 + 3 + 4 + 5;
711 auto actual = seq(2, 5) | reduce(add);
712 EXPECT_EQ(expected, actual | unwrap);
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'
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);
731 auto gen = seq(0) | filter([](int x) { return x > 3; });
732 EXPECT_EQ(4, gen | first | unwrap);
735 TEST(Gen, FromCopy) {
736 vector<int> v {3, 5};
738 auto copy = fromCopy(v);
739 EXPECT_EQ(8, src | sum);
740 EXPECT_EQ(8, copy | sum);
742 EXPECT_EQ(10, src | sum);
743 EXPECT_EQ(8, copy | sum);
747 std::map<int, int> pairs {
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);
760 EXPECT_EQ(15, keys | sum);
761 EXPECT_EQ(55, values | sum);
763 vector<tuple<int, int, int>> tuples {
766 make_tuple(3, 9, 27),
768 EXPECT_EQ(36, from(tuples) | get<2>() | sum);
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);
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);
786 EXPECT_TRUE(seq(0, 10) | any([](int i) { return i == 7; }));
787 EXPECT_FALSE(seq(0, 10) | any([](int i) { return i == 11; }));
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; }));
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; }));
800 TEST(Gen, Yielders) {
801 auto gen = GENERATOR(int) {
802 for (int i = 1; i <= 5; ++i) {
806 for (int i = 3; ; ++i) {
810 vector<int> expected {
811 1, 2, 3, 4, 5, 7, 9, 16, 25
813 EXPECT_EQ(expected, gen | take(9) | as<vector>());
816 TEST(Gen, NestedYield) {
817 auto nums = GENERATOR(int) {
818 for (int i = 1; ; ++i) {
822 auto gen = GENERATOR(int) {
823 nums | take(10) | yield;
824 seq(1, 5) | [&](int i) {
828 EXPECT_EQ(70, gen | sum);
831 TEST(Gen, MapYielders) {
834 return GENERATOR(int) {
836 for (i = 1; i < n; ++i)
843 vector<int> expected {
848 1, 2, 3, 4, 5, 4, 3, 2, 1,
850 EXPECT_EQ(expected, gen | as<vector>());
853 TEST(Gen, VirtualGen) {
854 VirtualGen<int> v(seq(1, 10));
855 EXPECT_EQ(55, v | sum);
857 EXPECT_EQ(385, v | sum);
859 EXPECT_EQ(55, v | sum);
860 EXPECT_EQ(30, v | take(4) | sum);
864 TEST(Gen, CustomType) {
868 auto gen = from({Foo{2}, Foo{3}})
869 | map([](const Foo& f) { return f.y; });
870 EXPECT_EQ(5, gen | sum);
873 TEST(Gen, NoNeedlessCopies) {
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);
885 class TestIntSeq : public GenImpl<int, TestIntSeq> {
889 template <class Body>
890 bool apply(Body&& body) const {
891 for (int i = 1; i < 6; ++i) {
899 TestIntSeq(TestIntSeq&&) noexcept = default;
900 TestIntSeq& operator=(TestIntSeq&&) noexcept = default;
901 TestIntSeq(const TestIntSeq&) = delete;
902 TestIntSeq& operator=(const TestIntSeq&) = delete;
907 TEST(Gen, NoGeneratorCopies) {
908 EXPECT_EQ(15, TestIntSeq() | sum);
909 auto x = TestIntSeq() | take(3);
910 EXPECT_EQ(6, std::move(x) | sum);
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);
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);
925 TEST(Gen, StringConcat) {
926 auto gen = seq(1, 10)
929 EXPECT_EQ("12345678910", gen | as<string>());
937 CopyCounter() : copies(0), moves(0) {
941 CopyCounter(CopyCounter&& source) noexcept {
942 *this = std::move(source);
946 CopyCounter(const CopyCounter& source) {
955 CopyCounter& operator=(const CopyCounter& source) {
956 this->copies = source.copies + 1;
957 this->moves = source.moves;
961 CopyCounter& operator=(CopyCounter&& source) {
962 this->copies = source.copies;
963 this->moves = source.moves + 1;
968 int CopyCounter::alive = 0;
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);
976 vector<CopyCounter> copies = from(originals) | as<vector>();
977 EXPECT_EQ(1, copies.back().copies);
978 EXPECT_EQ(0, copies.back().moves);
980 vector<CopyCounter> moves = from(originals) | move | as<vector>();
981 EXPECT_EQ(0, moves.back().copies);
982 EXPECT_EQ(1, moves.back().moves);
985 // test dynamics with various layers of nested arrays.
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);
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);
1003 TEST(Gen, Collect) {
1004 auto s = from({7, 6, 5, 4, 3}) | as<set<int>>();
1005 EXPECT_EQ(s.size(), 5);
1011 auto s = from({1, 2});
1012 EXPECT_EQ((vector<int> { 1, 2, 1, 2, 1 }),
1013 s | cycle | take(5) | as<vector>());
1016 auto s = from({1, 2});
1017 EXPECT_EQ((vector<int> { 1, 2, 1, 2 }),
1018 s | cycle(2) | as<vector>());
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>());
1026 auto s = empty<int>();
1027 EXPECT_EQ((vector<int> { }),
1028 s | cycle | take(4) | as<vector>());
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) {
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
1048 TEST(Gen, Dereference) {
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);
1055 vector<int> a { 1, 2 };
1056 vector<int> b { 3, 4 };
1057 vector<vector<int>*> pv { &a, nullptr, &b };
1060 | [&](vector<int>& v) {
1063 EXPECT_EQ(3, a.size());
1064 EXPECT_EQ(3, b.size());
1065 EXPECT_EQ(5, a.back());
1066 EXPECT_EQ(5, b.back());
1069 vector<std::map<int, int>> maps {
1086 | map([](std::map<int, int>& m) {
1087 return get_ptr(m, 3);
1093 vector<unique_ptr<int>> ups;
1094 ups.emplace_back(new int(3));
1096 ups.emplace_back(new int(7));
1097 EXPECT_EQ(10, from(ups) | dereference | sum);
1098 EXPECT_EQ(10, from(ups) | move | dereference | sum);
1102 TEST(Gen, Indirect) {
1104 EXPECT_EQ(&vs[0], from(vs) | indirect | first | unwrap);
1108 using std::runtime_error;
1109 EXPECT_THROW(from({"1", "a", "3"})
1114 from({"1", "a", "3"})
1115 | guard<runtime_error>([](runtime_error&, const char*) {
1116 return true; // continue
1121 from({"1", "a", "3"})
1122 | guard<runtime_error>([](runtime_error&, const char*) {
1123 return false; // break
1127 EXPECT_THROW(from({"1", "a", "3"})
1128 | guard<runtime_error>([](runtime_error&, const char* v) {
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);
1148 TEST(Gen, BatchMove) {
1149 auto expected = vector<vector<int>>{ {0, 1}, {2, 3}, {4} };
1152 | mapped([](int i) { return std::unique_ptr<int>(new int(i)); })
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);
1162 EXPECT_EQ(expected, actual);
1169 EXPECT_EQ(&x, j | indirect | first | unwrap);
1171 EXPECT_EQ(4, j | sum);
1177 EXPECT_EQ(&x, j | indirect | first | unwrap);
1179 EXPECT_EQ(5, j | sum);
1183 auto j = just(std::move(x));
1184 EXPECT_NE(&x, j | indirect | first | unwrap);
1186 EXPECT_EQ(3, j | sum);
1190 TEST(Gen, GroupBy) {
1191 vector<string> strs{"zero", "one", "two", "three", "four",
1192 "five", "six", "seven", "eight", "nine"};
1194 auto gb = from(strs) | groupBy([](const string& str) { return str.size(); });
1196 EXPECT_EQ(10, gb | mapOp(count) | sum);
1197 EXPECT_EQ(3, gb | count);
1199 vector<string> mode{"zero", "four", "five", "nine"};
1201 gb | maxBy([](const Group<size_t, string>& g) { return g.size(); })
1205 vector<string> largest{"three", "seven", "eight"};
1207 gb | maxBy([](const Group<size_t, string>& g) { return g.key(); })
1215 EXPECT_EQ(4, o | unwrap);
1216 EXPECT_THROW(e | unwrap, OptionalEmptyException);
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
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
1228 EXPECT_TRUE(oup.hasValue());
1229 EXPECT_FALSE(oup.value());
1230 EXPECT_TRUE(moved1);
1231 EXPECT_EQ(5, *moved1);
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);
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);
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));
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);
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
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
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!
1296 // test with nullptr
1297 vector<int> v{1, 2};
1298 EXPECT_EQ(&v[1], from(v) | indirect | max | unwrap);
1300 EXPECT_FALSE(from(v) | indirect | max | unwrapOr(nullptr));
1304 // mixed type determined by fallback
1305 Optional<std::nullptr_t> empty;
1307 EXPECT_EQ(&x, empty | unwrapOr(&x));
1311 int main(int argc, char *argv[]) {
1312 testing::InitGoogleTest(&argc, argv);
1313 gflags::ParseCommandLineFlags(&argc, &argv, true);
1314 return RUN_ALL_TESTS();