pub trait ResultExt<T, E> {
fn combine<U>(self, other: Result<U, E>) -> Result<(T, U), E>;
fn combine_with<U, F, R>(self, other: Result<U, E>, f: F) -> Result<R, E>
where
F: FnOnce(T, U) -> R;
}
impl<T, E> ResultExt<T, E> for Result<T, E> {
fn combine<U>(self, other: Result<U, E>) -> Result<(T, U), E> {
match (self, other) {
(Ok(left), Ok(right)) => Ok((left, right)),
(Ok(_), Err(err)) => Err(err),
(Err(err), _) => Err(err),
}
}
fn combine_with<U, F, R>(self, other: Result<U, E>, f: F) -> Result<R, E>
where
F: FnOnce(T, U) -> R,
{
self.combine(other).map(|(l, r)| f(l, r))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn combine() {
let test_vector = vec![
(Ok(1), Ok(2), Ok((1, 2))),
(Ok(1), Err("right"), Err("right")),
(Err("left"), Ok(2), Err("left")),
(Err("left"), Err("right"), Err("left")),
];
for (left, right, expected) in test_vector {
assert_eq!(left.combine(right), expected);
}
}
#[test]
fn combine_with() {
fn f(l: i32, r: i32) -> i32 {
l + r
};
let test_vector = vec![
(Ok(1), Ok(2), Ok(3)),
(Ok(1), Err("right"), Err("right")),
(Err("left"), Ok(2), Err("left")),
(Err("left"), Err("right"), Err("left")),
];
for (left, right, expected) in test_vector {
assert_eq!(left.combine_with(right, f), expected);
}
}
}