use crate::chain::{Chain, Operation};
#[cfg(feature = "async")]
use crate::chain::{AsyncChain, AsyncOperation};
pub struct ChainBuilder<T> {
data: Vec<T>,
operations: Vec<Operation<T>>,
}
impl<T> ChainBuilder<T> {
#[must_use]
pub fn new(data: Vec<T>) -> Self {
Self {
data,
operations: Vec::new(),
}
}
#[must_use]
pub fn map<F>(mut self, mapper: F) -> Self
where
F: Fn(&T) -> T + Send + Sync + 'static,
{
self.operations.push(Operation::Map(Box::new(mapper)));
self
}
#[must_use]
pub fn filter<F>(mut self, predicate: F) -> Self
where
F: Fn(&T) -> bool + Send + Sync + 'static,
{
self.operations.push(Operation::Filter(Box::new(predicate)));
self
}
#[must_use]
pub fn build(self) -> Chain<T> {
Chain {
data: self.data,
operations: self.operations,
}
}
}
#[cfg(feature = "async")]
pub struct AsyncChainBuilder<T> {
data: Vec<T>,
operations: Vec<AsyncOperation<T>>,
}
#[cfg(feature = "async")]
impl<T> AsyncChainBuilder<T> {
pub fn new(data: Vec<T>) -> Self {
Self {
data,
operations: Vec::new(),
}
}
pub fn map_async<F, Fut>(mut self, mapper: F) -> Self
where
F: Fn(&T) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = T> + Send + Sync + 'static,
{
self.operations.push(AsyncOperation::MapAsync(Box::new(move |x| {
Box::pin(mapper(x))
})));
self
}
pub fn filter_async<F, Fut>(mut self, predicate: F) -> Self
where
F: Fn(&T) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = bool> + Send + Sync + 'static,
{
self.operations.push(AsyncOperation::FilterAsync(Box::new(move |x| {
Box::pin(predicate(x))
})));
self
}
pub fn build(self) -> AsyncChain<T> {
AsyncChain {
data: self.data,
operations: self.operations,
}
}
}