|
77 | 77 | Self { value } |
78 | 78 | } |
79 | 79 |
|
| 80 | + /// Mutates the value inside the `Refined` type using the provided function. |
| 81 | + /// |
| 82 | + /// This method takes ownership of the current `Refined` instance, applies the |
| 83 | + /// provided function to its inner value, and attempts to create a new `Refined` |
| 84 | + /// instance with the mutated value. If the mutated value does not satisfy the |
| 85 | + /// rule, an error is returned. |
| 86 | + /// |
| 87 | + /// # Arguments |
| 88 | + /// |
| 89 | + /// * `f` - A function that takes the inner value and returns a new value. |
| 90 | + /// |
| 91 | + /// # Returns |
| 92 | + /// |
| 93 | + /// * `Result<Self, Error<T>>` - A new `Refined` instance with the mutated value |
| 94 | + /// if the value satisfies the rule, otherwise an error. |
| 95 | + /// |
| 96 | + /// # Example |
| 97 | + /// |
| 98 | + /// ```rust |
| 99 | + /// use refined_type::rule::NonEmptyString; |
| 100 | + /// use refined_type::Refined; |
| 101 | + /// |
| 102 | + /// let value = NonEmptyString::new("h".to_string()) |
| 103 | + /// .unwrap() |
| 104 | + /// .mutate(|n| n + "e") |
| 105 | + /// .unwrap() |
| 106 | + /// .mutate(|n| n + "l") |
| 107 | + /// .unwrap() |
| 108 | + /// .mutate(|n| n + "l") |
| 109 | + /// .unwrap() |
| 110 | + /// .mutate(|n| n + "o") |
| 111 | + /// .unwrap(); |
| 112 | + /// assert_eq!(value.into_value(), "hello"); |
| 113 | + /// ``` |
| 114 | + pub fn mutate<F>(self, f: F) -> Result<Self, Error<T>> |
| 115 | + where |
| 116 | + F: FnOnce(T) -> T, |
| 117 | + { |
| 118 | + Refined::new(f(self.into_value())) |
| 119 | + } |
| 120 | + |
80 | 121 | pub fn value(&self) -> &RULE::Item { |
81 | 122 | &self.value |
82 | 123 | } |
@@ -401,4 +442,15 @@ mod test { |
401 | 442 | assert_eq!(value.into_value(), vec!["hello".to_string().try_into()?]); |
402 | 443 | Ok(()) |
403 | 444 | } |
| 445 | + |
| 446 | + #[test] |
| 447 | + fn test_mutate() -> anyhow::Result<()> { |
| 448 | + let value = NonEmptyString::try_from("h")? |
| 449 | + .mutate(|n| n + "e")? |
| 450 | + .mutate(|n| n + "l")? |
| 451 | + .mutate(|n| n + "l")? |
| 452 | + .mutate(|n| n + "o")?; |
| 453 | + assert_eq!(value.into_value(), "hello"); |
| 454 | + Ok(()) |
| 455 | + } |
404 | 456 | } |
0 commit comments