streamweave_transformers/map/
map_transformer.rs

1use streamweave::TransformerConfig;
2use streamweave_error::ErrorStrategy;
3
4/// A transformer that applies a function to each item in the stream.
5///
6/// This transformer takes each input item and applies a function to transform it
7/// into an output item, creating a one-to-one mapping.
8pub struct MapTransformer<F, I, O>
9where
10  F: FnMut(I) -> O + Send + Clone + 'static,
11  I: std::fmt::Debug + Clone + Send + Sync + 'static,
12  O: std::fmt::Debug + Clone + Send + Sync + 'static,
13{
14  /// The function to apply to each input item.
15  pub f: F,
16  /// Configuration for the transformer, including error handling strategy.
17  pub config: TransformerConfig<I>,
18  /// Phantom data to track the input type parameter.
19  pub _phantom_i: std::marker::PhantomData<I>,
20  /// Phantom data to track the output type parameter.
21  pub _phantom_o: std::marker::PhantomData<O>,
22}
23
24impl<F, I, O> MapTransformer<F, I, O>
25where
26  F: FnMut(I) -> O + Send + Clone + 'static,
27  I: std::fmt::Debug + Clone + Send + Sync + 'static,
28  O: std::fmt::Debug + Clone + Send + Sync + 'static,
29{
30  /// Creates a new `MapTransformer` with the given function.
31  ///
32  /// # Arguments
33  ///
34  /// * `f` - The function to apply to each input item.
35  pub fn new(f: F) -> Self {
36    Self {
37      f,
38      config: TransformerConfig::default(),
39      _phantom_i: std::marker::PhantomData,
40      _phantom_o: std::marker::PhantomData,
41    }
42  }
43
44  /// Sets the error handling strategy for this transformer.
45  ///
46  /// # Arguments
47  ///
48  /// * `strategy` - The error handling strategy to use.
49  pub fn with_error_strategy(mut self, strategy: ErrorStrategy<I>) -> Self {
50    self.config.error_strategy = strategy;
51    self
52  }
53
54  /// Sets the name for this transformer.
55  ///
56  /// # Arguments
57  ///
58  /// * `name` - The name to assign to this transformer.
59  pub fn with_name(mut self, name: String) -> Self {
60    self.config.name = Some(name);
61    self
62  }
63}
64
65impl<F, I, O> Clone for MapTransformer<F, I, O>
66where
67  F: FnMut(I) -> O + Send + Clone + 'static,
68  I: std::fmt::Debug + Clone + Send + Sync + 'static,
69  O: std::fmt::Debug + Clone + Send + Sync + 'static,
70{
71  fn clone(&self) -> Self {
72    Self {
73      f: self.f.clone(),
74      config: self.config.clone(),
75      _phantom_i: std::marker::PhantomData,
76      _phantom_o: std::marker::PhantomData,
77    }
78  }
79}