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