error_rail/validation/
traits.rs

1use crate::traits::ErrorCategory;
2use crate::traits::WithError;
3use crate::validation::core::Validation;
4use crate::ErrorVec;
5
6/// Implementation of [`ErrorCategory`] for [`Validation`] types.
7///
8/// This allows `Validation<E, ()>` to act as an error category, where:
9/// - `lift` creates `Valid` values
10/// - `handle_error` creates `Invalid` values with a single error
11///
12/// # Examples
13///
14/// ```
15/// use error_rail::traits::ErrorCategory;
16/// use error_rail::validation::Validation;
17///
18/// let valid: Validation<String, i32> = <Validation<String, ()>>::lift(42);
19/// assert!(valid.is_valid());
20///
21/// let invalid: Validation<String, i32> = <Validation<String, ()>>::handle_error("error".to_string());
22/// assert!(invalid.is_invalid());
23/// ```
24impl<E> ErrorCategory<E> for Validation<E, ()> {
25    type ErrorFunctor<T> = Validation<E, T>;
26
27    #[inline]
28    fn lift<T>(value: T) -> Validation<E, T> {
29        Validation::Valid(value)
30    }
31
32    #[inline]
33    fn handle_error<T>(error: E) -> Validation<E, T> {
34        Validation::invalid(error)
35    }
36}
37
38/// Implementation of `WithError` for `Validation` types.
39///
40/// This allows transforming the error type of a validation while preserving
41/// the success value and accumulating all errors through the transformation.
42///
43/// # Examples
44///
45/// ```
46/// use error_rail::traits::WithError;
47/// use error_rail::validation::Validation;
48///
49/// let validation: Validation<&str, i32> = Validation::invalid_many(vec!["err1", "err2"]);
50/// let mapped = validation.fmap_error(|e| format!("Error: {}", e));
51/// assert_eq!(mapped.iter_errors().count(), 2);
52///
53/// let valid: Validation<&str, i32> = Validation::valid(42);
54/// let result = valid.to_result();
55/// assert_eq!(result, Ok(42));
56/// ```
57impl<T, E> WithError<E> for Validation<E, T> {
58    type Success = T;
59    type ErrorOutput<G> = Validation<G, T>;
60
61    #[inline]
62    fn fmap_error<F, G>(self, f: F) -> Self::ErrorOutput<G>
63    where
64        F: Fn(E) -> G,
65    {
66        self.map_err(f)
67    }
68
69    /// Converts the validation to a result, taking only the first error if invalid.
70    ///
71    /// This method explicitly indicates that only the first error will be returned,
72    /// potentially losing additional errors in multi-error scenarios.
73    ///
74    /// # Returns
75    ///
76    /// * `Ok(value)` if validation is valid
77    /// * `Err(first_error)` if validation is invalid (only the first error)
78    ///
79    /// # Examples
80    ///
81    /// ```
82    /// use error_rail::validation::Validation;
83    /// use error_rail::traits::WithError;
84    ///
85    /// let valid = Validation::<&str, i32>::valid(42);
86    /// assert_eq!(valid.to_result_first(), Ok(42));
87    ///
88    /// let invalid = Validation::<&str, i32>::invalid_many(vec!["error1", "error2"]);
89    /// assert_eq!(invalid.to_result_first(), Err("error1"));
90    /// ```
91    #[inline]
92    fn to_result_first(self) -> Result<Self::Success, E> {
93        match self {
94            Validation::Valid(t) => Ok(t),
95            Validation::Invalid(e) => Err(e
96                .into_iter()
97                .next()
98                .expect("Validation::Invalid must contain at least one error")),
99        }
100    }
101
102    /// Converts the validation to a result, preserving all errors if invalid.
103    ///
104    /// This method returns all accumulated errors in a `Vec<E>`, ensuring no error
105    /// information is lost during the conversion.
106    ///
107    /// # Returns
108    ///
109    /// * `Ok(value)` if validation is valid
110    /// * `Err(all_errors)` if validation is invalid (all errors in a Vec)
111    ///
112    /// # Examples
113    ///
114    /// ```
115    /// use error_rail::validation::Validation;
116    /// use error_rail::traits::WithError;
117    ///
118    /// let valid = Validation::<&str, i32>::valid(42);
119    /// assert_eq!(valid.to_result_all(), Ok(42));
120    ///
121    /// let invalid = Validation::<&str, i32>::invalid_many(vec!["error1", "error2"]);
122    /// assert_eq!(invalid.to_result_all(), Err(vec!["error1", "error2"].into()));
123    /// ```
124    #[inline]
125    fn to_result_all(self) -> Result<Self::Success, ErrorVec<E>> {
126        self.to_result()
127    }
128}