amadeus_core/par_sink/
fold.rs

1#![allow(clippy::type_complexity)]
2
3use derive_new::new;
4use educe::Educe;
5use either::Either;
6use replace_with::replace_with_or_abort;
7use serde::{Deserialize, Serialize};
8use serde_closure::traits::FnMut;
9use std::marker::PhantomData;
10
11use super::{folder_par_sink, FolderSync, FolderSyncReducer, ParallelPipe, ParallelSink};
12
13#[derive(new)]
14#[must_use]
15pub struct Fold<P, ID, F, B> {
16	pipe: P,
17	identity: ID,
18	op: F,
19	marker: PhantomData<fn() -> B>,
20}
21
22impl_par_dist! {
23	impl<P: ParallelPipe<Item>, Item, ID, F, B> ParallelSink<Item> for Fold<P, ID, F, B>
24	where
25		ID: FnMut<(), Output = B> + Clone + Send + 'static,
26		F: FnMut<(B, Either<P::Output, B>), Output = B> + Clone + Send + 'static,
27		B: Send + 'static,
28	{
29		folder_par_sink!(FoldFolder<P::Output, ID, F, B, StepA>, FoldFolder<P::Output, ID, F, B, StepB>, self, FoldFolder::new(self.identity.clone(), self.op.clone()), FoldFolder::new(self.identity, self.op));
30	}
31}
32
33#[derive(Educe, Serialize, Deserialize, new)]
34#[educe(Clone(bound = "ID: Clone, F: Clone"))]
35#[serde(
36	bound(serialize = "ID: Serialize, F: Serialize"),
37	bound(deserialize = "ID: Deserialize<'de>, F: Deserialize<'de>")
38)]
39pub struct FoldFolder<Item, ID, F, B, Step> {
40	identity: ID,
41	op: F,
42	marker: PhantomData<fn() -> (Item, B, Step)>,
43}
44
45pub struct StepA;
46pub struct StepB;
47
48impl<Item, ID, F, B> FolderSync<Item> for FoldFolder<Item, ID, F, B, StepA>
49where
50	ID: FnMut<(), Output = B>,
51	F: FnMut<(B, Either<Item, B>), Output = B>,
52{
53	type State = B;
54	type Done = Self::State;
55
56	fn zero(&mut self) -> Self::State {
57		self.identity.call_mut(())
58	}
59	fn push(&mut self, state: &mut Self::State, item: Item) {
60		replace_with_or_abort(state, |state| self.op.call_mut((state, Either::Left(item))))
61	}
62	fn done(&mut self, state: Self::State) -> Self::Done {
63		state
64	}
65}
66impl<A, ID, F, Item> FolderSync<Item> for FoldFolder<A, ID, F, Item, StepB>
67where
68	ID: FnMut<(), Output = Item>,
69	F: FnMut<(Item, Either<A, Item>), Output = Item>,
70{
71	type State = Item;
72	type Done = Self::State;
73
74	fn zero(&mut self) -> Self::State {
75		self.identity.call_mut(())
76	}
77	fn push(&mut self, state: &mut Self::State, item: Item) {
78		replace_with_or_abort(state, |state| {
79			self.op.call_mut((state, Either::Right(item)))
80		})
81	}
82	#[inline(always)]
83	fn done(&mut self, state: Self::State) -> Self::Done {
84		state
85	}
86}