Skip to content

Commit 108da3e

Browse files
authored
Merge pull request #26 from tomoikey/feat/mutate
implement mutate
2 parents 97672b2 + ad0af4c commit 108da3e

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ repository = "https://github.com/tomoikey/refined_type"
66
readme = "README.md"
77
categories = ["accessibility", "development-tools", "rust-patterns"]
88
license = "MIT"
9-
version = "0.5.15"
9+
version = "0.5.16"
1010
edition = "2021"
1111

1212
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

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)