Skip to content

Commit 27a2149

Browse files
committed
implement mutate
1 parent 97672b2 commit 27a2149

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

src/refined.rs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,47 @@ where
7777
Self { value }
7878
}
7979

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+
80121
pub fn value(&self) -> &RULE::Item {
81122
&self.value
82123
}
@@ -401,4 +442,15 @@ mod test {
401442
assert_eq!(value.into_value(), vec!["hello".to_string().try_into()?]);
402443
Ok(())
403444
}
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+
}
404456
}

0 commit comments

Comments
 (0)