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_GEN_BASE_H
18 #error This file may only be included from folly/gen/Base.h
21 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
22 #pragma GCC diagnostic push
23 #pragma GCC diagnostic ignored "-Wshadow"
25 namespace folly { namespace gen {
28 * ArgumentReference - For determining ideal argument type to receive a value.
31 struct ArgumentReference
32 : public std::conditional<
33 std::is_reference<T>::value,
34 T, // T& -> T&, T&& -> T&&, const T& -> const T&
35 typename std::conditional<std::is_const<T>::value,
36 T&, // const int -> const int&
43 * ReferencedSource - Generate values from an STL-like container using
44 * iterators from .begin() until .end(). Value type defaults to the type of
45 * *container->begin(). For std::vector<int>, this would be int&. Note that the
46 * value here is a reference, so the values in the vector will be passed by
47 * reference to downstream operators.
49 * This type is primarily used through the 'from' helper method, like:
51 * string& longestName = from(names)
52 * | maxBy([](string& s) { return s.size() });
54 template<class Container,
56 class ReferencedSource :
57 public GenImpl<Value, ReferencedSource<Container, Value>> {
58 Container* container_;
60 explicit ReferencedSource(Container* container)
61 : container_(container) {}
64 void foreach(Body&& body) const {
65 for (auto& value : *container_) {
66 body(std::forward<Value>(value));
70 template<class Handler>
71 bool apply(Handler&& handler) const {
72 for (auto& value : *container_) {
73 if (!handler(std::forward<Value>(value))) {
82 * CopiedSource - For producing values from eagerly from a sequence of values
83 * whose storage is owned by this class. Useful for preparing a generator for
84 * use after a source collection will no longer be available, or for when the
85 * values are specified literally with an initializer list.
87 * This type is primarily used through the 'fromCopy' function, like:
89 * auto sourceCopy = fromCopy(makeAVector());
90 * auto sum = sourceCopy | sum;
91 * auto max = sourceCopy | max;
93 * Though it is also used for the initializer_list specialization of from().
95 template<class StorageType,
98 public GenImpl<const StorageType&,
99 CopiedSource<StorageType, Container>> {
101 !std::is_reference<StorageType>::value, "StorageType must be decayed");
103 // Generator objects are often copied during normal construction as they are
104 // encapsulated by downstream generators. It would be bad if this caused
105 // a copy of the entire container each time, and since we're only exposing a
106 // const reference to the value, it's safe to share it between multiple
109 !std::is_reference<Container>::value,
110 "Can't copy into a reference");
111 std::shared_ptr<const Container> copy_;
113 typedef Container ContainerType;
115 template<class SourceContainer>
116 explicit CopiedSource(const SourceContainer& container)
117 : copy_(new Container(begin(container), end(container))) {}
119 explicit CopiedSource(Container&& container) :
120 copy_(new Container(std::move(container))) {}
122 // To enable re-use of cached results.
123 CopiedSource(const CopiedSource<StorageType, Container>& source)
124 : copy_(source.copy_) {}
127 void foreach(Body&& body) const {
128 for (const auto& value : *copy_) {
133 template<class Handler>
134 bool apply(Handler&& handler) const {
135 // The collection may be reused by others, we can't allow it to be changed.
136 for (const auto& value : *copy_) {
137 if (!handler(value)) {
146 * RangeSource - For producing values from a folly::Range. Useful for referring
147 * to a slice of some container.
149 * This type is primarily used through the 'from' function, like:
151 * auto rangeSource = from(folly::range(v.begin(), v.end()));
152 * auto sum = rangeSource | sum;
154 * Reminder: Be careful not to invalidate iterators when using ranges like this.
156 template<class Iterator>
157 class RangeSource : public GenImpl<typename Range<Iterator>::reference,
158 RangeSource<Iterator>> {
159 Range<Iterator> range_;
162 explicit RangeSource(Range<Iterator> range)
163 : range_(std::move(range))
166 template<class Handler>
167 bool apply(Handler&& handler) const {
168 for (auto& value : range_) {
169 if (!handler(value)) {
177 void foreach(Body&& body) const {
178 for (auto& value : range_) {
185 * Sequence - For generating values from beginning value, incremented along the
186 * way with the ++ and += operators. Iteration may continue indefinitely.
187 * Value type specified explicitly.
189 * This type is primarily used through the 'seq' and 'range' function, like:
191 * int total = seq(1, 10) | sum;
192 * auto indexes = range(0, 10);
193 * auto endless = seq(0); // 0, 1, 2, 3, ...
195 template<class Value, class SequenceImpl>
196 class Sequence : public GenImpl<const Value&, Sequence<Value, SequenceImpl>> {
197 static_assert(!std::is_reference<Value>::value &&
198 !std::is_const<Value>::value, "Value mustn't be const or ref.");
202 explicit Sequence(Value start, SequenceImpl impl)
203 : start_(std::move(start)), impl_(std::move(impl)) { }
205 template<class Handler>
206 bool apply(Handler&& handler) const {
207 for (Value current = start_; impl_.test(current); impl_.step(current)) {
208 if (!handler(current)) {
216 void foreach(Body&& body) const {
217 for (Value current = start_; impl_.test(current); impl_.step(current)) {
224 * Sequence implementations (range, sequence, infinite, with/without step)
226 template<class Value>
230 explicit RangeImpl(Value end) : end_(std::move(end)) { }
231 bool test(const Value& current) const { return current < end_; }
232 void step(Value& current) const { ++current; }
235 template<class Value, class Distance>
236 class RangeWithStepImpl {
240 explicit RangeWithStepImpl(Value end, Distance step)
241 : end_(std::move(end)), step_(std::move(step)) { }
242 bool test(const Value& current) const { return current < end_; }
243 void step(Value& current) const { current += step_; }
246 template<class Value>
250 explicit SeqImpl(Value end) : end_(std::move(end)) { }
251 bool test(const Value& current) const { return current <= end_; }
252 void step(Value& current) const { ++current; }
255 template<class Value, class Distance>
256 class SeqWithStepImpl {
260 explicit SeqWithStepImpl(Value end, Distance step)
261 : end_(std::move(end)), step_(std::move(step)) { }
262 bool test(const Value& current) const { return current <= end_; }
263 void step(Value& current) const { current += step_; }
266 template<class Value>
269 bool test(const Value& current) const { return true; }
270 void step(Value& current) const { ++current; }
274 * GenratorBuilder - Helper for GENERTATOR macro.
276 template<class Value>
277 struct GeneratorBuilder {
278 template<class Source,
279 class Yield = detail::Yield<Value, Source>>
280 Yield operator+(Source&& source) {
281 return Yield(std::forward<Source>(source));
286 * Yield - For producing values from a user-defined generator by way of a
289 template<class Value, class Source>
290 class Yield : public GenImpl<Value, Yield<Value, Source>> {
293 explicit Yield(Source source)
294 : source_(std::move(source)) {
297 template<class Handler>
298 bool apply(Handler&& handler) const {
300 auto body = [&](Value value) {
301 if (!handler(std::forward<Value>(value))) {
314 void foreach(Body&& body) const {
315 source_(std::forward<Body>(body));
319 template<class Value>
320 class Empty : public GenImpl<Value, Empty<Value>> {
322 template <class Handler>
323 bool apply(Handler&&) const {
327 template <class Body>
328 void foreach(Body&&) const {}
331 template<class Value>
332 class Just : public GenImpl<const Value&, Just<Value>> {
333 static_assert(!std::is_reference<Value>::value,
334 "Just requires non-ref types");
337 Just(Value value) : value_(std::forward<Value>(value)) {}
339 template <class Handler>
340 bool apply(Handler&& handler) const {
341 return handler(value_);
344 template <class Body>
345 void foreach(Body&& body) const {
355 * Map - For producing a sequence of values by passing each value from a source
356 * collection through a predicate.
358 * This type is usually used through the 'map' or 'mapped' helper function:
360 * auto squares = seq(1, 10) | map(square) | asVector;
362 template<class Predicate>
363 class Map : public Operator<Map<Predicate>> {
368 explicit Map(Predicate pred)
369 : pred_(std::move(pred))
372 template<class Value,
374 class Result = typename ArgumentReference<
375 typename std::result_of<Predicate(Value)>::type
378 public GenImpl<Result, Generator<Value, Source, Result>> {
382 explicit Generator(Source source, const Predicate& pred)
383 : source_(std::move(source)), pred_(pred) {}
386 void foreach(Body&& body) const {
387 source_.foreach([&](Value value) {
388 body(pred_(std::forward<Value>(value)));
392 template<class Handler>
393 bool apply(Handler&& handler) const {
394 return source_.apply([&](Value value) {
395 return handler(pred_(std::forward<Value>(value)));
399 static constexpr bool infinite = Source::infinite;
402 template<class Source,
404 class Gen = Generator<Value, Source>>
405 Gen compose(GenImpl<Value, Source>&& source) const {
406 return Gen(std::move(source.self()), pred_);
409 template<class Source,
411 class Gen = Generator<Value, Source>>
412 Gen compose(const GenImpl<Value, Source>& source) const {
413 return Gen(source.self(), pred_);
419 * Filter - For filtering values from a source sequence by a predicate.
421 * This type is usually used through the 'filter' helper function, like:
423 * auto nonEmpty = from(strings)
424 * | filter([](const string& str) -> bool {
425 * return !str.empty();
428 template<class Predicate>
429 class Filter : public Operator<Filter<Predicate>> {
433 explicit Filter(Predicate pred)
434 : pred_(std::move(pred))
437 template<class Value,
439 class Generator : public GenImpl<Value, Generator<Value, Source>> {
443 explicit Generator(Source source, const Predicate& pred)
444 : source_(std::move(source)), pred_(pred) {}
447 void foreach(Body&& body) const {
448 source_.foreach([&](Value value) {
449 if (pred_(std::forward<Value>(value))) {
450 body(std::forward<Value>(value));
455 template<class Handler>
456 bool apply(Handler&& handler) const {
457 return source_.apply([&](Value value) -> bool {
458 if (pred_(std::forward<Value>(value))) {
459 return handler(std::forward<Value>(value));
465 static constexpr bool infinite = Source::infinite;
468 template<class Source,
470 class Gen = Generator<Value, Source>>
471 Gen compose(GenImpl<Value, Source>&& source) const {
472 return Gen(std::move(source.self()), pred_);
475 template<class Source,
477 class Gen = Generator<Value, Source>>
478 Gen compose(const GenImpl<Value, Source>& source) const {
479 return Gen(source.self(), pred_);
484 * Until - For producing values from a source until a predicate is satisfied.
486 * This type is usually used through the 'until' helper function, like:
488 * auto best = from(sortedItems)
489 * | until([](Item& item) { return item.score > 100; })
492 template<class Predicate>
493 class Until : public Operator<Until<Predicate>> {
497 explicit Until(Predicate pred)
498 : pred_(std::move(pred))
501 template<class Value,
503 class Generator : public GenImpl<Value, Generator<Value, Source>> {
507 explicit Generator(Source source, const Predicate& pred)
508 : source_(std::move(source)), pred_(pred) {}
510 template<class Handler>
511 bool apply(Handler&& handler) const {
512 bool cancelled = false;
513 source_.apply([&](Value value) -> bool {
514 if (pred_(value)) { // un-forwarded to disable move
517 if (!handler(std::forward<Value>(value))) {
527 template<class Source,
529 class Gen = Generator<Value, Source>>
530 Gen compose(GenImpl<Value, Source>&& source) const {
531 return Gen(std::move(source.self()), pred_);
534 template<class Source,
536 class Gen = Generator<Value, Source>>
537 Gen compose(const GenImpl<Value, Source>& source) const {
538 return Gen(source.self(), pred_);
541 // Theoretically an 'until' might stop an infinite
542 static constexpr bool infinite = false;
546 * Take - For producing up to N values from a source.
548 * This type is usually used through the 'take' helper function, like:
550 * auto best = from(docs)
551 * | orderByDescending(scoreDoc)
554 class Take : public Operator<Take> {
557 explicit Take(size_t count)
560 template<class Value,
563 public GenImpl<Value, Generator<Value, Source>> {
567 explicit Generator(Source source, size_t count)
568 : source_(std::move(source)) , count_(count) {}
570 template<class Handler>
571 bool apply(Handler&& handler) const {
572 if (count_ == 0) { return false; }
574 bool cancelled = false;
575 source_.apply([&](Value value) -> bool {
576 if (!handler(std::forward<Value>(value))) {
586 template<class Source,
588 class Gen = Generator<Value, Source>>
589 Gen compose(GenImpl<Value, Source>&& source) const {
590 return Gen(std::move(source.self()), count_);
593 template<class Source,
595 class Gen = Generator<Value, Source>>
596 Gen compose(const GenImpl<Value, Source>& source) const {
597 return Gen(source.self(), count_);
602 * Sample - For taking a random sample of N elements from a sequence
603 * (without replacement).
605 template<class Random>
606 class Sample : public Operator<Sample<Random>> {
610 explicit Sample(size_t count, Random rng)
611 : count_(count), rng_(std::move(rng)) {}
613 template<class Value,
616 class StorageType = typename std::decay<Value>::type>
618 public GenImpl<StorageType&&,
619 Generator<Value, Source, Rand, StorageType>> {
620 static_assert(!Source::infinite, "Cannot sample infinite source!");
621 // It's too easy to bite ourselves if random generator is only 16-bit
622 static_assert(Random::max() >= std::numeric_limits<int32_t>::max() - 1,
623 "Random number generator must support big values");
628 explicit Generator(Source source, size_t count, Random rng)
629 : source_(std::move(source)) , count_(count), rng_(std::move(rng)) {}
631 template<class Handler>
632 bool apply(Handler&& handler) const {
633 if (count_ == 0) { return false; }
634 std::vector<StorageType> v;
636 // use reservoir sampling to give each source value an equal chance
637 // of appearing in our output.
639 source_.foreach([&](Value value) -> void {
640 if (v.size() < count_) {
641 v.push_back(std::forward<Value>(value));
643 // alternatively, we could create a std::uniform_int_distribution
644 // instead of using modulus, but benchmarks show this has
645 // substantial overhead.
646 size_t index = rng_() % n;
647 if (index < v.size()) {
648 v[index] = std::forward<Value>(value);
654 // output is unsorted!
656 if (!handler(std::move(val))) {
664 template<class Source,
666 class Gen = Generator<Value, Source, Random>>
667 Gen compose(GenImpl<Value, Source>&& source) const {
668 return Gen(std::move(source.self()), count_, rng_);
671 template<class Source,
673 class Gen = Generator<Value, Source, Random>>
674 Gen compose(const GenImpl<Value, Source>& source) const {
675 return Gen(source.self(), count_, rng_);
680 * Skip - For skipping N items from the beginning of a source generator.
682 * This type is usually used through the 'skip' helper function, like:
684 * auto page = from(results)
685 * | skip(pageSize * startPage)
688 class Skip : public Operator<Skip> {
691 explicit Skip(size_t count)
694 template<class Value,
697 public GenImpl<Value, Generator<Value, Source>> {
701 explicit Generator(Source source, size_t count)
702 : source_(std::move(source)) , count_(count) {}
705 void foreach(Body&& body) const {
707 source_.foreach(body);
711 source_.foreach([&](Value value) {
715 body(std::forward<Value>(value));
720 template<class Handler>
721 bool apply(Handler&& handler) const {
723 return source_.apply(std::forward<Handler>(handler));
726 return source_.apply([&](Value value) -> bool {
731 return handler(std::forward<Value>(value));
735 static constexpr bool infinite = Source::infinite;
738 template<class Source,
740 class Gen = Generator<Value, Source>>
741 Gen compose(GenImpl<Value, Source>&& source) const {
742 return Gen(std::move(source.self()), count_);
745 template<class Source,
747 class Gen = Generator<Value, Source>>
748 Gen compose(const GenImpl<Value, Source>& source) const {
749 return Gen(source.self(), count_);
754 * Order - For ordering a sequence of values from a source by key.
755 * The key is extracted by the given selector functor, and this key is then
756 * compared using the specified comparator.
758 * This type is usually used through the 'order' helper function, like:
760 * auto closest = from(places)
761 * | orderBy([](Place& p) {
762 * return -distance(p.location, here);
766 template<class Selector, class Comparer>
767 class Order : public Operator<Order<Selector, Comparer>> {
773 explicit Order(Selector selector)
774 : selector_(std::move(selector))
777 Order(Selector selector,
779 : selector_(std::move(selector))
780 , comparer_(std::move(comparer))
783 template<class Value,
785 class StorageType = typename std::decay<Value>::type,
786 class Result = typename std::result_of<Selector(Value)>::type>
788 public GenImpl<StorageType&&,
789 Generator<Value, Source, StorageType, Result>> {
790 static_assert(!Source::infinite, "Cannot sort infinite source!");
795 typedef std::vector<StorageType> VectorType;
797 VectorType asVector() const {
798 auto comparer = [&](const StorageType& a, const StorageType& b) {
799 return comparer_(selector_(a), selector_(b));
801 auto vals = source_ | as<VectorType>();
802 std::sort(vals.begin(), vals.end(), comparer);
803 return std::move(vals);
806 Generator(Source source,
809 : source_(std::move(source)),
810 selector_(std::move(selector)),
811 comparer_(std::move(comparer)) {}
813 VectorType operator|(const Collect<VectorType>&) const {
817 VectorType operator|(const CollectTemplate<std::vector>&) const {
822 void foreach(Body&& body) const {
823 for (auto& value : asVector()) {
824 body(std::move(value));
828 template<class Handler>
829 bool apply(Handler&& handler) const {
830 auto comparer = [&](const StorageType& a, const StorageType& b) {
831 // swapped for minHeap
832 return comparer_(selector_(b), selector_(a));
834 auto heap = source_ | as<VectorType>();
835 std::make_heap(heap.begin(), heap.end(), comparer);
836 while (!heap.empty()) {
837 std::pop_heap(heap.begin(), heap.end(), comparer);
838 if (!handler(std::move(heap.back()))) {
847 template<class Source,
849 class Gen = Generator<Value, Source>>
850 Gen compose(GenImpl<Value, Source>&& source) const {
851 return Gen(std::move(source.self()), selector_, comparer_);
854 template<class Source,
856 class Gen = Generator<Value, Source>>
857 Gen compose(const GenImpl<Value, Source>& source) const {
858 return Gen(source.self(), selector_, comparer_);
863 * TypeAssertion - For verifying the exact type of the value produced by a
864 * generator. Useful for testing and debugging, and acts as a no-op at runtime.
865 * Pass-through at runtime. Used through the 'assert_type<>()' factory method
868 * auto c = from(vector) | assert_type<int&>() | sum;
871 template<class Expected>
872 class TypeAssertion : public Operator<TypeAssertion<Expected>> {
874 template<class Source, class Value>
875 const Source& compose(const GenImpl<Value, Source>& source) const {
876 static_assert(std::is_same<Expected, Value>::value,
877 "assert_type() check failed");
878 return source.self();
881 template<class Source, class Value>
882 Source&& compose(GenImpl<Value, Source>&& source) const {
883 static_assert(std::is_same<Expected, Value>::value,
884 "assert_type() check failed");
885 return std::move(source.self());
890 * Distinct - For filtering duplicates out of a sequence. A selector may be
891 * provided to generate a key to uniquify for each value.
893 * This type is usually used through the 'distinct' helper function, like:
895 * auto closest = from(results)
896 * | distinctBy([](Item& i) {
901 template<class Selector>
902 class Distinct : public Operator<Distinct<Selector>> {
907 explicit Distinct(Selector selector)
908 : selector_(std::move(selector))
911 template<class Value,
913 class Generator : public GenImpl<Value, Generator<Value, Source>> {
917 typedef typename std::decay<Value>::type StorageType;
919 // selector_ cannot be passed an rvalue or it would end up passing the husk
920 // of a value to the downstream operators.
921 typedef const StorageType& ParamType;
923 typedef typename std::result_of<Selector(ParamType)>::type KeyType;
924 typedef typename std::decay<KeyType>::type KeyStorageType;
927 Generator(Source source,
929 : source_(std::move(source)),
930 selector_(std::move(selector)) {}
933 void foreach(Body&& body) const {
934 std::unordered_set<KeyStorageType> keysSeen;
935 source_.foreach([&](Value value) {
936 if (keysSeen.insert(selector_(ParamType(value))).second) {
937 body(std::forward<Value>(value));
942 template<class Handler>
943 bool apply(Handler&& handler) const {
944 std::unordered_set<KeyStorageType> keysSeen;
945 return source_.apply([&](Value value) -> bool {
946 if (keysSeen.insert(selector_(ParamType(value))).second) {
947 return handler(std::forward<Value>(value));
954 template<class Source,
956 class Gen = Generator<Value, Source>>
957 Gen compose(GenImpl<Value, Source>&& source) const {
958 return Gen(std::move(source.self()), selector_);
961 template<class Source,
963 class Gen = Generator<Value, Source>>
964 Gen compose(const GenImpl<Value, Source>& source) const {
965 return Gen(source.self(), selector_);
970 * Composer - Helper class for adapting pipelines into functors. Primarily used
973 template<class Operators>
977 explicit Composer(Operators op)
978 : op_(std::move(op)) {}
980 template<class Source,
981 class Ret = decltype(std::declval<Operators>()
982 .compose(std::declval<Source>()))>
983 Ret operator()(Source&& source) const {
984 return op_.compose(std::forward<Source>(source));
989 * Batch - For producing fixed-size batches of each value from a source.
991 * This type is usually used through the 'batch' helper function:
996 * | map([](const std::vector<int>& batch) {
997 * return from(batch) | sum;
1001 class Batch : public Operator<Batch> {
1004 explicit Batch(size_t batchSize)
1005 : batchSize_(batchSize) {
1006 if (batchSize_ == 0) {
1007 throw std::invalid_argument("Batch size must be non-zero!");
1011 template<class Value,
1013 class StorageType = typename std::decay<Value>::type,
1014 class VectorType = std::vector<StorageType>>
1016 public GenImpl<VectorType&,
1017 Generator<Value, Source, StorageType, VectorType>> {
1021 explicit Generator(Source source, size_t batchSize)
1022 : source_(std::move(source))
1023 , batchSize_(batchSize) {}
1025 template<class Handler>
1026 bool apply(Handler&& handler) const {
1028 batch_.reserve(batchSize_);
1029 bool shouldContinue = source_.apply([&](Value value) -> bool {
1030 batch_.push_back(std::forward<Value>(value));
1031 if (batch_.size() == batchSize_) {
1032 bool needMore = handler(batch_);
1036 // Always need more if the handler is not called.
1039 // Flush everything, if and only if `handler` hasn't returned false.
1040 if (shouldContinue && !batch_.empty()) {
1041 shouldContinue = handler(batch_);
1044 return shouldContinue;
1047 static constexpr bool infinite = Source::infinite;
1050 template<class Source,
1052 class Gen = Generator<Value, Source>>
1053 Gen compose(GenImpl<Value, Source>&& source) const {
1054 return Gen(std::move(source.self()), batchSize_);
1057 template<class Source,
1059 class Gen = Generator<Value, Source>>
1060 Gen compose(const GenImpl<Value, Source>& source) const {
1061 return Gen(source.self(), batchSize_);
1069 * FoldLeft - Left-associative functional fold. For producing an aggregate value
1070 * from a seed and a folder function. Useful for custom aggregators on a
1073 * This type is primarily used through the 'foldl' helper method, like:
1075 * double movingAverage = from(values)
1076 * | foldl(0.0, [](double avg, double sample) {
1077 * return sample * 0.1 + avg * 0.9;
1080 template<class Seed,
1082 class FoldLeft : public Operator<FoldLeft<Seed, Fold>> {
1089 : seed_(std::move(seed))
1090 , fold_(std::move(fold))
1093 template<class Source,
1095 Seed compose(const GenImpl<Value, Source>& source) const {
1096 static_assert(!Source::infinite, "Cannot foldl infinite source");
1098 source | [&](Value v) {
1099 accum = fold_(std::move(accum), std::forward<Value>(v));
1106 * First - For finding the first value in a sequence.
1108 * This type is primarily used through the 'first' static value, like:
1110 * int firstThreeDigitPrime = seq(100) | filter(isPrime) | first;
1112 class First : public Operator<First> {
1116 template<class Source,
1118 class StorageType = typename std::decay<Value>::type>
1119 StorageType compose(const GenImpl<Value, Source>& source) const {
1120 Optional<StorageType> accum;
1121 source | [&](Value v) -> bool {
1122 accum = std::forward<Value>(v);
1125 if (!accum.hasValue()) {
1126 throw EmptySequence();
1128 return std::move(accum.value());
1134 * Any - For determining whether any values in a sequence satisfy a predicate.
1136 * This type is primarily used through the 'any' static value, like:
1138 * bool any20xPrimes = seq(200, 210) | filter(isPrime) | any;
1140 * Note that it may also be used like so:
1142 * bool any20xPrimes = seq(200, 210) | any(isPrime);
1145 class Any : public Operator<Any> {
1149 template<class Source,
1151 bool compose(const GenImpl<Value, Source>& source) const {
1153 source | [&](Value v) -> bool {
1161 * Convenience function for use like:
1163 * bool found = gen | any([](int i) { return i * i > 100; });
1165 template<class Predicate,
1166 class Filter = Filter<Predicate>,
1167 class Composed = Composed<Filter, Any>>
1168 Composed operator()(Predicate pred) const {
1169 return Composed(Filter(std::move(pred)), Any());
1174 * All - For determining whether all values in a sequence satisfy a predicate.
1176 * This type is primarily used through the 'any' static value, like:
1178 * bool valid = from(input) | all(validate);
1180 * Note: Passing an empty sequence through 'all()' will always return true.
1182 template<class Predicate>
1183 class All : public Operator<All<Predicate>> {
1187 explicit All(Predicate pred)
1188 : pred_(std::move(pred))
1191 template<class Source,
1193 bool compose(const GenImpl<Value, Source>& source) const {
1194 static_assert(!Source::infinite, "Cannot call 'all' on infinite source");
1196 source | [&](Value v) -> bool {
1197 if (!pred_(std::forward<Value>(v))) {
1208 * Reduce - Functional reduce, for recursively combining values from a source
1209 * using a reducer function until there is only one item left. Useful for
1210 * combining values when an empty sequence doesn't make sense.
1212 * This type is primarily used through the 'reduce' helper method, like:
1214 * sring longest = from(names)
1215 * | reduce([](string&& best, string& current) {
1216 * return best.size() >= current.size() ? best : current;
1219 template<class Reducer>
1220 class Reduce : public Operator<Reduce<Reducer>> {
1224 explicit Reduce(Reducer reducer)
1225 : reducer_(std::move(reducer))
1228 template<class Source,
1230 class StorageType = typename std::decay<Value>::type>
1231 StorageType compose(const GenImpl<Value, Source>& source) const {
1232 Optional<StorageType> accum;
1233 source | [&](Value v) {
1234 if (accum.hasValue()) {
1235 accum = reducer_(std::move(accum.value()), std::forward<Value>(v));
1237 accum = std::forward<Value>(v);
1240 if (!accum.hasValue()) {
1241 throw EmptySequence();
1243 return accum.value();
1248 * Count - for simply counting the items in a collection.
1250 * This type is usually used through its singleton, 'count':
1252 * auto shortPrimes = seq(1, 100) | filter(isPrime) | count;
1254 class Count : public Operator<Count> {
1258 template<class Source,
1260 size_t compose(const GenImpl<Value, Source>& source) const {
1261 static_assert(!Source::infinite, "Cannot count infinite source");
1262 return foldl(size_t(0),
1263 [](size_t accum, Value v) {
1270 * Sum - For simply summing up all the values from a source.
1272 * This type is usually used through its singleton, 'sum':
1274 * auto gaussSum = seq(1, 100) | sum;
1276 class Sum : public Operator<Sum> {
1278 Sum() : Operator<Sum>() {}
1280 template<class Source,
1282 class StorageType = typename std::decay<Value>::type>
1283 StorageType compose(const GenImpl<Value, Source>& source) const {
1284 static_assert(!Source::infinite, "Cannot sum infinite source");
1285 return foldl(StorageType(0),
1286 [](StorageType&& accum, Value v) {
1287 return std::move(accum) + std::forward<Value>(v);
1293 * Contains - For testing whether a value matching the given value is contained
1296 * This type should be used through the 'contains' helper method, like:
1298 * bool contained = seq(1, 10) | map(square) | contains(49);
1300 template<class Needle>
1301 class Contains : public Operator<Contains<Needle>> {
1304 explicit Contains(Needle needle)
1305 : needle_(std::move(needle))
1308 template<class Source,
1310 class StorageType = typename std::decay<Value>::type>
1311 bool compose(const GenImpl<Value, Source>& source) const {
1312 static_assert(!Source::infinite,
1313 "Calling contains on an infinite source might cause "
1314 "an infinite loop.");
1315 return !(source | [this](Value value) {
1316 return !(needle_ == std::forward<Value>(value));
1322 * Min - For a value which minimizes a key, where the key is determined by a
1323 * given selector, and compared by given comparer.
1325 * This type is usually used through the singletone 'min' or through the helper
1326 * functions 'minBy' and 'maxBy'.
1328 * auto oldest = from(people)
1329 * | minBy([](Person& p) {
1330 * return p.dateOfBirth;
1333 template<class Selector,
1335 class Min : public Operator<Min<Selector, Comparer>> {
1341 explicit Min(Selector selector)
1342 : selector_(std::move(selector))
1345 Min(Selector selector,
1347 : selector_(std::move(selector))
1348 , comparer_(std::move(comparer))
1351 template<class Value,
1353 class StorageType = typename std::decay<Value>::type,
1354 class Key = typename std::decay<
1355 typename std::result_of<Selector(Value)>::type
1357 StorageType compose(const GenImpl<Value, Source>& source) const {
1358 Optional<StorageType> min;
1359 Optional<Key> minKey;
1360 source | [&](Value v) {
1361 Key key = selector_(std::forward<Value>(v));
1362 if (!minKey.hasValue() || comparer_(key, minKey.value())) {
1364 min = std::forward<Value>(v);
1367 if (!min.hasValue()) {
1368 throw EmptySequence();
1375 * Append - For collecting values from a source into a given output container
1378 * This type is usually used through the helper function 'appendTo', like:
1380 * vector<int64_t> ids;
1381 * from(results) | map([](Person& p) { return p.id })
1384 template<class Collection>
1385 class Append : public Operator<Append<Collection>> {
1386 Collection* collection_;
1388 explicit Append(Collection* collection)
1389 : collection_(collection)
1392 template<class Value,
1394 Collection& compose(const GenImpl<Value, Source>& source) const {
1395 source | [&](Value v) {
1396 collection_->insert(collection_->end(), std::forward<Value>(v));
1398 return *collection_;
1403 * Collect - For collecting values from a source in a collection of the desired
1406 * This type is usually used through the helper function 'as', like:
1408 * std::string upper = from(stringPiece)
1410 * | as<std::string>();
1412 template<class Collection>
1413 class Collect : public Operator<Collect<Collection>> {
1417 template<class Value,
1419 class StorageType = typename std::decay<Value>::type>
1420 Collection compose(const GenImpl<Value, Source>& source) const {
1421 Collection collection;
1422 source | [&](Value v) {
1423 collection.insert(collection.end(), std::forward<Value>(v));
1431 * CollectTemplate - For collecting values from a source in a collection
1432 * constructed using the specified template type. Given the type of values
1433 * produced by the given generator, the collection type will be:
1434 * Container<Value, Allocator<Value>>
1436 * The allocator defaults to std::allocator, so this may be used for the STL
1437 * containers by simply using operators like 'as<set>', 'as<deque>',
1438 * 'as<vector>'. 'as', here is the helper method which is the usual means of
1439 * consturcting this operator.
1443 * set<string> uniqueNames = from(names) | as<set>();
1445 template<template<class, class> class Container,
1446 template<class> class Allocator>
1447 class CollectTemplate : public Operator<CollectTemplate<Container, Allocator>> {
1449 CollectTemplate() { }
1451 template<class Value,
1453 class StorageType = typename std::decay<Value>::type,
1454 class Collection = Container<StorageType, Allocator<StorageType>>>
1455 Collection compose(const GenImpl<Value, Source>& source) const {
1456 Collection collection;
1457 source | [&](Value v) {
1458 collection.insert(collection.end(), std::forward<Value>(v));
1465 * Concat - For flattening generators of generators.
1467 * This type is usually used through the 'concat' static value, like:
1471 * | map([](Node& x) {
1472 * return from(x.neighbors)
1473 * | map([&](Node& y) {
1474 * return Edge(x, y);
1480 class Concat : public Operator<Concat> {
1484 template<class Inner,
1486 class InnerValue = typename std::decay<Inner>::type::ValueType>
1488 public GenImpl<InnerValue, Generator<Inner, Source, InnerValue>> {
1491 explicit Generator(Source source)
1492 : source_(std::move(source)) {}
1494 template<class Handler>
1495 bool apply(Handler&& handler) const {
1496 return source_.apply([&](Inner inner) -> bool {
1497 return inner.apply(std::forward<Handler>(handler));
1501 template<class Body>
1502 void foreach(Body&& body) const {
1503 source_.foreach([&](Inner inner) {
1504 inner.foreach(std::forward<Body>(body));
1508 static constexpr bool infinite = Source::infinite;
1511 template<class Value,
1513 class Gen = Generator<Value, Source>>
1514 Gen compose(GenImpl<Value, Source>&& source) const {
1515 return Gen(std::move(source.self()));
1518 template<class Value,
1520 class Gen = Generator<Value, Source>>
1521 Gen compose(const GenImpl<Value, Source>& source) const {
1522 return Gen(source.self());
1527 * RangeConcat - For flattening generators of iterables.
1529 * This type is usually used through the 'rconcat' static value, like:
1531 * map<int, vector<int>> adjacency;
1538 class RangeConcat : public Operator<RangeConcat> {
1542 template<class Range,
1544 class InnerValue = typename ValueTypeOfRange<Range>::RefType>
1546 : public GenImpl<InnerValue, Generator<Range, Source, InnerValue>> {
1549 explicit Generator(Source source)
1550 : source_(std::move(source)) {}
1552 template<class Body>
1553 void foreach(Body&& body) const {
1554 source_.foreach([&](Range range) {
1555 for (auto& value : range) {
1561 template<class Handler>
1562 bool apply(Handler&& handler) const {
1563 return source_.apply([&](Range range) -> bool {
1564 for (auto& value : range) {
1565 if (!handler(value)) {
1574 template<class Value,
1576 class Gen = Generator<Value, Source>>
1577 Gen compose(GenImpl<Value, Source>&& source) const {
1578 return Gen(std::move(source.self()));
1581 template<class Value,
1583 class Gen = Generator<Value, Source>>
1584 Gen compose(const GenImpl<Value, Source>& source) const {
1585 return Gen(source.self());
1591 * GuardImpl - For handling exceptions from downstream computation. Requires the
1592 * type of exception to catch, and handler function to invoke in the event of
1593 * the exception. Note that the handler may:
1594 * 1) return true to continue processing the sequence
1595 * 2) return false to end the sequence immediately
1596 * 3) throw, to pass the exception to the next catch
1597 * The handler must match the signature 'bool(Exception&, Value)'.
1599 * This type is used through the `guard` helper, like so:
1602 * = byLine(STDIN_FILENO)
1603 * | guard<std::runtime_error>([](std::runtime_error& e,
1605 * LOG(ERROR) << sp << ": " << e.str();
1606 * return true; // continue processing subsequent lines
1611 * TODO(tjackson): Rename this back to Guard.
1613 template<class Exception,
1615 class GuardImpl : public Operator<GuardImpl<Exception, ErrorHandler>> {
1616 ErrorHandler handler_;
1618 GuardImpl(ErrorHandler handler)
1619 : handler_(std::move(handler)) {}
1621 template<class Value,
1623 class Generator : public GenImpl<Value, Generator<Value, Source>> {
1625 ErrorHandler handler_;
1627 explicit Generator(Source source,
1628 ErrorHandler handler)
1629 : source_(std::move(source)),
1630 handler_(std::move(handler)) {}
1632 template<class Handler>
1633 bool apply(Handler&& handler) const {
1634 return source_.apply([&](Value value) -> bool {
1636 handler(std::forward<Value>(value));
1638 } catch (Exception& e) {
1639 return handler_(e, std::forward<Value>(value));
1644 static constexpr bool infinite = Source::infinite;
1647 template<class Value,
1649 class Gen = Generator<Value, Source>>
1650 Gen compose(GenImpl<Value, Source>&& source) const {
1651 return Gen(std::move(source.self()), handler_);
1654 template<class Value,
1656 class Gen = Generator<Value, Source>>
1657 Gen compose(const GenImpl<Value, Source>& source) const {
1658 return Gen(source.self(), handler_);
1663 * Cycle - For repeating a sequence forever.
1665 * This type is usually used through the 'cycle' static value, like:
1672 class Cycle : public Operator<Cycle> {
1673 off_t limit_; // -1 for infinite
1678 explicit Cycle(off_t limit)
1681 template<class Value,
1683 class Generator : public GenImpl<Value, Generator<Value, Source>> {
1685 off_t limit_; // -1 for infinite
1687 explicit Generator(Source source, off_t limit)
1688 : source_(std::move(source))
1691 template<class Handler>
1692 bool apply(Handler&& handler) const {
1694 auto handler2 = [&](Value value) {
1695 cont = handler(std::forward<Value>(value));
1698 for (off_t count = 0; count != limit_; ++count) {
1700 source_.apply(handler2);
1708 // not actually infinite, since an empty generator will end the cycles.
1709 static constexpr bool infinite = Source::infinite;
1712 template<class Source,
1714 class Gen = Generator<Value, Source>>
1715 Gen compose(GenImpl<Value, Source>&& source) const {
1716 return Gen(std::move(source.self()), limit_);
1719 template<class Source,
1721 class Gen = Generator<Value, Source>>
1722 Gen compose(const GenImpl<Value, Source>& source) const {
1723 return Gen(source.self(), limit_);
1727 * Convenience function for use like:
1729 * auto tripled = gen | cycle(3);
1731 Cycle operator()(off_t limit) const {
1732 return Cycle(limit);
1737 * Dereference - For dereferencing a sequence of pointers while filtering out
1740 * This type is usually used through the 'dereference' static value, like:
1742 * auto refs = from(ptrs) | dereference;
1744 class Dereference : public Operator<Dereference> {
1748 template<class Value,
1750 class Result = decltype(*std::declval<Value>())>
1751 class Generator : public GenImpl<Result, Generator<Value, Source, Result>> {
1754 explicit Generator(Source source)
1755 : source_(std::move(source)) {}
1757 template<class Body>
1758 void foreach(Body&& body) const {
1759 source_.foreach([&](Value value) {
1761 return body(*value);
1766 template<class Handler>
1767 bool apply(Handler&& handler) const {
1768 return source_.apply([&](Value value) -> bool {
1770 return handler(*value);
1776 // not actually infinite, since an empty generator will end the cycles.
1777 static constexpr bool infinite = Source::infinite;
1780 template<class Source,
1782 class Gen = Generator<Value, Source>>
1783 Gen compose(GenImpl<Value, Source>&& source) const {
1784 return Gen(std::move(source.self()));
1787 template<class Source,
1789 class Gen = Generator<Value, Source>>
1790 Gen compose(const GenImpl<Value, Source>& source) const {
1791 return Gen(source.self());
1798 * VirtualGen<T> - For wrapping template types in simple polymorphic wrapper.
1800 template<class Value>
1801 class VirtualGen : public GenImpl<Value, VirtualGen<Value>> {
1804 virtual ~WrapperBase() {}
1805 virtual bool apply(const std::function<bool(Value)>& handler) const = 0;
1806 virtual void foreach(const std::function<void(Value)>& body) const = 0;
1807 virtual std::unique_ptr<const WrapperBase> clone() const = 0;
1810 template<class Wrapped>
1811 class WrapperImpl : public WrapperBase {
1814 explicit WrapperImpl(Wrapped wrapped)
1815 : wrapped_(std::move(wrapped)) {
1818 virtual bool apply(const std::function<bool(Value)>& handler) const {
1819 return wrapped_.apply(handler);
1822 virtual void foreach(const std::function<void(Value)>& body) const {
1823 wrapped_.foreach(body);
1826 virtual std::unique_ptr<const WrapperBase> clone() const {
1827 return std::unique_ptr<const WrapperBase>(new WrapperImpl(wrapped_));
1831 std::unique_ptr<const WrapperBase> wrapper_;
1834 template<class Self>
1835 /* implicit */ VirtualGen(Self source)
1836 : wrapper_(new WrapperImpl<Self>(std::move(source)))
1839 VirtualGen(VirtualGen&& source)
1840 : wrapper_(std::move(source.wrapper_))
1843 VirtualGen(const VirtualGen& source)
1844 : wrapper_(source.wrapper_->clone())
1847 VirtualGen& operator=(const VirtualGen& source) {
1848 wrapper_.reset(source.wrapper_->clone());
1852 VirtualGen& operator=(VirtualGen&& source) {
1853 wrapper_= std::move(source.wrapper_);
1857 bool apply(const std::function<bool(Value)>& handler) const {
1858 return wrapper_->apply(handler);
1861 void foreach(const std::function<void(Value)>& body) const {
1862 wrapper_->foreach(body);
1867 * non-template operators, statically defined to avoid the need for anything but
1870 static const detail::Sum sum;
1872 static const detail::Count count;
1874 static const detail::First first;
1877 * Use directly for detecting any values, or as a function to detect values
1878 * which pass a predicate:
1880 * auto nonempty = g | any;
1881 * auto evens = g | any(even);
1883 static const detail::Any any;
1885 static const detail::Min<Identity, Less> min;
1887 static const detail::Min<Identity, Greater> max;
1889 static const detail::Order<Identity> order;
1891 static const detail::Distinct<Identity> distinct;
1893 static const detail::Map<Move> move;
1895 static const detail::Concat concat;
1897 static const detail::RangeConcat rconcat;
1900 * Use directly for infinite sequences, or as a function to limit cycle count.
1902 * auto forever = g | cycle;
1903 * auto thrice = g | cycle(3);
1905 static const detail::Cycle cycle;
1907 static const detail::Dereference dereference;
1909 inline detail::Take take(size_t count) {
1910 return detail::Take(count);
1913 template<class Random = std::default_random_engine>
1914 inline detail::Sample<Random> sample(size_t count, Random rng = Random()) {
1915 return detail::Sample<Random>(count, std::move(rng));
1918 inline detail::Skip skip(size_t count) {
1919 return detail::Skip(count);
1922 inline detail::Batch batch(size_t batchSize) {
1923 return detail::Batch(batchSize);
1928 #pragma GCC diagnostic pop