use core::ops::AsyncFn;
#[allow(async_fn_in_trait)]
pub trait TransformOp<I> {
type Output;
async fn apply(&self, input: I) -> Self::Output;
fn then<N>(self, next: N) -> Then<Self, N>
where
Self: Sized,
N: TransformOp<Self::Output>,
{
Then {
first: self,
second: next,
}
}
}
#[must_use]
pub struct Transform<F> {
function: F,
}
impl<F> Transform<F> {
pub fn new(function: F) -> Self {
Self { function }
}
pub fn new_async(function: F) -> AsyncTransform<F> {
AsyncTransform { function }
}
}
impl<I, O, F> TransformOp<I> for Transform<F>
where
F: Fn(I) -> O,
{
type Output = O;
async fn apply(&self, input: I) -> Self::Output {
(self.function)(input)
}
}
#[must_use]
pub struct AsyncTransform<F> {
function: F,
}
impl<F> AsyncTransform<F> {
pub fn new(function: F) -> Self {
Self { function }
}
}
impl<I, O, F> TransformOp<I> for AsyncTransform<F>
where
F: AsyncFn(I) -> O,
{
type Output = O;
async fn apply(&self, input: I) -> Self::Output {
(self.function)(input).await
}
}
#[must_use]
pub struct Then<First, Second> {
first: First,
second: Second,
}
impl<I, First, Second> TransformOp<I> for Then<First, Second>
where
First: TransformOp<I>,
Second: TransformOp<First::Output>,
{
type Output = Second::Output;
async fn apply(&self, input: I) -> Self::Output {
let intermediate = self.first.apply(input).await;
self.second.apply(intermediate).await
}
}