streamweave_vec/consumers/vec_consumer.rs
1use streamweave::ConsumerConfig;
2use streamweave_error::ErrorStrategy;
3
4/// A consumer that collects items into a `Vec`.
5///
6/// This consumer collects all items from the stream into an internal `Vec`,
7/// preserving the order in which they were received.
8#[derive(Clone)]
9pub struct VecConsumer<T>
10where
11 T: std::fmt::Debug + Clone + Send + Sync + 'static,
12{
13 /// The internal `Vec` where items are collected.
14 pub vec: Vec<T>,
15 /// Configuration for the consumer, including error handling strategy.
16 pub config: ConsumerConfig<T>,
17}
18
19impl<T> Default for VecConsumer<T>
20where
21 T: std::fmt::Debug + Clone + Send + Sync + 'static,
22{
23 fn default() -> Self {
24 Self::new()
25 }
26}
27
28impl<T> VecConsumer<T>
29where
30 T: std::fmt::Debug + Clone + Send + Sync + 'static,
31{
32 /// Creates a new `VecConsumer` with an empty `Vec`.
33 pub fn new() -> Self {
34 Self {
35 vec: Vec::new(),
36 config: ConsumerConfig::default(),
37 }
38 }
39
40 /// Creates a new `VecConsumer` with a pre-allocated `Vec` capacity.
41 ///
42 /// # Arguments
43 ///
44 /// * `capacity` - The initial capacity of the internal `Vec`.
45 pub fn with_capacity(capacity: usize) -> Self {
46 Self {
47 vec: Vec::with_capacity(capacity),
48 config: ConsumerConfig::default(),
49 }
50 }
51
52 /// Sets the error handling strategy for this consumer.
53 ///
54 /// # Arguments
55 ///
56 /// * `strategy` - The error handling strategy to use.
57 pub fn with_error_strategy(mut self, strategy: ErrorStrategy<T>) -> Self {
58 self.config.error_strategy = strategy;
59 self
60 }
61
62 /// Sets the name for this consumer.
63 ///
64 /// # Arguments
65 ///
66 /// * `name` - The name to assign to this consumer.
67 pub fn with_name(mut self, name: String) -> Self {
68 self.config.name = name;
69 self
70 }
71
72 /// Consumes the consumer and returns the collected `Vec`.
73 ///
74 /// # Returns
75 ///
76 /// The `Vec` containing all collected items in order.
77 pub fn into_vec(self) -> Vec<T> {
78 self.vec
79 }
80}