Skip to content

Commit

Permalink
feat: use Into trait for Valid::trace (#23)
Browse files Browse the repository at this point in the history
Co-authored-by: Tushar Mathur <[email protected]>
  • Loading branch information
meskill and tusharmath authored Dec 2, 2024
1 parent 5d9579f commit 46f9d48
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 13 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/target
/.idea
/build
/.vscode
/build
33 changes: 21 additions & 12 deletions src/valid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,12 @@ pub trait Validator<A, E, T>: Sized {
Fusion(self.zip(other))
}

fn trace(self, trace: T) -> Valid<A, E, T>
where
T: Clone,
{
fn trace(self, trace: impl Into<T> + Clone) -> Valid<A, E, T> {
let valid = self.to_result();
if let Err(error) = valid {
return Valid(Err(error
.into_iter()
.map(|cause| cause.trace(trace.clone()))
.map(|cause| cause.trace(trace.clone().into()))
.collect()));
}

Expand Down Expand Up @@ -121,10 +118,6 @@ impl<A, E, T> Valid<A, E, T> {
Valid(Err(vec![cause]))
}

pub fn from(error: Vec<Cause<E, T>>) -> Self {
Valid(Err(error))
}

pub fn succeed(a: A) -> Valid<A, E, T> {
Valid(Ok(a))
}
Expand Down Expand Up @@ -306,9 +299,9 @@ mod tests {
#[test]
fn test_trace() {
let result = Valid::<(), i32, String>::fail(1)
.trace("A".into())
.trace("B".into())
.trace("C".into());
.trace("A")
.trace("B")
.trace("C");

let expected = Valid::from(vec![Cause {
error: 1,
Expand Down Expand Up @@ -403,4 +396,20 @@ mod tests {
assert_eq!(result, Valid::fail(1));
assert_eq!(a, 0);
}

#[test]
fn test_trace_owned_referenced() {
let trace_value = "inner".to_string();

let valid: Valid<((), ()), &str, String> = Valid::fail("fail")
.trace(&trace_value)
.zip(Valid::fail("fail 2").trace(trace_value))
.trace("outer");

let causes = valid.to_result().unwrap_err();

assert_eq!(causes.len(), 2);
assert_eq!(causes[0].to_string(), "[outer, inner] fail");
assert_eq!(causes[1].to_string(), "[outer, inner] fail 2");
}
}

0 comments on commit 46f9d48

Please sign in to comment.