amadeus_core/par_stream/
map.rs

1use derive_new::new;
2use pin_project::pin_project;
3use serde::{Deserialize, Serialize};
4use serde_closure::traits::FnMut;
5use std::{
6	pin::Pin, task::{Context, Poll}
7};
8
9use super::{ParallelPipe, ParallelStream, PipeTask, StreamTask};
10
11#[pin_project]
12#[derive(new)]
13#[must_use]
14pub struct Map<P, F> {
15	#[pin]
16	pipe: P,
17	f: F,
18}
19
20impl_par_dist! {
21	impl<P: ParallelStream, F, R> ParallelStream for Map<P, F>
22	where
23		F: FnMut<(P::Item,), Output = R> + Clone + Send + 'static,
24	{
25		type Item = R;
26		type Task = MapTask<P::Task, F>;
27
28		fn size_hint(&self) -> (usize, Option<usize>) {
29			self.pipe.size_hint()
30		}
31		fn next_task(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Task>> {
32			let self_ = self.project();
33			let f = self_.f;
34			self_.pipe.next_task(cx).map(|task| {
35				task.map(|task| {
36					let f = f.clone();
37					MapTask { task, f }
38				})
39			})
40		}
41	}
42
43	impl<P: ParallelPipe<Input>, F, R, Input> ParallelPipe<Input> for Map<P, F>
44	where
45		F: FnMut<(P::Output,), Output = R> + Clone + Send + 'static,
46	{
47		type Output = R;
48		type Task = MapTask<P::Task, F>;
49
50		fn task(&self) -> Self::Task {
51			let task = self.pipe.task();
52			let f = self.f.clone();
53			MapTask { task, f }
54		}
55	}
56}
57
58#[pin_project]
59#[derive(Serialize, Deserialize)]
60pub struct MapTask<C, F> {
61	#[pin]
62	task: C,
63	f: F,
64}
65
66impl<C: StreamTask, F, R> StreamTask for MapTask<C, F>
67where
68	F: FnMut<(C::Item,), Output = R> + Clone,
69{
70	type Item = R;
71	type Async = crate::pipe::Map<C::Async, F>;
72
73	fn into_async(self) -> Self::Async {
74		crate::pipe::Map::new(self.task.into_async(), self.f)
75	}
76}
77impl<C: PipeTask<Input>, F, R, Input> PipeTask<Input> for MapTask<C, F>
78where
79	F: FnMut<(C::Output,), Output = R> + Clone,
80{
81	type Output = R;
82	type Async = crate::pipe::Map<C::Async, F>;
83
84	fn into_async(self) -> Self::Async {
85		crate::pipe::Map::new(self.task.into_async(), self.f)
86	}
87}