@@ -816,12 +816,12 @@ impl Error {
816
816
}
817
817
}
818
818
819
- /// Attempt to downgrade the inner error to `E` if any.
819
+ /// Attempt to downcast the inner error to `E` if any.
820
820
///
821
821
/// If this [`Error`] was constructed via [`new`] then this function will
822
822
/// attempt to perform downgrade on it, otherwise it will return [`Err`].
823
823
///
824
- /// If downgrade succeeds, it will return [`Ok`], otherwise it will also
824
+ /// If the downcast succeeds, it will return [`Ok`], otherwise it will also
825
825
/// return [`Err`].
826
826
///
827
827
/// [`new`]: Error::new
@@ -852,13 +852,39 @@ impl Error {
852
852
/// impl From<io::Error> for E {
853
853
/// fn from(err: io::Error) -> E {
854
854
/// err.downcast::<E>()
855
- /// .map(|b| *b)
856
855
/// .unwrap_or_else(E::Io)
857
856
/// }
858
857
/// }
858
+ ///
859
+ /// impl From<E> for io::Error {
860
+ /// fn from(err: E) -> io::Error {
861
+ /// match err {
862
+ /// E::Io(io_error) => io_error,
863
+ /// e => io::Error::new(io::ErrorKind::Other, e),
864
+ /// }
865
+ /// }
866
+ /// }
867
+ ///
868
+ /// # fn main() {
869
+ /// let e = E::SomeOtherVariant;
870
+ /// // Convert it to an io::Error
871
+ /// let io_error = io::Error::from(e);
872
+ /// // Cast it back to the original variant
873
+ /// let e = E::from(io_error);
874
+ /// assert!(matches!(e, E::SomeOtherVariant));
875
+ ///
876
+ /// let io_error = io::Error::from(io::ErrorKind::AlreadyExists);
877
+ /// // Convert it to E
878
+ /// let e = E::from(io_error);
879
+ /// // Cast it back to the original variant
880
+ /// let io_error = io::Error::from(e);
881
+ /// assert_eq!(io_error.kind(), io::ErrorKind::AlreadyExists);
882
+ /// assert!(io_error.get_ref().is_none());
883
+ /// assert!(io_error.raw_os_error().is_none());
884
+ /// # }
859
885
/// ```
860
886
#[ unstable( feature = "io_error_downcast" , issue = "99262" ) ]
861
- pub fn downcast < E > ( self ) -> result:: Result < Box < E > , Self >
887
+ pub fn downcast < E > ( self ) -> result:: Result < E , Self >
862
888
where
863
889
E : error:: Error + Send + Sync + ' static ,
864
890
{
@@ -872,7 +898,7 @@ impl Error {
872
898
// And the compiler should be able to eliminate the branch
873
899
// that produces `Err` here since b.error.is::<E>()
874
900
// returns true.
875
- Ok ( res. unwrap ( ) )
901
+ Ok ( * res. unwrap ( ) )
876
902
}
877
903
repr_data => Err ( Self { repr : Repr :: new ( repr_data) } ) ,
878
904
}
0 commit comments