Skip to main content

use_reaction/
reaction_condition_set.rs

1use std::fmt;
2
3use crate::{ReactionCondition, ReactionValidationError};
4
5/// An ordered collection of reaction conditions.
6#[derive(Clone, Debug, Default, Eq, PartialEq)]
7pub struct ReactionConditionSet {
8    conditions: Vec<ReactionCondition>,
9}
10
11impl ReactionConditionSet {
12    /// Creates an empty condition set.
13    #[must_use]
14    pub const fn new() -> Self {
15        Self {
16            conditions: Vec::new(),
17        }
18    }
19
20    /// Adds a condition and returns the updated set.
21    #[must_use]
22    pub fn with_condition<T>(mut self, condition: T) -> Self
23    where
24        T: Into<ReactionCondition>,
25    {
26        self.push(condition);
27        self
28    }
29
30    /// Adds a condition to the set.
31    pub fn push<T>(&mut self, condition: T)
32    where
33        T: Into<ReactionCondition>,
34    {
35        self.conditions.push(condition.into());
36    }
37
38    /// Returns the conditions as a slice.
39    #[must_use]
40    pub fn as_slice(&self) -> &[ReactionCondition] {
41        &self.conditions
42    }
43
44    /// Iterates over the conditions in insertion order.
45    pub fn iter(&self) -> impl Iterator<Item = &ReactionCondition> {
46        self.conditions.iter()
47    }
48
49    /// Returns the number of conditions.
50    #[must_use]
51    pub fn len(&self) -> usize {
52        self.conditions.len()
53    }
54
55    /// Returns `true` when the condition set is empty.
56    #[must_use]
57    pub fn is_empty(&self) -> bool {
58        self.conditions.is_empty()
59    }
60
61    /// Validates all conditions in this set.
62    ///
63    /// # Errors
64    ///
65    /// Returns a [`ReactionValidationError`] when any condition contains an empty label or value.
66    pub fn validate(&self) -> Result<(), ReactionValidationError> {
67        for condition in &self.conditions {
68            condition.validate()?;
69        }
70
71        Ok(())
72    }
73}
74
75impl fmt::Display for ReactionConditionSet {
76    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
77        for (index, condition) in self.conditions.iter().enumerate() {
78            if index > 0 {
79                formatter.write_str(", ")?;
80            }
81            write!(formatter, "{condition}")?;
82        }
83
84        Ok(())
85    }
86}