Skip to content

Commit 8f14ec1

Browse files
committed
Implemented error conversion for FromResidual<Fallible<U>> to Fallible<E> where E: From<U>
1 parent 328d812 commit 8f14ec1

File tree

2 files changed

+47
-4
lines changed

2 files changed

+47
-4
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "fallible-option"
3-
version = "0.1.0"
3+
version = "0.1.1"
44
authors = ["Mathias Pius <contact@pius.io>"]
55
description = "Fallible is an Option with inverted Try-semantics."
66
keywords = ["error-handling", "result", "try", "fallible"]

src/lib.rs

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -633,10 +633,16 @@ impl<E> Try for Fallible<E> {
633633
}
634634
}
635635

636-
impl<E> FromResidual<Fallible<E>> for Fallible<E> {
636+
impl<E, U> FromResidual<Fallible<U>> for Fallible<E>
637+
where
638+
E: From<U>,
639+
{
637640
#[inline]
638-
fn from_residual(residual: Fallible<E>) -> Self {
639-
residual
641+
fn from_residual(residual: Fallible<U>) -> Self {
642+
match residual {
643+
Success => Success,
644+
Fail(u) => Fail(u.into()),
645+
}
640646
}
641647
}
642648

@@ -669,3 +675,40 @@ impl<E> FromResidual<Result<Infallible, E>> for Fallible<E> {
669675
}
670676
}
671677
}
678+
679+
#[cfg(test)]
680+
mod tests {
681+
use crate::Fallible::{self, Fail, Success};
682+
683+
#[test]
684+
fn casting_conversion() {
685+
#[derive(Debug, PartialEq)]
686+
struct InnerError(pub u8);
687+
688+
#[derive(Debug, PartialEq)]
689+
enum OuterError {
690+
Inner(InnerError),
691+
}
692+
693+
impl From<InnerError> for OuterError {
694+
fn from(value: InnerError) -> Self {
695+
OuterError::Inner(value)
696+
}
697+
}
698+
699+
fn inner_error() -> Fallible<InnerError> {
700+
Fail(InnerError(1))
701+
}
702+
703+
fn outer_error() -> Fallible<OuterError> {
704+
inner_error()?;
705+
706+
Success
707+
}
708+
709+
assert_eq!(
710+
outer_error().unwrap_fail(),
711+
OuterError::Inner(InnerError(1))
712+
);
713+
}
714+
}

0 commit comments

Comments
 (0)