2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #ifndef FOLLY_GEN_CORE_H_
18 #error This file may only be included from folly/gen/Core.h
21 #include <type_traits>
24 #include <folly/Portability.h>
26 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
28 FOLLY_GCC_DISABLE_WARNING("-Wshadow")
34 * IsCompatibleSignature - Trait type for testing whether a given Functor
35 * matches an expected signature.
38 * IsCompatibleSignature<FunctorType, bool(int, float)>::value
40 template <class Candidate, class Expected>
41 class IsCompatibleSignature {
42 static constexpr bool value = false;
45 template <class Candidate, class ExpectedReturn, class... ArgTypes>
46 class IsCompatibleSignature<Candidate, ExpectedReturn(ArgTypes...)> {
50 decltype(std::declval<F>()(std::declval<ArgTypes>()...)),
51 bool good = std::is_same<ExpectedReturn, ActualReturn>::value>
52 static constexpr bool testArgs(int*) {
57 static constexpr bool testArgs(...) {
62 static constexpr bool value = testArgs<Candidate>(nullptr);
66 * FBounded - Helper type for the curiously recurring template pattern, used
67 * heavily here to enable inlining and obviate virtual functions
71 const Self& self() const {
72 return *static_cast<const Self*>(this);
76 return *static_cast<Self*>(this);
81 * Operator - Core abstraction of an operation which may be applied to a
82 * generator. All operators implement a method compose(), which takes a
83 * generator and produces an output generator.
86 class Operator : public FBounded<Self> {
89 * compose() - Must be implemented by child class to compose a new Generator
90 * out of a given generator. This function left intentionally unimplemented.
92 template <class Source, class Value, class ResultGen = void>
93 ResultGen compose(const GenImpl<Value, Source>& source) const;
97 Operator(Operator&&) noexcept = default;
98 Operator(const Operator&) = default;
99 Operator& operator=(Operator&&) noexcept = default;
100 Operator& operator=(const Operator&) = default;
104 * operator|() - For composing two operators without binding it to a
105 * particular generator.
110 class Composed = detail::Composed<Left, Right>>
111 Composed operator|(const Operator<Left>& left,
112 const Operator<Right>& right) {
113 return Composed(left.self(), right.self());
119 class Composed = detail::Composed<Left, Right>>
120 Composed operator|(const Operator<Left>& left,
121 Operator<Right>&& right) {
122 return Composed(left.self(), std::move(right.self()));
128 class Composed = detail::Composed<Left, Right>>
129 Composed operator|(Operator<Left>&& left,
130 const Operator<Right>& right) {
131 return Composed(std::move(left.self()), right.self());
137 class Composed = detail::Composed<Left, Right>>
138 Composed operator|(Operator<Left>&& left,
139 Operator<Right>&& right) {
140 return Composed(std::move(left.self()), std::move(right.self()));
144 * GenImpl - Core abstraction of a generator, an object which produces values by
145 * passing them to a given handler lambda. All generator implementations must
146 * implement apply(). foreach() may also be implemented to special case the
147 * condition where the entire sequence is consumed.
149 template <class Value, class Self>
150 class GenImpl : public FBounded<Self> {
152 // To prevent slicing
154 GenImpl(GenImpl&&) = default;
155 GenImpl(const GenImpl&) = default;
156 GenImpl& operator=(GenImpl&&) = default;
157 GenImpl& operator=(const GenImpl&) = default;
160 typedef Value ValueType;
161 typedef typename std::decay<Value>::type StorageType;
164 * apply() - Send all values produced by this generator to given handler until
165 * the handler returns false. Returns false if and only if the handler passed
166 * in returns false. Note: It should return true even if it completes (without
167 * the handler returning false), as 'Chain' uses the return value of apply to
168 * determine if it should process the second object in its chain.
170 template <class Handler>
171 bool apply(Handler&& handler) const;
174 * foreach() - Send all values produced by this generator to given lambda.
176 template <class Body>
177 void foreach(Body&& body) const {
178 this->self().apply([&](Value value) -> bool {
179 static_assert(!infinite, "Cannot call foreach on infinite GenImpl");
180 body(std::forward<Value>(value));
185 // Child classes should override if the sequence generated is *definitely*
186 // infinite. 'infinite' may be false_type for some infinite sequences
187 // (due the the Halting Problem).
189 // In general, almost all sources are finite (only seq(n) produces an infinite
190 // source), almost all operators keep the finiteness of the source (only cycle
191 // makes an infinite generator from a finite one, only until and take make a
192 // finite generator from an infinite one, and concat needs both the inner and
193 // outer generators to be finite to make a finite one), and most sinks
194 // cannot accept and infinite generators (first being the expection).
195 static constexpr bool infinite = false;
203 class Chain = detail::Chain<LeftValue, Left, Right>>
204 Chain operator+(const GenImpl<LeftValue, Left>& left,
205 const GenImpl<RightValue, Right>& right) {
207 std::is_same<LeftValue, RightValue>::value,
208 "Generators may ony be combined if Values are the exact same type.");
209 return Chain(left.self(), right.self());
217 class Chain = detail::Chain<LeftValue, Left, Right>>
218 Chain operator+(const GenImpl<LeftValue, Left>& left,
219 GenImpl<RightValue, Right>&& right) {
221 std::is_same<LeftValue, RightValue>::value,
222 "Generators may ony be combined if Values are the exact same type.");
223 return Chain(left.self(), std::move(right.self()));
231 class Chain = detail::Chain<LeftValue, Left, Right>>
232 Chain operator+(GenImpl<LeftValue, Left>&& left,
233 const GenImpl<RightValue, Right>& right) {
235 std::is_same<LeftValue, RightValue>::value,
236 "Generators may ony be combined if Values are the exact same type.");
237 return Chain(std::move(left.self()), right.self());
245 class Chain = detail::Chain<LeftValue, Left, Right>>
246 Chain operator+(GenImpl<LeftValue, Left>&& left,
247 GenImpl<RightValue, Right>&& right) {
249 std::is_same<LeftValue, RightValue>::value,
250 "Generators may ony be combined if Values are the exact same type.");
251 return Chain(std::move(left.self()), std::move(right.self()));
255 * operator|() which enables foreach-like usage:
256 * gen | [](Value v) -> void {...};
258 template <class Value, class Gen, class Handler>
259 typename std::enable_if<
260 IsCompatibleSignature<Handler, void(Value)>::value>::type
261 operator|(const GenImpl<Value, Gen>& gen, Handler&& handler) {
262 static_assert(!Gen::infinite,
263 "Cannot pull all values from an infinite sequence.");
264 gen.self().foreach(std::forward<Handler>(handler));
268 * operator|() which enables foreach-like usage with 'break' support:
269 * gen | [](Value v) -> bool { return shouldContinue(); };
271 template <class Value, class Gen, class Handler>
272 typename std::enable_if<
273 IsCompatibleSignature<Handler, bool(Value)>::value, bool>::type
274 operator|(const GenImpl<Value, Gen>& gen, Handler&& handler) {
275 return gen.self().apply(std::forward<Handler>(handler));
279 * operator|() for composing generators with operators, similar to boosts' range
281 * gen | map(square) | sum
283 template <class Value, class Gen, class Op>
284 auto operator|(const GenImpl<Value, Gen>& gen, const Operator<Op>& op) ->
285 decltype(op.self().compose(gen.self())) {
286 return op.self().compose(gen.self());
289 template <class Value, class Gen, class Op>
290 auto operator|(GenImpl<Value, Gen>&& gen, const Operator<Op>& op) ->
291 decltype(op.self().compose(std::move(gen.self()))) {
292 return op.self().compose(std::move(gen.self()));
298 * Composed - For building up a pipeline of operations to perform, absent any
299 * particular source generator. Useful for building up custom pipelines.
301 * This type is usually used by just piping two operators together:
303 * auto valuesOf = filter([](Optional<int>& o) { return o.hasValue(); })
304 * | map([](Optional<int>& o) -> int& { return o.value(); });
306 * auto valuesIncluded = from(optionals) | valuesOf | as<vector>();
308 template <class First, class Second>
309 class Composed : public Operator<Composed<First, Second>> {
313 Composed() = default;
315 Composed(First first, Second second)
316 : first_(std::move(first))
317 , second_(std::move(second)) {}
323 decltype(std::declval<First>().compose(std::declval<Source>())),
325 decltype(std::declval<Second>().compose(std::declval<FirstRet>()))>
326 SecondRet compose(const GenImpl<Value, Source>& source) const {
327 return second_.compose(first_.compose(source.self()));
334 decltype(std::declval<First>().compose(std::declval<Source>())),
336 decltype(std::declval<Second>().compose(std::declval<FirstRet>()))>
337 SecondRet compose(GenImpl<Value, Source>&& source) const {
338 return second_.compose(first_.compose(std::move(source.self())));
343 * Chain - For concatenating the values produced by two Generators.
345 * This type is primarily used through using '+' to combine generators, like:
347 * auto nums = seq(1, 10) + seq(20, 30);
348 * int total = nums | sum;
350 template <class Value, class First, class Second>
351 class Chain : public GenImpl<Value,
352 Chain<Value, First, Second>> {
357 explicit Chain(First first, Second second)
358 : first_(std::move(first))
359 , second_(std::move(second)) {}
361 template <class Handler>
362 bool apply(Handler&& handler) const {
363 return first_.apply(std::forward<Handler>(handler))
364 && second_.apply(std::forward<Handler>(handler));
367 template <class Body>
368 void foreach(Body&& body) const {
369 first_.foreach(std::forward<Body>(body));
370 second_.foreach(std::forward<Body>(body));
373 static constexpr bool infinite = First::infinite || Second::infinite;
376 } // namespace detail