par_stream/builder/
fn_factory.rs1pub type BoxFnFactory<In, Out> = Box<dyn FnMut(In) -> BoxFn<'static, Out> + Send>;
2pub(crate) type BoxFn<'a, T> = Box<dyn FnOnce() -> T + Send + 'a>;
3
4pub trait FnFactory<In, Out>
5where
6 Self::Fn: 'static + Send + FnOnce() -> Out,
7 In: 'static + Send,
8 Out: 'static + Send,
9{
10 type Fn;
11
12 fn generate(&mut self, input: In) -> Self::Fn;
13
14 fn boxed(self) -> BoxFnFactory<In, Out>
15 where
16 Self: 'static + Send;
17
18 fn chain<GOut, G>(self, other: G) -> BoxFnFactory<In, GOut>
19 where
20 Self: 'static + Send + Sized,
21 G: 'static + Send + Clone + FnFactory<Out, GOut>,
22 GOut: 'static + Send,
23 G::Fn: 'static + Send + FnOnce() -> GOut;
24}
25
26impl<F, In, Out, Func> FnFactory<In, Out> for F
27where
28 F: FnMut(In) -> Func,
29 Func: 'static + Send + FnOnce() -> Out,
30 In: 'static + Send,
31 Out: 'static + Send,
32{
33 type Fn = Func;
34
35 fn generate(&mut self, input: In) -> Self::Fn {
36 self(input)
37 }
38
39 fn boxed(mut self) -> BoxFnFactory<In, Out>
40 where
41 Self: 'static + Send,
42 {
43 Box::new(move |input: In| -> BoxFn<'static, Out> { Box::new(self.generate(input)) })
44 }
45
46 fn chain<GOut, G>(mut self, other: G) -> BoxFnFactory<In, GOut>
47 where
48 Self: 'static + Send + Sized,
49 G: 'static + Send + Clone + FnFactory<Out, GOut>,
50 GOut: 'static + Send,
51 {
52 Box::new(move |input: In| -> BoxFn<'static, GOut> {
53 let func1 = self.generate(input);
54 let mut g = other.clone();
55
56 Box::new(move || {
57 let mid = func1();
58 let func2 = g.generate(mid);
59 func2()
60 })
61 })
62 }
63}