Apply clang-format to folly/gen/ (partial: namespace)
[folly.git] / folly / gen / Base-inl.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifndef FOLLY_GEN_BASE_H_
18 #error This file may only be included from folly/gen/Base.h
19 #endif
20
21 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
22 #pragma GCC diagnostic push
23 #pragma GCC diagnostic ignored "-Wshadow"
24
25 namespace folly {
26 namespace gen {
27
28 /**
29  * ArgumentReference - For determining ideal argument type to receive a value.
30  */
31 template <class T>
32 struct ArgumentReference
33     : public std::conditional<
34           std::is_reference<T>::value,
35           T, // T& -> T&, T&& -> T&&, const T& -> const T&
36           typename std::conditional<std::is_const<T>::value,
37                                     T&, // const int -> const int&
38                                     T&& // int -> int&&
39                                     >::type> {};
40
41 /**
42  * Group - The output objects from the GroupBy operator
43  */
44 template <class Key, class Value>
45 class Group : public GenImpl<Value&&, Group<Key, Value>> {
46  public:
47   static_assert(!std::is_reference<Key>::value &&
48                     !std::is_reference<Value>::value,
49                 "Key and Value must be decayed types");
50
51   typedef std::vector<Value> VectorType;
52   typedef Key KeyType;
53   typedef Value ValueType;
54
55   Group(Key key, VectorType values)
56       : key_(std::move(key)), values_(std::move(values)) {}
57
58   const Key& key() const { return key_; }
59
60   size_t size() const { return values_.size(); }
61   const VectorType& values() const { return values_; }
62   VectorType& values() { return values_; }
63
64   VectorType operator|(const detail::Collect<VectorType>&) const {
65     return values();
66   }
67
68   VectorType operator|(const detail::CollectTemplate<std::vector>&) const {
69     return values();
70   }
71
72   template <class Body>
73   void foreach(Body&& body) const {
74     for (auto& value : values_) {
75       body(std::move(value));
76     }
77   }
78
79   template <class Handler>
80   bool apply(Handler&& handler) const {
81     for (auto& value : values_) {
82       if (!handler(std::move(value))) {
83         return false;
84       }
85     }
86     return true;
87   }
88
89   // GroupBy only takes in finite generators, so we only have finite groups
90   static constexpr bool infinite = false;
91
92  private:
93   Key key_;
94   mutable VectorType values_;
95 };
96
97 namespace detail {
98
99 // Classes used for the implementation of Sources, Operators, and Sinks
100
101 /*
102  ******************************* Sources ***************************************
103  */
104
105 /*
106  * ReferencedSource - Generate values from an STL-like container using
107  * iterators from .begin() until .end(). Value type defaults to the type of
108  * *container->begin(). For std::vector<int>, this would be int&. Note that the
109  * value here is a reference, so the values in the vector will be passed by
110  * reference to downstream operators.
111  *
112  * This type is primarily used through the 'from' helper method, like:
113  *
114  *   string& longestName = from(names)
115  *                       | maxBy([](string& s) { return s.size() });
116  */
117 template <class Container, class Value>
118 class ReferencedSource
119     : public GenImpl<Value, ReferencedSource<Container, Value>> {
120   Container* container_;
121
122  public:
123   explicit ReferencedSource(Container* container) : container_(container) {}
124
125   template <class Body>
126   void foreach(Body&& body) const {
127     for (auto& value : *container_) {
128       body(std::forward<Value>(value));
129     }
130   }
131
132   template <class Handler>
133   bool apply(Handler&& handler) const {
134     for (auto& value : *container_) {
135       if (!handler(std::forward<Value>(value))) {
136         return false;
137       }
138     }
139     return true;
140   }
141
142   // from takes in a normal stl structure, which are all finite
143   static constexpr bool infinite = false;
144 };
145
146 /**
147  * CopiedSource - For producing values from eagerly from a sequence of values
148  * whose storage is owned by this class. Useful for preparing a generator for
149  * use after a source collection will no longer be available, or for when the
150  * values are specified literally with an initializer list.
151  *
152  * This type is primarily used through the 'fromCopy' function, like:
153  *
154  *   auto sourceCopy = fromCopy(makeAVector());
155  *   auto sum = sourceCopy | sum;
156  *   auto max = sourceCopy | max;
157  *
158  * Though it is also used for the initializer_list specialization of from().
159  */
160 template <class StorageType, class Container>
161 class CopiedSource
162     : public GenImpl<const StorageType&, CopiedSource<StorageType, Container>> {
163   static_assert(!std::is_reference<StorageType>::value,
164                 "StorageType must be decayed");
165
166  public:
167   // Generator objects are often copied during normal construction as they are
168   // encapsulated by downstream generators. It would be bad if this caused
169   // a copy of the entire container each time, and since we're only exposing a
170   // const reference to the value, it's safe to share it between multiple
171   // generators.
172   static_assert(!std::is_reference<Container>::value,
173                 "Can't copy into a reference");
174   std::shared_ptr<const Container> copy_;
175
176  public:
177   typedef Container ContainerType;
178
179   template <class SourceContainer>
180   explicit CopiedSource(const SourceContainer& container)
181       : copy_(new Container(begin(container), end(container))) {}
182
183   explicit CopiedSource(Container&& container)
184       : copy_(new Container(std::move(container))) {}
185
186   // To enable re-use of cached results.
187   CopiedSource(const CopiedSource<StorageType, Container>& source)
188       : copy_(source.copy_) {}
189
190   template <class Body>
191   void foreach(Body&& body) const {
192     for (const auto& value : *copy_) {
193       body(value);
194     }
195   }
196
197   template <class Handler>
198   bool apply(Handler&& handler) const {
199     // The collection may be reused by others, we can't allow it to be changed.
200     for (const auto& value : *copy_) {
201       if (!handler(value)) {
202         return false;
203       }
204     }
205     return true;
206   }
207
208   // from takes in a normal stl structure, which are all finite
209   static constexpr bool infinite = false;
210 };
211
212 /**
213  * RangeSource - For producing values from a folly::Range. Useful for referring
214  * to a slice of some container.
215  *
216  * This type is primarily used through the 'from' function, like:
217  *
218  *   auto rangeSource = from(folly::range(v.begin(), v.end()));
219  *   auto sum = rangeSource | sum;
220  *
221  * Reminder: Be careful not to invalidate iterators when using ranges like this.
222  */
223 template <class Iterator>
224 class RangeSource : public GenImpl<typename Range<Iterator>::reference,
225                                    RangeSource<Iterator>> {
226   Range<Iterator> range_;
227
228  public:
229   RangeSource() = default;
230   explicit RangeSource(Range<Iterator> range) : range_(std::move(range)) {}
231
232   template <class Handler>
233   bool apply(Handler&& handler) const {
234     for (auto& value : range_) {
235       if (!handler(value)) {
236         return false;
237       }
238     }
239     return true;
240   }
241
242   template <class Body>
243   void foreach(Body&& body) const {
244     for (auto& value : range_) {
245       body(value);
246     }
247   }
248
249   // folly::Range only supports finite ranges
250   static constexpr bool infinite = false;
251 };
252
253 /**
254  * Sequence - For generating values from beginning value, incremented along the
255  * way with the ++ and += operators. Iteration may continue indefinitely.
256  * Value type specified explicitly.
257  *
258  * This type is primarily used through the 'seq' and 'range' function, like:
259  *
260  *   int total = seq(1, 10) | sum;
261  *   auto indexes = range(0, 10);
262  *   auto endless = seq(0); // 0, 1, 2, 3, ...
263  */
264 template <class Value, class SequenceImpl>
265 class Sequence : public GenImpl<const Value&, Sequence<Value, SequenceImpl>> {
266   static_assert(!std::is_reference<Value>::value &&
267                     !std::is_const<Value>::value,
268                 "Value mustn't be const or ref.");
269   Value start_;
270   SequenceImpl impl_;
271
272  public:
273   explicit Sequence(Value start, SequenceImpl impl)
274       : start_(std::move(start)), impl_(std::move(impl)) {}
275
276   template <class Handler>
277   bool apply(Handler&& handler) const {
278     for (Value current = start_; impl_.test(current); impl_.step(current)) {
279       if (!handler(current)) {
280         return false;
281       }
282     }
283     return true;
284   }
285
286   template <class Body>
287   void foreach(Body&& body) const {
288     for (Value current = start_; impl_.test(current); impl_.step(current)) {
289       body(current);
290     }
291   }
292
293   // Let the implementation say if we are infinite or not
294   static constexpr bool infinite = SequenceImpl::infinite;
295 };
296
297 /**
298  * Sequence implementations (range, sequence, infinite, with/without step)
299  **/
300 template <class Value>
301 class RangeImpl {
302   Value end_;
303
304  public:
305   explicit RangeImpl(Value end) : end_(std::move(end)) {}
306   bool test(const Value& current) const { return current < end_; }
307   void step(Value& current) const { ++current; }
308   static constexpr bool infinite = false;
309 };
310
311 template <class Value, class Distance>
312 class RangeWithStepImpl {
313   Value end_;
314   Distance step_;
315
316  public:
317   explicit RangeWithStepImpl(Value end, Distance step)
318       : end_(std::move(end)), step_(std::move(step)) {}
319   bool test(const Value& current) const { return current < end_; }
320   void step(Value& current) const { current += step_; }
321   static constexpr bool infinite = false;
322 };
323
324 template <class Value>
325 class SeqImpl {
326   Value end_;
327
328  public:
329   explicit SeqImpl(Value end) : end_(std::move(end)) {}
330   bool test(const Value& current) const { return current <= end_; }
331   void step(Value& current) const { ++current; }
332   static constexpr bool infinite = false;
333 };
334
335 template <class Value, class Distance>
336 class SeqWithStepImpl {
337   Value end_;
338   Distance step_;
339
340  public:
341   explicit SeqWithStepImpl(Value end, Distance step)
342       : end_(std::move(end)), step_(std::move(step)) {}
343   bool test(const Value& current) const { return current <= end_; }
344   void step(Value& current) const { current += step_; }
345   static constexpr bool infinite = false;
346 };
347
348 template <class Value>
349 class InfiniteImpl {
350  public:
351   bool test(const Value& /* current */) const { return true; }
352   void step(Value& current) const { ++current; }
353   static constexpr bool infinite = true;
354 };
355
356 /**
357  * GenratorBuilder - Helper for GENERTATOR macro.
358  **/
359 template <class Value>
360 struct GeneratorBuilder {
361   template <class Source,
362             class Yield = detail::Yield<Value, Source>>
363   Yield operator+(Source&& source) {
364     return Yield(std::forward<Source>(source));
365   }
366 };
367
368 /**
369  * Yield - For producing values from a user-defined generator by way of a
370  * 'yield' function.
371  **/
372 template <class Value, class Source>
373 class Yield : public GenImpl<Value, Yield<Value, Source>> {
374   Source source_;
375
376  public:
377   explicit Yield(Source source) : source_(std::move(source)) {}
378
379   template <class Handler>
380   bool apply(Handler&& handler) const {
381     struct Break {};
382     auto body = [&](Value value) {
383       if (!handler(std::forward<Value>(value))) {
384         throw Break();
385       }
386     };
387     try {
388       source_(body);
389       return true;
390     } catch (Break&) {
391       return false;
392     }
393   }
394
395   template <class Body>
396   void foreach(Body&& body) const {
397     source_(std::forward<Body>(body));
398   }
399 };
400
401 template <class Value>
402 class Empty : public GenImpl<Value, Empty<Value>> {
403  public:
404   template <class Handler>
405   bool apply(Handler&&) const {
406     return true;
407   }
408
409   template <class Body>
410   void foreach(Body&&) const {}
411
412   // No values, so finite
413   static constexpr bool infinite = false;
414 };
415
416 template <class Value>
417 class SingleReference : public GenImpl<Value&, SingleReference<Value>> {
418   static_assert(!std::is_reference<Value>::value,
419                 "SingleReference requires non-ref types");
420   Value* ptr_;
421
422  public:
423   explicit SingleReference(Value& ref) : ptr_(&ref) {}
424
425   template <class Handler>
426   bool apply(Handler&& handler) const {
427     return handler(*ptr_);
428   }
429
430   template <class Body>
431   void foreach(Body&& body) const {
432     body(*ptr_);
433   }
434
435   // One value, so finite
436   static constexpr bool infinite = false;
437 };
438
439 template <class Value>
440 class SingleCopy : public GenImpl<const Value&, SingleCopy<Value>> {
441   static_assert(!std::is_reference<Value>::value,
442                 "SingleCopy requires non-ref types");
443   Value value_;
444
445  public:
446   explicit SingleCopy(Value value) : value_(std::forward<Value>(value)) {}
447
448   template <class Handler>
449   bool apply(Handler&& handler) const {
450     return handler(value_);
451   }
452
453   template <class Body>
454   void foreach(Body&& body) const {
455     body(value_);
456   }
457
458   // One value, so finite
459   static constexpr bool infinite = false;
460 };
461
462 /*
463  ***************************** Operators ***************************************
464  */
465
466 /**
467  * Map - For producing a sequence of values by passing each value from a source
468  * collection through a predicate.
469  *
470  * This type is usually used through the 'map' or 'mapped' helper function:
471  *
472  *   auto squares = seq(1, 10) | map(square) | asVector;
473  */
474 template <class Predicate>
475 class Map : public Operator<Map<Predicate>> {
476   Predicate pred_;
477
478  public:
479   Map() = default;
480
481   explicit Map(Predicate pred) : pred_(std::move(pred)) {}
482
483   template <class Value,
484             class Source,
485             class Result = typename ArgumentReference<
486                 typename std::result_of<Predicate(Value)>::type>::type>
487   class Generator : public GenImpl<Result, Generator<Value, Source, Result>> {
488     Source source_;
489     Predicate pred_;
490
491    public:
492     explicit Generator(Source source, const Predicate& pred)
493         : source_(std::move(source)), pred_(pred) {}
494
495     template <class Body>
496     void foreach(Body&& body) const {
497       source_.foreach(
498           [&](Value value) { body(pred_(std::forward<Value>(value))); });
499     }
500
501     template <class Handler>
502     bool apply(Handler&& handler) const {
503       return source_.apply([&](Value value) {
504         return handler(pred_(std::forward<Value>(value)));
505       });
506     }
507
508     static constexpr bool infinite = Source::infinite;
509   };
510
511   template <class Source,
512             class Value,
513             class Gen = Generator<Value, Source>>
514   Gen compose(GenImpl<Value, Source>&& source) const {
515     return Gen(std::move(source.self()), pred_);
516   }
517
518   template <class Source,
519             class Value,
520             class Gen = Generator<Value, Source>>
521   Gen compose(const GenImpl<Value, Source>& source) const {
522     return Gen(source.self(), pred_);
523   }
524 };
525
526 /**
527  * Filter - For filtering values from a source sequence by a predicate.
528  *
529  * This type is usually used through the 'filter' helper function, like:
530  *
531  *   auto nonEmpty = from(strings)
532  *                 | filter([](const string& str) -> bool {
533  *                     return !str.empty();
534  *                   });
535  *
536  * Note that if no predicate is provided, the values are casted to bool and
537  * filtered based on that. So if pointers is a vector of pointers,
538  *
539  *   auto nonNull = from(pointers) | filter();
540  *
541  * will give a vector of all the pointers != nullptr.
542  */
543 template <class Predicate>
544 class Filter : public Operator<Filter<Predicate>> {
545   Predicate pred_;
546
547  public:
548   Filter() = default;
549   explicit Filter(Predicate pred) : pred_(std::move(pred)) {}
550
551   template <class Value, class Source>
552   class Generator : public GenImpl<Value, Generator<Value, Source>> {
553     Source source_;
554     Predicate pred_;
555
556    public:
557     explicit Generator(Source source, const Predicate& pred)
558         : source_(std::move(source)), pred_(pred) {}
559
560     template <class Body>
561     void foreach(Body&& body) const {
562       source_.foreach([&](Value value) {
563         // NB: Argument not forwarded to avoid accidental move-construction
564         if (pred_(value)) {
565           body(std::forward<Value>(value));
566         }
567       });
568     }
569
570     template <class Handler>
571     bool apply(Handler&& handler) const {
572       return source_.apply([&](Value value) -> bool {
573         // NB: Argument not forwarded to avoid accidental move-construction
574         if (pred_(value)) {
575           return handler(std::forward<Value>(value));
576         }
577         return true;
578       });
579     }
580
581     static constexpr bool infinite = Source::infinite;
582   };
583
584   template <class Source,
585             class Value,
586             class Gen = Generator<Value, Source>>
587   Gen compose(GenImpl<Value, Source>&& source) const {
588     return Gen(std::move(source.self()), pred_);
589   }
590
591   template <class Source,
592             class Value,
593             class Gen = Generator<Value, Source>>
594   Gen compose(const GenImpl<Value, Source>& source) const {
595     return Gen(source.self(), pred_);
596   }
597 };
598
599 /**
600  * Until - For producing values from a source until a predicate is satisfied.
601  *
602  * This type is usually used through the 'until' helper function, like:
603  *
604  *   auto best = from(sortedItems)
605  *             | until([](Item& item) { return item.score > 100; })
606  *             | asVector;
607  */
608 template <class Predicate>
609 class Until : public Operator<Until<Predicate>> {
610   Predicate pred_;
611
612  public:
613   Until() = default;
614   explicit Until(Predicate pred) : pred_(std::move(pred)) {}
615
616   template <class Value, class Source>
617   class Generator : public GenImpl<Value, Generator<Value, Source>> {
618     Source source_;
619     Predicate pred_;
620
621    public:
622     explicit Generator(Source source, const Predicate& pred)
623         : source_(std::move(source)), pred_(pred) {}
624
625     template <class Handler>
626     bool apply(Handler&& handler) const {
627       bool cancelled = false;
628       source_.apply([&](Value value) -> bool {
629         if (pred_(value)) { // un-forwarded to disable move
630           return false;
631         }
632         if (!handler(std::forward<Value>(value))) {
633           cancelled = true;
634           return false;
635         }
636         return true;
637       });
638       return !cancelled;
639     }
640
641     // Theoretically an 'until' might stop an infinite
642     static constexpr bool infinite = false;
643   };
644
645   template <class Source,
646             class Value,
647             class Gen = Generator<Value, Source>>
648   Gen compose(GenImpl<Value, Source>&& source) const {
649     return Gen(std::move(source.self()), pred_);
650   }
651
652   template <class Source,
653             class Value,
654             class Gen = Generator<Value, Source>>
655   Gen compose(const GenImpl<Value, Source>& source) const {
656     return Gen(source.self(), pred_);
657   }
658 };
659
660 /**
661  * Take - For producing up to N values from a source.
662  *
663  * This type is usually used through the 'take' helper function, like:
664  *
665  *   auto best = from(docs)
666  *             | orderByDescending(scoreDoc)
667  *             | take(10);
668  */
669 class Take : public Operator<Take> {
670   size_t count_;
671
672  public:
673   explicit Take(size_t count) : count_(count) {}
674
675   template <class Value, class Source>
676   class Generator : public GenImpl<Value, Generator<Value, Source>> {
677     Source source_;
678     size_t count_;
679
680    public:
681     explicit Generator(Source source, size_t count)
682         : source_(std::move(source)), count_(count) {}
683
684     template <class Handler>
685     bool apply(Handler&& handler) const {
686       if (count_ == 0) {
687         return false;
688       }
689       size_t n = count_;
690       bool cancelled = false;
691       source_.apply([&](Value value) -> bool {
692         if (!handler(std::forward<Value>(value))) {
693           cancelled = true;
694           return false;
695         }
696         return --n;
697       });
698       return !cancelled;
699     }
700
701     // take will stop an infinite generator
702     static constexpr bool infinite = false;
703   };
704
705   template <class Source,
706             class Value,
707             class Gen = Generator<Value, Source>>
708   Gen compose(GenImpl<Value, Source>&& source) const {
709     return Gen(std::move(source.self()), count_);
710   }
711
712   template <class Source,
713             class Value,
714             class Gen = Generator<Value, Source>>
715   Gen compose(const GenImpl<Value, Source>& source) const {
716     return Gen(source.self(), count_);
717   }
718 };
719
720 /**
721  * Stride - For producing every Nth value from a source.
722  *
723  * This type is usually used through the 'stride' helper function, like:
724  *
725  *   auto half = from(samples)
726  *             | stride(2);
727  */
728 class Stride : public Operator<Stride> {
729   size_t stride_;
730
731  public:
732   explicit Stride(size_t stride) : stride_(stride) {
733     if (stride == 0) {
734       throw std::invalid_argument("stride must not be 0");
735     }
736   }
737
738   template <class Value, class Source>
739   class Generator : public GenImpl<Value, Generator<Value, Source>> {
740     Source source_;
741     size_t stride_;
742
743    public:
744     explicit Generator(Source source, size_t stride)
745         : source_(std::move(source)), stride_(stride) {}
746
747     template <class Handler>
748     bool apply(Handler&& handler) const {
749       size_t distance = stride_;
750       return source_.apply([&](Value value) -> bool {
751         if (++distance >= stride_) {
752           if (!handler(std::forward<Value>(value))) {
753             return false;
754           }
755           distance = 0;
756         }
757         return true;
758       });
759     }
760
761     template <class Body>
762     void foreach(Body&& body) const {
763       size_t distance = stride_;
764       source_.foreach([&](Value value) {
765         if (++distance >= stride_) {
766           body(std::forward<Value>(value));
767           distance = 0;
768         }
769       });
770     }
771
772     // Taking every Nth of an infinite list is still infinte
773     static constexpr bool infinite = Source::infinite;
774   };
775
776   template <class Source,
777             class Value,
778             class Gen = Generator<Value, Source>>
779   Gen compose(GenImpl<Value, Source>&& source) const {
780     return Gen(std::move(source.self()), stride_);
781   }
782
783   template <class Source,
784             class Value,
785             class Gen = Generator<Value, Source>>
786   Gen compose(const GenImpl<Value, Source>& source) const {
787     return Gen(source.self(), stride_);
788   }
789 };
790
791 /**
792  * Sample - For taking a random sample of N elements from a sequence
793  * (without replacement).
794  */
795 template <class Random>
796 class Sample : public Operator<Sample<Random>> {
797   size_t count_;
798   Random rng_;
799
800  public:
801   explicit Sample(size_t count, Random rng)
802       : count_(count), rng_(std::move(rng)) {}
803
804   template <class Value,
805             class Source,
806             class Rand,
807             class StorageType = typename std::decay<Value>::type>
808   class Generator
809       : public GenImpl<StorageType&&,
810                        Generator<Value, Source, Rand, StorageType>> {
811     static_assert(!Source::infinite, "Cannot sample infinite source!");
812     // It's too easy to bite ourselves if random generator is only 16-bit
813     static_assert(Random::max() >= std::numeric_limits<int32_t>::max() - 1,
814                   "Random number generator must support big values");
815     Source source_;
816     size_t count_;
817     mutable Rand rng_;
818
819    public:
820     explicit Generator(Source source, size_t count, Random rng)
821         : source_(std::move(source)), count_(count), rng_(std::move(rng)) {}
822
823     template <class Handler>
824     bool apply(Handler&& handler) const {
825       if (count_ == 0) {
826         return false;
827       }
828       std::vector<StorageType> v;
829       v.reserve(count_);
830       // use reservoir sampling to give each source value an equal chance
831       // of appearing in our output.
832       size_t n = 1;
833       source_.foreach([&](Value value) -> void {
834         if (v.size() < count_) {
835           v.push_back(std::forward<Value>(value));
836         } else {
837           // alternatively, we could create a std::uniform_int_distribution
838           // instead of using modulus, but benchmarks show this has
839           // substantial overhead.
840           size_t index = rng_() % n;
841           if (index < v.size()) {
842             v[index] = std::forward<Value>(value);
843           }
844         }
845         ++n;
846       });
847
848       // output is unsorted!
849       for (auto& val : v) {
850         if (!handler(std::move(val))) {
851           return false;
852         }
853       }
854       return true;
855     }
856
857     // Only takes N elements, so finite
858     static constexpr bool infinite = false;
859   };
860
861   template <class Source,
862             class Value,
863             class Gen = Generator<Value, Source, Random>>
864   Gen compose(GenImpl<Value, Source>&& source) const {
865     return Gen(std::move(source.self()), count_, rng_);
866   }
867
868   template <class Source,
869             class Value,
870             class Gen = Generator<Value, Source, Random>>
871   Gen compose(const GenImpl<Value, Source>& source) const {
872     return Gen(source.self(), count_, rng_);
873   }
874 };
875
876 /**
877  * Skip - For skipping N items from the beginning of a source generator.
878  *
879  * This type is usually used through the 'skip' helper function, like:
880  *
881  *   auto page = from(results)
882  *             | skip(pageSize * startPage)
883  *             | take(10);
884  */
885 class Skip : public Operator<Skip> {
886   size_t count_;
887
888  public:
889   explicit Skip(size_t count) : count_(count) {}
890
891   template <class Value, class Source>
892   class Generator : public GenImpl<Value, Generator<Value, Source>> {
893     Source source_;
894     size_t count_;
895
896    public:
897     explicit Generator(Source source, size_t count)
898         : source_(std::move(source)), count_(count) {}
899
900     template <class Body>
901     void foreach(Body&& body) const {
902       if (count_ == 0) {
903         source_.foreach(body);
904         return;
905       }
906       size_t n = 0;
907       source_.foreach([&](Value value) {
908         if (n < count_) {
909           ++n;
910         } else {
911           body(std::forward<Value>(value));
912         }
913       });
914     }
915
916     template <class Handler>
917     bool apply(Handler&& handler) const {
918       if (count_ == 0) {
919         return source_.apply(std::forward<Handler>(handler));
920       }
921       size_t n = 0;
922       return source_.apply([&](Value value) -> bool {
923         if (n < count_) {
924           ++n;
925           return true;
926         }
927         return handler(std::forward<Value>(value));
928       });
929     }
930
931     // Skipping N items of an infinite source is still infinite
932     static constexpr bool infinite = Source::infinite;
933   };
934
935   template <class Source,
936             class Value,
937             class Gen = Generator<Value, Source>>
938   Gen compose(GenImpl<Value, Source>&& source) const {
939     return Gen(std::move(source.self()), count_);
940   }
941
942   template <class Source,
943             class Value,
944             class Gen = Generator<Value, Source>>
945   Gen compose(const GenImpl<Value, Source>& source) const {
946     return Gen(source.self(), count_);
947   }
948 };
949
950 /**
951  * Order - For ordering a sequence of values from a source by key.
952  * The key is extracted by the given selector functor, and this key is then
953  * compared using the specified comparator.
954  *
955  * This type is usually used through the 'order' helper function, like:
956  *
957  *   auto closest = from(places)
958  *                | orderBy([](Place& p) {
959  *                    return -distance(p.location, here);
960  *                  })
961  *                | take(10);
962  */
963 template <class Selector, class Comparer>
964 class Order : public Operator<Order<Selector, Comparer>> {
965   Selector selector_;
966   Comparer comparer_;
967
968  public:
969   Order() = default;
970
971   explicit Order(Selector selector) : selector_(std::move(selector)) {}
972
973   Order(Selector selector, Comparer comparer)
974       : selector_(std::move(selector)), comparer_(std::move(comparer)) {}
975
976   template <class Value,
977             class Source,
978             class StorageType = typename std::decay<Value>::type,
979             class Result = typename std::result_of<Selector(Value)>::type>
980   class Generator
981       : public GenImpl<StorageType&&,
982                        Generator<Value, Source, StorageType, Result>> {
983     static_assert(!Source::infinite, "Cannot sort infinite source!");
984     Source source_;
985     Selector selector_;
986     Comparer comparer_;
987
988     typedef std::vector<StorageType> VectorType;
989
990     VectorType asVector() const {
991       auto comparer = [&](const StorageType& a, const StorageType& b) {
992         return comparer_(selector_(a), selector_(b));
993       };
994       auto vals = source_ | as<VectorType>();
995       std::sort(vals.begin(), vals.end(), comparer);
996       return std::move(vals);
997     }
998
999    public:
1000     Generator(Source source, Selector selector, Comparer comparer)
1001         : source_(std::move(source)),
1002           selector_(std::move(selector)),
1003           comparer_(std::move(comparer)) {}
1004
1005     VectorType operator|(const Collect<VectorType>&) const {
1006       return asVector();
1007     }
1008
1009     VectorType operator|(const CollectTemplate<std::vector>&) const {
1010       return asVector();
1011     }
1012
1013     template <class Body>
1014     void foreach(Body&& body) const {
1015       for (auto& value : asVector()) {
1016         body(std::move(value));
1017       }
1018     }
1019
1020     template <class Handler>
1021     bool apply(Handler&& handler) const {
1022       auto comparer = [&](const StorageType& a, const StorageType& b) {
1023         // swapped for minHeap
1024         return comparer_(selector_(b), selector_(a));
1025       };
1026       auto heap = source_ | as<VectorType>();
1027       std::make_heap(heap.begin(), heap.end(), comparer);
1028       while (!heap.empty()) {
1029         std::pop_heap(heap.begin(), heap.end(), comparer);
1030         if (!handler(std::move(heap.back()))) {
1031           return false;
1032         }
1033         heap.pop_back();
1034       }
1035       return true;
1036     }
1037
1038     // Can only be run on and produce finite generators
1039     static constexpr bool infinite = false;
1040   };
1041
1042   template <class Source,
1043             class Value,
1044             class Gen = Generator<Value, Source>>
1045   Gen compose(GenImpl<Value, Source>&& source) const {
1046     return Gen(std::move(source.self()), selector_, comparer_);
1047   }
1048
1049   template <class Source,
1050             class Value,
1051             class Gen = Generator<Value, Source>>
1052   Gen compose(const GenImpl<Value, Source>& source) const {
1053     return Gen(source.self(), selector_, comparer_);
1054   }
1055 };
1056
1057 /**
1058  * GroupBy - Group values by a given key selector, producing a sequence of
1059  * groups.
1060  *
1061  * This type is usually used through the 'groupBy' helper function, like:
1062  *
1063  *   auto bests
1064  *     = from(places)
1065  *     | groupBy([](const Place& p) {
1066  *         return p.city;
1067  *       })
1068  *     | [](Group<std::string, Place>&& g) {
1069  *         cout << g.key() << ": " << (g | first).description;
1070  *       };
1071  */
1072 template <class Selector>
1073 class GroupBy : public Operator<GroupBy<Selector>> {
1074   Selector selector_;
1075
1076  public:
1077   GroupBy() {}
1078
1079   explicit GroupBy(Selector selector) : selector_(std::move(selector)) {}
1080
1081   template <class Value,
1082             class Source,
1083             class ValueDecayed = typename std::decay<Value>::type,
1084             class Key = typename std::result_of<Selector(Value)>::type,
1085             class KeyDecayed = typename std::decay<Key>::type>
1086   class Generator
1087       : public GenImpl<
1088             Group<KeyDecayed, ValueDecayed>&&,
1089             Generator<Value, Source, ValueDecayed, Key, KeyDecayed>> {
1090     static_assert(!Source::infinite, "Cannot group infinite source!");
1091     Source source_;
1092     Selector selector_;
1093
1094    public:
1095     Generator(Source source, Selector selector)
1096         : source_(std::move(source)), selector_(std::move(selector)) {}
1097
1098     typedef Group<KeyDecayed, ValueDecayed> GroupType;
1099
1100     template <class Handler>
1101     bool apply(Handler&& handler) const {
1102       std::unordered_map<KeyDecayed, typename GroupType::VectorType> groups;
1103       source_ | [&](Value value) {
1104         const Value& cv = value;
1105         auto& group = groups[selector_(cv)];
1106         group.push_back(std::forward<Value>(value));
1107       };
1108       for (auto& kg : groups) {
1109         GroupType group(kg.first, std::move(kg.second));
1110         if (!handler(std::move(group))) {
1111           return false;
1112         }
1113         kg.second.clear();
1114       }
1115       return true;
1116     }
1117
1118     // Can only be run on and produce finite generators
1119     static constexpr bool infinite = false;
1120   };
1121
1122   template <class Source,
1123             class Value,
1124             class Gen = Generator<Value, Source>>
1125   Gen compose(GenImpl<Value, Source>&& source) const {
1126     return Gen(std::move(source.self()), selector_);
1127   }
1128
1129   template <class Source,
1130             class Value,
1131             class Gen = Generator<Value, Source>>
1132   Gen compose(const GenImpl<Value, Source>& source) const {
1133     return Gen(source.self(), selector_);
1134   }
1135 };
1136
1137 /*
1138  * TypeAssertion - For verifying the exact type of the value produced by a
1139  * generator. Useful for testing and debugging, and acts as a no-op at runtime.
1140  * Pass-through at runtime. Used through the 'assert_type<>()' factory method
1141  * like so:
1142  *
1143  *   auto c =  from(vector) | assert_type<int&>() | sum;
1144  *
1145  */
1146 template <class Expected>
1147 class TypeAssertion : public Operator<TypeAssertion<Expected>> {
1148  public:
1149   template <class Source, class Value>
1150   const Source& compose(const GenImpl<Value, Source>& source) const {
1151     static_assert(std::is_same<Expected, Value>::value,
1152                   "assert_type() check failed");
1153     return source.self();
1154   }
1155
1156   template <class Source, class Value>
1157   Source&& compose(GenImpl<Value, Source>&& source) const {
1158     static_assert(std::is_same<Expected, Value>::value,
1159                   "assert_type() check failed");
1160     return std::move(source.self());
1161   }
1162 };
1163
1164 /**
1165  * Distinct - For filtering duplicates out of a sequence. A selector may be
1166  * provided to generate a key to uniquify for each value.
1167  *
1168  * This type is usually used through the 'distinct' helper function, like:
1169  *
1170  *   auto closest = from(results)
1171  *                | distinctBy([](Item& i) {
1172  *                    return i.target;
1173  *                  })
1174  *                | take(10);
1175  */
1176 template <class Selector>
1177 class Distinct : public Operator<Distinct<Selector>> {
1178   Selector selector_;
1179
1180  public:
1181   Distinct() = default;
1182
1183   explicit Distinct(Selector selector) : selector_(std::move(selector)) {}
1184
1185   template <class Value, class Source>
1186   class Generator : public GenImpl<Value, Generator<Value, Source>> {
1187     Source source_;
1188     Selector selector_;
1189
1190     typedef typename std::decay<Value>::type StorageType;
1191
1192     // selector_ cannot be passed an rvalue or it would end up passing the husk
1193     // of a value to the downstream operators.
1194     typedef const StorageType& ParamType;
1195
1196     typedef typename std::result_of<Selector(ParamType)>::type KeyType;
1197     typedef typename std::decay<KeyType>::type KeyStorageType;
1198
1199    public:
1200     Generator(Source source, Selector selector)
1201         : source_(std::move(source)), selector_(std::move(selector)) {}
1202
1203     template <class Body>
1204     void foreach(Body&& body) const {
1205       std::unordered_set<KeyStorageType> keysSeen;
1206       source_.foreach([&](Value value) {
1207         if (keysSeen.insert(selector_(ParamType(value))).second) {
1208           body(std::forward<Value>(value));
1209         }
1210       });
1211     }
1212
1213     template <class Handler>
1214     bool apply(Handler&& handler) const {
1215       std::unordered_set<KeyStorageType> keysSeen;
1216       return source_.apply([&](Value value) -> bool {
1217         if (keysSeen.insert(selector_(ParamType(value))).second) {
1218           return handler(std::forward<Value>(value));
1219         }
1220         return true;
1221       });
1222     }
1223
1224     // While running distinct on an infinite sequence might produce a
1225     // conceptually finite sequence, it will take infinite time
1226     static constexpr bool infinite = Source::infinite;
1227   };
1228
1229   template <class Source,
1230             class Value,
1231             class Gen = Generator<Value, Source>>
1232   Gen compose(GenImpl<Value, Source>&& source) const {
1233     return Gen(std::move(source.self()), selector_);
1234   }
1235
1236   template <class Source,
1237             class Value,
1238             class Gen = Generator<Value, Source>>
1239   Gen compose(const GenImpl<Value, Source>& source) const {
1240     return Gen(source.self(), selector_);
1241   }
1242 };
1243
1244 /**
1245  * Composer - Helper class for adapting pipelines into functors. Primarily used
1246  * for 'mapOp'.
1247  */
1248 template <class Operators>
1249 class Composer {
1250   Operators op_;
1251
1252  public:
1253   explicit Composer(Operators op) : op_(std::move(op)) {}
1254
1255   template <class Source,
1256             class Ret = decltype(
1257                 std::declval<Operators>().compose(std::declval<Source>()))>
1258   Ret operator()(Source&& source) const {
1259     return op_.compose(std::forward<Source>(source));
1260   }
1261 };
1262
1263 /**
1264  * Batch - For producing fixed-size batches of each value from a source.
1265  *
1266  * This type is usually used through the 'batch' helper function:
1267  *
1268  *   auto batchSums
1269  *     = seq(1, 10)
1270  *     | batch(3)
1271  *     | map([](const std::vector<int>& batch) {
1272  *         return from(batch) | sum;
1273  *       })
1274  *     | as<vector>();
1275  */
1276 class Batch : public Operator<Batch> {
1277   size_t batchSize_;
1278
1279  public:
1280   explicit Batch(size_t batchSize) : batchSize_(batchSize) {
1281     if (batchSize_ == 0) {
1282       throw std::invalid_argument("Batch size must be non-zero!");
1283     }
1284   }
1285
1286   template <class Value,
1287             class Source,
1288             class StorageType = typename std::decay<Value>::type,
1289             class VectorType = std::vector<StorageType>>
1290   class Generator
1291       : public GenImpl<VectorType&,
1292                        Generator<Value, Source, StorageType, VectorType>> {
1293     Source source_;
1294     size_t batchSize_;
1295
1296    public:
1297     explicit Generator(Source source, size_t batchSize)
1298         : source_(std::move(source)), batchSize_(batchSize) {}
1299
1300     template <class Handler>
1301     bool apply(Handler&& handler) const {
1302       VectorType batch_;
1303       batch_.reserve(batchSize_);
1304       bool shouldContinue = source_.apply([&](Value value) -> bool {
1305         batch_.push_back(std::forward<Value>(value));
1306         if (batch_.size() == batchSize_) {
1307           bool needMore = handler(batch_);
1308           batch_.clear();
1309           return needMore;
1310         }
1311         // Always need more if the handler is not called.
1312         return true;
1313       });
1314       // Flush everything, if and only if `handler` hasn't returned false.
1315       if (shouldContinue && !batch_.empty()) {
1316         shouldContinue = handler(batch_);
1317         batch_.clear();
1318       }
1319       return shouldContinue;
1320     }
1321
1322     // Taking n-tuples of an infinite source is still infinite
1323     static constexpr bool infinite = Source::infinite;
1324   };
1325
1326   template <class Source,
1327             class Value,
1328             class Gen = Generator<Value, Source>>
1329   Gen compose(GenImpl<Value, Source>&& source) const {
1330     return Gen(std::move(source.self()), batchSize_);
1331   }
1332
1333   template <class Source,
1334             class Value,
1335             class Gen = Generator<Value, Source>>
1336   Gen compose(const GenImpl<Value, Source>& source) const {
1337     return Gen(source.self(), batchSize_);
1338   }
1339 };
1340
1341 /**
1342  * Concat - For flattening generators of generators.
1343  *
1344  * This type is usually used through the 'concat' static value, like:
1345  *
1346  *   auto edges =
1347  *       from(nodes)
1348  *     | map([](Node& x) {
1349  *           return from(x.neighbors)
1350  *                | map([&](Node& y) {
1351  *                    return Edge(x, y);
1352  *                  });
1353  *         })
1354  *     | concat
1355  *     | as<std::set>();
1356  */
1357 class Concat : public Operator<Concat> {
1358  public:
1359   Concat() = default;
1360
1361   template <class Inner,
1362             class Source,
1363             class InnerValue = typename std::decay<Inner>::type::ValueType>
1364   class Generator
1365       : public GenImpl<InnerValue, Generator<Inner, Source, InnerValue>> {
1366     Source source_;
1367
1368    public:
1369     explicit Generator(Source source) : source_(std::move(source)) {}
1370
1371     template <class Handler>
1372     bool apply(Handler&& handler) const {
1373       return source_.apply([&](Inner inner) -> bool {
1374         return inner.apply(std::forward<Handler>(handler));
1375       });
1376     }
1377
1378     template <class Body>
1379     void foreach(Body&& body) const {
1380       source_.foreach([&](Inner inner) {
1381         inner.foreach(std::forward<Body>(body));
1382       });
1383     }
1384
1385     // Resulting concatination is only finite if both Source and Inner are also
1386     // finite. In one sence, if dosn't make sence to call concat when the Inner
1387     // generator is infinite (you could just call first), so we could also just
1388     // static_assert if the inner is infinite. Taking the less restrictive
1389     // approch for now.
1390     static constexpr bool infinite =
1391         Source::infinite || std::decay<Inner>::type::infinite;
1392   };
1393
1394   template <class Value,
1395             class Source,
1396             class Gen = Generator<Value, Source>>
1397   Gen compose(GenImpl<Value, Source>&& source) const {
1398     return Gen(std::move(source.self()));
1399   }
1400
1401   template <class Value,
1402             class Source,
1403             class Gen = Generator<Value, Source>>
1404   Gen compose(const GenImpl<Value, Source>& source) const {
1405     return Gen(source.self());
1406   }
1407 };
1408
1409 /**
1410  * RangeConcat - For flattening generators of iterables.
1411  *
1412  * This type is usually used through the 'rconcat' static value, like:
1413  *
1414  *   map<int, vector<int>> adjacency;
1415  *   auto sinks =
1416  *       from(adjacency)
1417  *     | get<1>()
1418  *     | rconcat()
1419  *     | as<std::set>();
1420  */
1421 class RangeConcat : public Operator<RangeConcat> {
1422  public:
1423   RangeConcat() = default;
1424
1425   template <class Range,
1426             class Source,
1427             class InnerValue = typename ValueTypeOfRange<Range>::RefType>
1428   class Generator
1429       : public GenImpl<InnerValue, Generator<Range, Source, InnerValue>> {
1430     Source source_;
1431
1432    public:
1433     explicit Generator(Source source) : source_(std::move(source)) {}
1434
1435     template <class Body>
1436     void foreach(Body&& body) const {
1437       source_.foreach([&](Range range) {
1438         for (auto& value : range) {
1439           body(value);
1440         }
1441       });
1442     }
1443
1444     template <class Handler>
1445     bool apply(Handler&& handler) const {
1446       return source_.apply([&](Range range) -> bool {
1447         for (auto& value : range) {
1448           if (!handler(value)) {
1449             return false;
1450           }
1451         }
1452         return true;
1453       });
1454     }
1455
1456     // This is similar to concat, except that the inner iterables all are finite
1457     // so the only thing that matters is that the source is infinite.
1458     static constexpr bool infinite = Source::infinite;
1459   };
1460
1461   template <class Value,
1462             class Source,
1463             class Gen = Generator<Value, Source>>
1464   Gen compose(GenImpl<Value, Source>&& source) const {
1465     return Gen(std::move(source.self()));
1466   }
1467
1468   template <class Value,
1469             class Source,
1470             class Gen = Generator<Value, Source>>
1471   Gen compose(const GenImpl<Value, Source>& source) const {
1472     return Gen(source.self());
1473   }
1474 };
1475
1476 /**
1477  * GuardImpl - For handling exceptions from downstream computation. Requires the
1478  * type of exception to catch, and handler function to invoke in the event of
1479  * the exception. Note that the handler may:
1480  *   1) return true to continue processing the sequence
1481  *   2) return false to end the sequence immediately
1482  *   3) throw, to pass the exception to the next catch
1483  * The handler must match the signature 'bool(Exception&, Value)'.
1484  *
1485  * This type is used through the `guard` helper, like so:
1486  *
1487  *  auto indexes
1488  *    = byLine(STDIN_FILENO)
1489  *    | guard<std::runtime_error>([](std::runtime_error& e,
1490  *                                   StringPiece sp) {
1491  *        LOG(ERROR) << sp << ": " << e.str();
1492  *        return true; // continue processing subsequent lines
1493  *      })
1494  *    | eachTo<int>()
1495  *    | as<vector>();
1496  *
1497  *  TODO(tjackson): Rename this back to Guard.
1498  **/
1499 template <class Exception, class ErrorHandler>
1500 class GuardImpl : public Operator<GuardImpl<Exception, ErrorHandler>> {
1501   ErrorHandler handler_;
1502
1503  public:
1504   explicit GuardImpl(ErrorHandler handler) : handler_(std::move(handler)) {}
1505
1506   template <class Value, class Source>
1507   class Generator : public GenImpl<Value, Generator<Value, Source>> {
1508     Source source_;
1509     ErrorHandler handler_;
1510
1511    public:
1512     explicit Generator(Source source, ErrorHandler handler)
1513         : source_(std::move(source)), handler_(std::move(handler)) {}
1514
1515     template <class Handler>
1516     bool apply(Handler&& handler) const {
1517       return source_.apply([&](Value value) -> bool {
1518         try {
1519           handler(std::forward<Value>(value));
1520           return true;
1521         } catch (Exception& e) {
1522           return handler_(e, std::forward<Value>(value));
1523         }
1524       });
1525     }
1526
1527     // Just passes value though, length unaffected
1528     static constexpr bool infinite = Source::infinite;
1529   };
1530
1531   template <class Value,
1532             class Source,
1533             class Gen = Generator<Value, Source>>
1534   Gen compose(GenImpl<Value, Source>&& source) const {
1535     return Gen(std::move(source.self()), handler_);
1536   }
1537
1538   template <class Value,
1539             class Source,
1540             class Gen = Generator<Value, Source>>
1541   Gen compose(const GenImpl<Value, Source>& source) const {
1542     return Gen(source.self(), handler_);
1543   }
1544 };
1545
1546 /**
1547  * Dereference - For dereferencing a sequence of pointers while filtering out
1548  * null pointers.
1549  *
1550  * This type is usually used through the 'dereference' static value, like:
1551  *
1552  *   auto refs = from(ptrs) | dereference;
1553  */
1554 class Dereference : public Operator<Dereference> {
1555  public:
1556   Dereference() = default;
1557
1558   template <class Value,
1559             class Source,
1560             class Result = decltype(*std::declval<Value>())>
1561   class Generator : public GenImpl<Result, Generator<Value, Source, Result>> {
1562     Source source_;
1563
1564    public:
1565     explicit Generator(Source source) : source_(std::move(source)) {}
1566
1567     template <class Body>
1568     void foreach(Body&& body) const {
1569       source_.foreach([&](Value value) {
1570         if (value) {
1571           return body(*std::forward<Value>(value));
1572         }
1573       });
1574     }
1575
1576     template <class Handler>
1577     bool apply(Handler&& handler) const {
1578       return source_.apply([&](Value value) -> bool {
1579         if (value) {
1580           return handler(*std::forward<Value>(value));
1581         }
1582         return true;
1583       });
1584     }
1585
1586     // Just passes value though, length unaffected
1587     static constexpr bool infinite = Source::infinite;
1588   };
1589
1590   template <class Source,
1591             class Value,
1592             class Gen = Generator<Value, Source>>
1593   Gen compose(GenImpl<Value, Source>&& source) const {
1594     return Gen(std::move(source.self()));
1595   }
1596
1597   template <class Source,
1598             class Value,
1599             class Gen = Generator<Value, Source>>
1600   Gen compose(const GenImpl<Value, Source>& source) const {
1601     return Gen(source.self());
1602   }
1603 };
1604
1605 /**
1606  * Indirect - For producing a sequence of the addresses of the values in the
1607  * input.
1608  *
1609  * This type is usually used through the 'indirect' static value, like:
1610  *
1611  *   auto ptrs = from(refs) | indirect;
1612  */
1613 class Indirect : public Operator<Indirect> {
1614  public:
1615   Indirect() = default;
1616
1617   template <class Value,
1618             class Source,
1619             class Result = typename std::remove_reference<Value>::type*>
1620   class Generator : public GenImpl<Result, Generator<Value, Source, Result>> {
1621     Source source_;
1622     static_assert(!std::is_rvalue_reference<Value>::value,
1623                   "Cannot use indirect on an rvalue");
1624
1625    public:
1626     explicit Generator(Source source) : source_(std::move(source)) {}
1627
1628     template <class Body>
1629     void foreach(Body&& body) const {
1630       source_.foreach([&](Value value) {
1631         return body(&std::forward<Value>(value));
1632       });
1633     }
1634
1635     template <class Handler>
1636     bool apply(Handler&& handler) const {
1637       return source_.apply([&](Value value) -> bool {
1638         return handler(&std::forward<Value>(value));
1639       });
1640     }
1641
1642     // Just passes value though, length unaffected
1643     static constexpr bool infinite = Source::infinite;
1644   };
1645
1646   template <class Source,
1647             class Value,
1648             class Gen = Generator<Value, Source>>
1649   Gen compose(GenImpl<Value, Source>&& source) const {
1650     return Gen(std::move(source.self()));
1651   }
1652
1653   template <class Source,
1654             class Value,
1655             class Gen = Generator<Value, Source>>
1656   Gen compose(const GenImpl<Value, Source>& source) const {
1657     return Gen(source.self());
1658   }
1659 };
1660
1661 /**
1662  * Cycle - For repeating a sequence forever.
1663  *
1664  * This type is usually used through the 'cycle' static value, like:
1665  *
1666  *   auto tests
1667  *     = from(samples)
1668  *     | cycle
1669  *     | take(100);
1670  *
1671  * or in the finite case:
1672  *
1673  *   auto thrice = g | cycle(3);
1674  */
1675 template <bool forever>
1676 class Cycle : public Operator<Cycle<forever>> {
1677   off_t limit_; // not used if forever == true
1678  public:
1679   Cycle() = default;
1680
1681   explicit Cycle(off_t limit) : limit_(limit) {
1682     static_assert(
1683         !forever,
1684         "Cycle limit constructor should not be used when forever == true.");
1685   }
1686
1687   template <class Value, class Source>
1688   class Generator : public GenImpl<Value, Generator<Value, Source>> {
1689     Source source_;
1690     off_t limit_;
1691
1692    public:
1693     explicit Generator(Source source, off_t limit)
1694         : source_(std::move(source)), limit_(limit) {}
1695
1696     template <class Handler>
1697     bool apply(Handler&& handler) const {
1698       bool cont;
1699       auto handler2 = [&](Value value) {
1700         cont = handler(std::forward<Value>(value));
1701         return cont;
1702       };
1703       // Becomes an infinte loop if forever == true
1704       for (off_t count = 0; (forever || count != limit_); ++count) {
1705         cont = false;
1706         source_.apply(handler2);
1707         if (!cont) {
1708           return false;
1709         }
1710       }
1711       return true;
1712     }
1713
1714     // This is the hardest one to infer. If we are simply doing a finite cycle,
1715     // then (gen | cycle(n)) is infinite if and only if gen is infinite.
1716     // However, if we are doing an infinite cycle, (gen | cycle) is infinite
1717     // unless gen is empty. However, we will always mark (gen | cycle) as
1718     // infinite, because patterns such as (gen | cycle | count) can either take
1719     // on exactly one value, or infinite loop.
1720     static constexpr bool infinite = forever || Source::infinite;
1721   };
1722
1723   template <class Source,
1724             class Value,
1725             class Gen = Generator<Value, Source>>
1726   Gen compose(GenImpl<Value, Source>&& source) const {
1727     return Gen(std::move(source.self()), limit_);
1728   }
1729
1730   template <class Source,
1731             class Value,
1732             class Gen = Generator<Value, Source>>
1733   Gen compose(const GenImpl<Value, Source>& source) const {
1734     return Gen(source.self(), limit_);
1735   }
1736
1737   /**
1738    * Convenience function for finite cycles used like:
1739    *
1740    *  auto tripled = gen | cycle(3);
1741    */
1742   Cycle<false> operator()(off_t limit) const { return Cycle<false>(limit); }
1743 };
1744
1745 /*
1746  ******************************* Sinks *****************************************
1747  */
1748
1749 /**
1750  * FoldLeft - Left-associative functional fold. For producing an aggregate value
1751  * from a seed and a folder function. Useful for custom aggregators on a
1752  * sequence.
1753  *
1754  * This type is primarily used through the 'foldl' helper method, like:
1755  *
1756  *   double movingAverage = from(values)
1757  *                        | foldl(0.0, [](double avg, double sample) {
1758  *                            return sample * 0.1 + avg * 0.9;
1759  *                          });
1760  */
1761 template <class Seed, class Fold>
1762 class FoldLeft : public Operator<FoldLeft<Seed, Fold>> {
1763   Seed seed_;
1764   Fold fold_;
1765
1766  public:
1767   FoldLeft() = default;
1768   FoldLeft(Seed seed, Fold fold)
1769       : seed_(std::move(seed)), fold_(std::move(fold)) {}
1770
1771   template <class Source, class Value>
1772   Seed compose(const GenImpl<Value, Source>& source) const {
1773     static_assert(!Source::infinite, "Cannot foldl infinite source");
1774     Seed accum = seed_;
1775     source | [&](Value v) {
1776       accum = fold_(std::move(accum), std::forward<Value>(v));
1777     };
1778     return accum;
1779   }
1780 };
1781
1782 /**
1783  * First - For finding the first value in a sequence.
1784  *
1785  * This type is primarily used through the 'first' static value, like:
1786  *
1787  *   int firstThreeDigitPrime = seq(100) | filter(isPrime) | first;
1788  */
1789 class First : public Operator<First> {
1790  public:
1791   First() = default;
1792
1793   template <class Source,
1794             class Value,
1795             class StorageType = typename std::decay<Value>::type>
1796   Optional<StorageType> compose(const GenImpl<Value, Source>& source) const {
1797     Optional<StorageType> accum;
1798     source | [&](Value v) -> bool {
1799       accum = std::forward<Value>(v);
1800       return false;
1801     };
1802     return accum;
1803   }
1804 };
1805
1806 /**
1807  * IsEmpty - a helper class for isEmpty and notEmpty
1808  *
1809  * Essentially returns 'result' if the source is empty. Note that this cannot be
1810  * called on an infinite source, because then there is only one possible return
1811  * value.
1812  *
1813  *
1814  *  Used primarily through 'isEmpty' and 'notEmpty' static values
1815  *
1816  *  bool hasPrimes = g | filter(prime) | notEmpty;
1817  *  bool lacksEvens = g | filter(even) | isEmpty;
1818  *
1819  *  Also used in the implementation of 'any' and 'all'
1820  */
1821 template <bool emptyResult>
1822 class IsEmpty : public Operator<IsEmpty<emptyResult>> {
1823  public:
1824   IsEmpty() = default;
1825
1826   template <class Source, class Value>
1827   bool compose(const GenImpl<Value, Source>& source) const {
1828     static_assert(!Source::infinite,
1829                   "Cannot call 'all', 'any', 'isEmpty', or 'notEmpty' on "
1830                   "infinite source. 'all' and 'isEmpty' will either return "
1831                   "false or hang. 'any' or 'notEmpty' will either return true "
1832                   "or hang.");
1833     bool ans = emptyResult;
1834     source |
1835         [&](Value /* v */) -> bool {
1836           ans = !emptyResult;
1837           return false;
1838         };
1839     return ans;
1840   }
1841 };
1842
1843 /**
1844  * Reduce - Functional reduce, for recursively combining values from a source
1845  * using a reducer function until there is only one item left. Useful for
1846  * combining values when an empty sequence doesn't make sense.
1847  *
1848  * This type is primarily used through the 'reduce' helper method, like:
1849  *
1850  *   sring longest = from(names)
1851  *                 | reduce([](string&& best, string& current) {
1852  *                     return best.size() >= current.size() ? best : current;
1853  *                   });
1854  */
1855 template <class Reducer>
1856 class Reduce : public Operator<Reduce<Reducer>> {
1857   Reducer reducer_;
1858
1859  public:
1860   Reduce() = default;
1861   explicit Reduce(Reducer reducer) : reducer_(std::move(reducer)) {}
1862
1863   template <class Source,
1864             class Value,
1865             class StorageType = typename std::decay<Value>::type>
1866   Optional<StorageType> compose(const GenImpl<Value, Source>& source) const {
1867     static_assert(!Source::infinite, "Cannot reduce infinite source");
1868     Optional<StorageType> accum;
1869     source | [&](Value v) {
1870       if (auto target = accum.get_pointer()) {
1871         *target = reducer_(std::move(*target), std::forward<Value>(v));
1872       } else {
1873         accum = std::forward<Value>(v);
1874       }
1875     };
1876     return accum;
1877   }
1878 };
1879
1880 /**
1881  * Count - for simply counting the items in a collection.
1882  *
1883  * This type is usually used through its singleton, 'count':
1884  *
1885  *   auto shortPrimes = seq(1, 100) | filter(isPrime) | count;
1886  */
1887 class Count : public Operator<Count> {
1888  public:
1889   Count() = default;
1890
1891   template <class Source, class Value>
1892   size_t compose(const GenImpl<Value, Source>& source) const {
1893     static_assert(!Source::infinite, "Cannot count infinite source");
1894     return foldl(size_t(0),
1895                  [](size_t accum, Value /* v */) { return accum + 1; })
1896         .compose(source);
1897   }
1898 };
1899
1900 /**
1901  * Sum - For simply summing up all the values from a source.
1902  *
1903  * This type is usually used through its singleton, 'sum':
1904  *
1905  *   auto gaussSum = seq(1, 100) | sum;
1906  */
1907 class Sum : public Operator<Sum> {
1908  public:
1909   Sum() = default;
1910
1911   template <class Source,
1912             class Value,
1913             class StorageType = typename std::decay<Value>::type>
1914   StorageType compose(const GenImpl<Value, Source>& source) const {
1915     static_assert(!Source::infinite, "Cannot sum infinite source");
1916     return foldl(StorageType(0),
1917                  [](StorageType&& accum, Value v) {
1918                    return std::move(accum) + std::forward<Value>(v);
1919                  }).compose(source);
1920   }
1921 };
1922
1923 /**
1924  * Contains - For testing whether a value matching the given value is contained
1925  * in a sequence.
1926  *
1927  * This type should be used through the 'contains' helper method, like:
1928  *
1929  *   bool contained = seq(1, 10) | map(square) | contains(49);
1930  */
1931 template <class Needle>
1932 class Contains : public Operator<Contains<Needle>> {
1933   Needle needle_;
1934
1935  public:
1936   explicit Contains(Needle needle) : needle_(std::move(needle)) {}
1937
1938   template <class Source,
1939             class Value,
1940             class StorageType = typename std::decay<Value>::type>
1941   bool compose(const GenImpl<Value, Source>& source) const {
1942     static_assert(!Source::infinite,
1943                   "Calling contains on an infinite source might cause "
1944                   "an infinite loop.");
1945     return !(source | [this](Value value) {
1946       return !(needle_ == std::forward<Value>(value));
1947     });
1948   }
1949 };
1950
1951 /**
1952  * Min - For a value which minimizes a key, where the key is determined by a
1953  * given selector, and compared by given comparer.
1954  *
1955  * This type is usually used through the singletone 'min' or through the helper
1956  * functions 'minBy' and 'maxBy'.
1957  *
1958  *   auto oldest = from(people)
1959  *               | minBy([](Person& p) {
1960  *                   return p.dateOfBirth;
1961  *                 });
1962  */
1963 template <class Selector, class Comparer>
1964 class Min : public Operator<Min<Selector, Comparer>> {
1965   Selector selector_;
1966   Comparer comparer_;
1967
1968   template <typename T>
1969   const T& asConst(const T& t) const {
1970     return t;
1971   }
1972
1973  public:
1974   Min() = default;
1975
1976   explicit Min(Selector selector) : selector_(std::move(selector)) {}
1977
1978   Min(Selector selector, Comparer comparer)
1979       : selector_(std::move(selector)), comparer_(std::move(comparer)) {}
1980
1981   template <class Value,
1982             class Source,
1983             class StorageType = typename std::decay<Value>::type,
1984             class Key = typename std::decay<
1985                 typename std::result_of<Selector(Value)>::type>::type>
1986   Optional<StorageType> compose(const GenImpl<Value, Source>& source) const {
1987     static_assert(!Source::infinite,
1988                   "Calling min or max on an infinite source will cause "
1989                   "an infinite loop.");
1990     Optional<StorageType> min;
1991     Optional<Key> minKey;
1992     source | [&](Value v) {
1993       Key key = selector_(asConst(v)); // so that selector_ cannot mutate v
1994       if (auto lastKey = minKey.get_pointer()) {
1995         if (!comparer_(key, *lastKey)) {
1996           return;
1997         }
1998       }
1999       minKey = std::move(key);
2000       min = std::forward<Value>(v);
2001     };
2002     return min;
2003   }
2004 };
2005
2006 /**
2007  * Append - For collecting values from a source into a given output container
2008  * by appending.
2009  *
2010  * This type is usually used through the helper function 'appendTo', like:
2011  *
2012  *   vector<int64_t> ids;
2013  *   from(results) | map([](Person& p) { return p.id })
2014  *                 | appendTo(ids);
2015  */
2016 template <class Collection>
2017 class Append : public Operator<Append<Collection>> {
2018   Collection* collection_;
2019
2020  public:
2021   explicit Append(Collection* collection) : collection_(collection) {}
2022
2023   template <class Value, class Source>
2024   Collection& compose(const GenImpl<Value, Source>& source) const {
2025     static_assert(!Source::infinite, "Cannot appendTo with infinite source");
2026     source | [&](Value v) {
2027       collection_->insert(collection_->end(), std::forward<Value>(v));
2028     };
2029     return *collection_;
2030   }
2031 };
2032
2033 /**
2034  * Collect - For collecting values from a source in a collection of the desired
2035  * type.
2036  *
2037  * This type is usually used through the helper function 'as', like:
2038  *
2039  *   std::string upper = from(stringPiece)
2040  *                     | map(&toupper)
2041  *                     | as<std::string>();
2042  */
2043 template <class Collection>
2044 class Collect : public Operator<Collect<Collection>> {
2045  public:
2046   Collect() = default;
2047
2048   template <class Value,
2049             class Source,
2050             class StorageType = typename std::decay<Value>::type>
2051   Collection compose(const GenImpl<Value, Source>& source) const {
2052     static_assert(!Source::infinite,
2053                   "Cannot convert infinite source to object with as.");
2054     Collection collection;
2055     source | [&](Value v) {
2056       collection.insert(collection.end(), std::forward<Value>(v));
2057     };
2058     return collection;
2059   }
2060 };
2061
2062 /**
2063  * CollectTemplate - For collecting values from a source in a collection
2064  * constructed using the specified template type. Given the type of values
2065  * produced by the given generator, the collection type will be:
2066  *   Container<Value, Allocator<Value>>
2067  *
2068  * The allocator defaults to std::allocator, so this may be used for the STL
2069  * containers by simply using operators like 'as<set>', 'as<deque>',
2070  * 'as<vector>'. 'as', here is the helper method which is the usual means of
2071  * constructing this operator.
2072  *
2073  * Example:
2074  *
2075  *   set<string> uniqueNames = from(names) | as<set>();
2076  */
2077 template <template <class, class> class Container,
2078           template <class> class Allocator>
2079 class CollectTemplate : public Operator<CollectTemplate<Container, Allocator>> {
2080  public:
2081   CollectTemplate() = default;
2082
2083   template <class Value,
2084             class Source,
2085             class StorageType = typename std::decay<Value>::type,
2086             class Collection = Container<StorageType, Allocator<StorageType>>>
2087   Collection compose(const GenImpl<Value, Source>& source) const {
2088     static_assert(!Source::infinite,
2089                   "Cannot convert infinite source to object with as.");
2090     Collection collection;
2091     source | [&](Value v) {
2092       collection.insert(collection.end(), std::forward<Value>(v));
2093     };
2094     return collection;
2095   }
2096 };
2097
2098 /**
2099  * UnwrapOr - For unwrapping folly::Optional values, or providing the given
2100  * fallback value. Usually used through the 'unwrapOr' helper like so:
2101  *
2102  *   auto best = from(scores) | max | unwrapOr(-1);
2103  *
2104  * Note that the fallback value needn't match the value in the Optional it is
2105  * unwrapping. If mis-matched types are supported, the common type of the two is
2106  * returned by value. If the types match, a reference (T&& > T& > const T&) is
2107  * returned.
2108  */
2109 template <class T>
2110 class UnwrapOr {
2111  public:
2112   explicit UnwrapOr(T&& value) : value_(std::move(value)) {}
2113   explicit UnwrapOr(const T& value) : value_(value) {}
2114
2115   T& value() { return value_; }
2116   const T& value() const { return value_; }
2117
2118  private:
2119   T value_;
2120 };
2121
2122 template <class T>
2123 T&& operator|(Optional<T>&& opt, UnwrapOr<T>&& fallback) {
2124   if (T* p = opt.get_pointer()) {
2125     return std::move(*p);
2126   }
2127   return std::move(fallback.value());
2128 }
2129
2130 template <class T>
2131 T& operator|(Optional<T>& opt, UnwrapOr<T>& fallback) {
2132   if (T* p = opt.get_pointer()) {
2133     return *p;
2134   }
2135   return fallback.value();
2136 }
2137
2138 template <class T>
2139 const T& operator|(const Optional<T>& opt, const UnwrapOr<T>& fallback) {
2140   if (const T* p = opt.get_pointer()) {
2141     return *p;
2142   }
2143   return fallback.value();
2144 }
2145
2146 // Mixed type unwrapping always returns values, moving where possible
2147 template <class T,
2148           class U,
2149           class R = typename std::enable_if<
2150               !std::is_same<T, U>::value,
2151               typename std::common_type<T, U>::type>::type>
2152 R operator|(Optional<T>&& opt, UnwrapOr<U>&& fallback) {
2153   if (T* p = opt.get_pointer()) {
2154     return std::move(*p);
2155   }
2156   return std::move(fallback.value());
2157 }
2158
2159 template <class T,
2160           class U,
2161           class R = typename std::enable_if<
2162               !std::is_same<T, U>::value,
2163               typename std::common_type<T, U>::type>::type>
2164 R operator|(const Optional<T>& opt, UnwrapOr<U>&& fallback) {
2165   if (const T* p = opt.get_pointer()) {
2166     return *p;
2167   }
2168   return std::move(fallback.value());
2169 }
2170
2171 template <class T,
2172           class U,
2173           class R = typename std::enable_if<
2174               !std::is_same<T, U>::value,
2175               typename std::common_type<T, U>::type>::type>
2176 R operator|(Optional<T>&& opt, const UnwrapOr<U>& fallback) {
2177   if (T* p = opt.get_pointer()) {
2178     return std::move(*p);
2179   }
2180   return fallback.value();
2181 }
2182
2183 template <class T,
2184           class U,
2185           class R = typename std::enable_if<
2186               !std::is_same<T, U>::value,
2187               typename std::common_type<T, U>::type>::type>
2188 R operator|(const Optional<T>& opt, const UnwrapOr<U>& fallback) {
2189   if (const T* p = opt.get_pointer()) {
2190     return *p;
2191   }
2192   return fallback.value();
2193 }
2194
2195 /**
2196  * Unwrap - For unwrapping folly::Optional values in a folly::gen style. Usually
2197  * used through the 'unwrap' instace like so:
2198  *
2199  *   auto best = from(scores) | max | unwrap; // may throw
2200  */
2201 class Unwrap {};
2202
2203 template <class T>
2204 T&& operator|(Optional<T>&& opt, const Unwrap&) {
2205   return std::move(opt.value());
2206 }
2207
2208 template <class T>
2209 T& operator|(Optional<T>& opt, const Unwrap&) {
2210   return opt.value();
2211 }
2212
2213 template <class T>
2214 const T& operator|(const Optional<T>& opt, const Unwrap&) {
2215   return opt.value();
2216 }
2217
2218 } //::detail
2219
2220 /**
2221  * VirtualGen<T> - For wrapping template types in simple polymorphic wrapper.
2222  **/
2223 template <class Value>
2224 class VirtualGen : public GenImpl<Value, VirtualGen<Value>> {
2225   class WrapperBase {
2226    public:
2227     virtual ~WrapperBase() noexcept {}
2228     virtual bool apply(const std::function<bool(Value)>& handler) const = 0;
2229     virtual void foreach(const std::function<void(Value)>& body) const = 0;
2230     virtual std::unique_ptr<const WrapperBase> clone() const = 0;
2231   };
2232
2233   template <class Wrapped>
2234   class WrapperImpl : public WrapperBase {
2235     Wrapped wrapped_;
2236
2237    public:
2238     explicit WrapperImpl(Wrapped wrapped) : wrapped_(std::move(wrapped)) {}
2239
2240     bool apply(const std::function<bool(Value)>& handler) const override {
2241       return wrapped_.apply(handler);
2242     }
2243
2244     void foreach(const std::function<void(Value)>& body) const override {
2245       wrapped_.foreach(body);
2246     }
2247
2248     std::unique_ptr<const WrapperBase> clone() const override {
2249       return std::unique_ptr<const WrapperBase>(new WrapperImpl(wrapped_));
2250     }
2251   };
2252
2253   std::unique_ptr<const WrapperBase> wrapper_;
2254
2255  public:
2256   template <class Self>
2257   /* implicit */ VirtualGen(Self source)
2258       : wrapper_(new WrapperImpl<Self>(std::move(source))) {}
2259
2260   VirtualGen(VirtualGen&& source) noexcept
2261       : wrapper_(std::move(source.wrapper_)) {}
2262
2263   VirtualGen(const VirtualGen& source) : wrapper_(source.wrapper_->clone()) {}
2264
2265   VirtualGen& operator=(const VirtualGen& source) {
2266     wrapper_.reset(source.wrapper_->clone());
2267     return *this;
2268   }
2269
2270   VirtualGen& operator=(VirtualGen&& source) noexcept {
2271     wrapper_ = std::move(source.wrapper_);
2272     return *this;
2273   }
2274
2275   bool apply(const std::function<bool(Value)>& handler) const {
2276     return wrapper_->apply(handler);
2277   }
2278
2279   void foreach(const std::function<void(Value)>& body) const {
2280     wrapper_->foreach(body);
2281   }
2282 };
2283
2284 /**
2285  * non-template operators, statically defined to avoid the need for anything but
2286  * the header.
2287  */
2288 constexpr detail::Sum sum{};
2289
2290 constexpr detail::Count count{};
2291
2292 constexpr detail::First first{};
2293
2294 constexpr detail::IsEmpty<true> isEmpty{};
2295
2296 constexpr detail::IsEmpty<false> notEmpty{};
2297
2298 constexpr detail::Min<Identity, Less> min{};
2299
2300 constexpr detail::Min<Identity, Greater> max{};
2301
2302 constexpr detail::Order<Identity> order{};
2303
2304 constexpr detail::Distinct<Identity> distinct{};
2305
2306 constexpr detail::Map<Move> move{};
2307
2308 constexpr detail::Concat concat{};
2309
2310 constexpr detail::RangeConcat rconcat{};
2311
2312 constexpr detail::Cycle<true> cycle{};
2313
2314 constexpr detail::Dereference dereference{};
2315
2316 constexpr detail::Indirect indirect{};
2317
2318 constexpr detail::Unwrap unwrap{};
2319
2320 template <class Number>
2321 inline detail::Take take(Number count) {
2322   if (count < 0) {
2323     throw std::invalid_argument("Negative value passed to take()");
2324   }
2325   return detail::Take(static_cast<size_t>(count));
2326 }
2327
2328 inline detail::Stride stride(size_t s) { return detail::Stride(s); }
2329
2330 template <class Random = std::default_random_engine>
2331 inline detail::Sample<Random> sample(size_t count, Random rng = Random()) {
2332   return detail::Sample<Random>(count, std::move(rng));
2333 }
2334
2335 inline detail::Skip skip(size_t count) { return detail::Skip(count); }
2336
2337 inline detail::Batch batch(size_t batchSize) {
2338   return detail::Batch(batchSize);
2339 }
2340 } // gen
2341 } // folly
2342
2343 #pragma GCC diagnostic pop