Skip to content
Myr

context.rs

This file

Path

src/context.rs

177 lines · 4.0 KiB · Rust

Last changed by

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

History of this file

Take it

1use crate::error::ContextError;2use crate::{Context, Error, StdError};3use core::convert::Infallible;4use core::fmt::{self, Debug, Display, Write};56#[cfg(backtrace)]7use std::backtrace::Backtrace;89mod ext {10    use super::*;1112    pub trait StdError {13        fn ext_context<C>(self, context: C) -> Error14        where15            C: Display + Send + Sync + 'static;16    }1718    #[cfg(feature = "std")]19    impl<E> StdError for E20    where21        E: std::error::Error + Send + Sync + 'static,22    {23        fn ext_context<C>(self, context: C) -> Error24        where25            C: Display + Send + Sync + 'static,26        {27            let backtrace = backtrace_if_absent!(self);28            Error::from_context(context, self, backtrace)29        }30    }3132    impl StdError for Error {33        fn ext_context<C>(self, context: C) -> Error34        where35            C: Display + Send + Sync + 'static,36        {37            self.context(context)38        }39    }40}4142impl<T, E> Context<T, E> for Result<T, E>43where44    E: ext::StdError + Send + Sync + 'static,45{46    fn context<C>(self, context: C) -> Result<T, Error>47    where48        C: Display + Send + Sync + 'static,49    {50        self.map_err(|error| error.ext_context(context))51    }5253    fn with_context<C, F>(self, context: F) -> Result<T, Error>54    where55        C: Display + Send + Sync + 'static,56        F: FnOnce() -> C,57    {58        self.map_err(|error| error.ext_context(context()))59    }60}6162/// ```63/// # type T = ();64/// #65/// use anyhow::{Context, Result};66///67/// fn maybe_get() -> Option<T> {68///     # const IGNORE: &str = stringify! {69///     ...70///     # };71///     # unimplemented!()72/// }73///74/// fn demo() -> Result<()> {75///     let t = maybe_get().context("there is no T")?;76///     # const IGNORE: &str = stringify! {77///     ...78///     # };79///     # unimplemented!()80/// }81/// ```82impl<T> Context<T, Infallible> for Option<T> {83    fn context<C>(self, context: C) -> Result<T, Error>84    where85        C: Display + Send + Sync + 'static,86    {87        self.ok_or_else(|| Error::from_display(context, backtrace!()))88    }8990    fn with_context<C, F>(self, context: F) -> Result<T, Error>91    where92        C: Display + Send + Sync + 'static,93        F: FnOnce() -> C,94    {95        self.ok_or_else(|| Error::from_display(context(), backtrace!()))96    }97}9899impl<C, E> Debug for ContextError<C, E>100where101    C: Display,102    E: Debug,103{104    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {105        f.debug_struct("Error")106            .field("context", &Quoted(&self.context))107            .field("source", &self.error)108            .finish()109    }110}111112impl<C, E> Display for ContextError<C, E>113where114    C: Display,115{116    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {117        Display::fmt(&self.context, f)118    }119}120121impl<C, E> StdError for ContextError<C, E>122where123    C: Display,124    E: StdError + 'static,125{126    #[cfg(backtrace)]127    fn backtrace(&self) -> Option<&Backtrace> {128        self.error.backtrace()129    }130131    fn source(&self) -> Option<&(dyn StdError + 'static)> {132        Some(&self.error)133    }134}135136impl<C> StdError for ContextError<C, Error>137where138    C: Display,139{140    #[cfg(backtrace)]141    fn backtrace(&self) -> Option<&Backtrace> {142        Some(self.error.backtrace())143    }144145    fn source(&self) -> Option<&(dyn StdError + 'static)> {146        Some(unsafe { crate::ErrorImpl::error(self.error.inner.by_ref()) })147    }148}149150struct Quoted<C>(C);151152impl<C> Debug for Quoted<C>153where154    C: Display,155{156    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {157        formatter.write_char('"')?;158        Quoted(&mut *formatter).write_fmt(format_args!("{}", self.0))?;159        formatter.write_char('"')?;160        Ok(())161    }162}163164impl Write for Quoted<&mut fmt::Formatter<'_>> {165    fn write_str(&mut self, s: &str) -> fmt::Result {166        Display::fmt(&s.escape_debug(), self.0)167    }168}169170pub(crate) mod private {171    use super::*;172173    pub trait Sealed {}174175    impl<T, E> Sealed for Result<T, E> where E: ext::StdError {}176    impl<T> Sealed for Option<T> {}177}