amadeus_core/par_sink/
for_each.rs1use derive_new::new;
2use educe::Educe;
3use futures::{ready, Stream};
4use pin_project::pin_project;
5use serde::{Deserialize, Serialize};
6use serde_closure::traits::FnMut;
7use std::{
8 marker::PhantomData, pin::Pin, task::{Context, Poll}
9};
10
11use super::{
12 DistributedPipe, DistributedSink, ParallelPipe, ParallelSink, PushReducer, Reducer, ReducerProcessSend, ReducerSend
13};
14use crate::{pipe::Sink, pool::ProcessSend};
15
16#[derive(new)]
17#[must_use]
18pub struct ForEach<P, F> {
19 pipe: P,
20 f: F,
21}
22
23impl<P: ParallelPipe<Item>, Item, F> ParallelSink<Item> for ForEach<P, F>
24where
25 F: FnMut<(P::Output,), Output = ()> + Clone + Send + 'static,
26{
27 type Done = ();
28 type Pipe = P;
29 type ReduceA = ForEachReducer<P::Output, F>;
30 type ReduceC = PushReducer<()>;
31
32 fn reducers(self) -> (Self::Pipe, Self::ReduceA, Self::ReduceC) {
33 (
34 self.pipe,
35 ForEachReducer(self.f, PhantomData),
36 PushReducer::new(),
37 )
38 }
39}
40impl<P: DistributedPipe<Item>, Item, F> DistributedSink<Item> for ForEach<P, F>
41where
42 F: FnMut<(P::Output,), Output = ()> + Clone + ProcessSend + 'static,
43{
44 type Done = ();
45 type Pipe = P;
46 type ReduceA = ForEachReducer<P::Output, F>;
47 type ReduceB = PushReducer<()>;
48 type ReduceC = PushReducer<()>;
49
50 fn reducers(self) -> (Self::Pipe, Self::ReduceA, Self::ReduceB, Self::ReduceC) {
51 (
52 self.pipe,
53 ForEachReducer(self.f, PhantomData),
54 PushReducer::new(),
55 PushReducer::new(),
56 )
57 }
58}
59
60#[pin_project]
61#[derive(Educe, Serialize, Deserialize)]
62#[educe(Clone(bound = "F: Clone"))]
63#[serde(
64 bound(serialize = "F: Serialize"),
65 bound(deserialize = "F: Deserialize<'de>")
66)]
67pub struct ForEachReducer<Item, F>(F, PhantomData<fn() -> Item>);
68
69impl<Item, F> Reducer<Item> for ForEachReducer<Item, F>
70where
71 F: FnMut<(Item,), Output = ()>,
72{
73 type Done = ();
74 type Async = Self;
75
76 fn into_async(self) -> Self::Async {
77 self
78 }
79}
80impl<Item, F> ReducerProcessSend<Item> for ForEachReducer<Item, F>
81where
82 F: FnMut<(Item,), Output = ()>,
83{
84 type Done = ();
85}
86impl<Item, F> ReducerSend<Item> for ForEachReducer<Item, F>
87where
88 F: FnMut<(Item,), Output = ()>,
89{
90 type Done = ();
91}
92
93impl<Item, F> Sink<Item> for ForEachReducer<Item, F>
94where
95 F: FnMut<(Item,), Output = ()>,
96{
97 type Done = ();
98
99 #[inline(always)]
100 fn poll_forward(
101 self: Pin<&mut Self>, cx: &mut Context, mut stream: Pin<&mut impl Stream<Item = Item>>,
102 ) -> Poll<Self::Done> {
103 let self_ = self.project();
104 while let Some(item) = ready!(stream.as_mut().poll_next(cx)) {
105 self_.0.call_mut((item,));
106 }
107 Poll::Ready(())
108 }
109}