Skip to content
Myr

error.rs

This file

Path

src/error.rs

356 lines · 9.2 KiB · Rust

Last changed by

Recommend RUST_LIB_BACKTRACE=1 variableDavid Tolnaybefore adoption71b360e

History of this file

Take it

1use crate::context::ContextError;2use std::any::TypeId;3use std::backtrace::{Backtrace, BacktraceStatus};4use std::error::Error as StdError;5use std::fmt::{self, Debug, Display};6use std::mem;7use std::ops::{Deref, DerefMut};8use std::ptr;910/// The `Error` type, a wrapper around a dynamic error type.11///12/// `Error` functions a lot like `Box<dyn std::error::Error>`, with these13/// differences:14///15/// - `Error` requires that the error is `Send`, `Sync`, and `'static`16/// - `Error` guarantees that a backtrace will exist, even if the error type17///   did not provide one18/// - `Error` is represented as a narrow pointer - exactly one word in size,19///   instead of two.20pub struct Error {21    inner: Box<ErrorImpl<()>>,22}2324impl Error {25    /// Create a new error object from any error type.26    ///27    /// The error type must be threadsafe and `'static`, so that the `Error`28    /// will be as well.29    ///30    /// If the error type does not provide a backtrace, a backtrace will be31    /// created here to ensure that a backtrace exists.32    pub fn new<E>(error: E) -> Self33    where34        E: StdError + Send + Sync + 'static,35    {36        Error::construct(error, TypeId::of::<E>())37    }3839    #[doc(hidden)]40    pub fn new_adhoc<M>(message: M) -> Self41    where42        M: Display + Debug + Send + Sync + 'static,43    {44        Error::construct(MessageError(message), TypeId::of::<M>())45    }4647    fn construct<E>(error: E, type_id: TypeId) -> Self48    where49        E: StdError + Send + Sync + 'static,50    {51        let backtrace = match error.backtrace() {52            Some(_) => None,53            None => Some(Backtrace::capture()),54        };5556        unsafe {57            let obj = mem::transmute::<&dyn StdError, TraitObject>(&error);58            let vtable = obj.vtable;59            let inner = Box::new(ErrorImpl {60                vtable,61                type_id,62                backtrace,63                error,64            });65            Error {66                inner: mem::transmute::<Box<ErrorImpl<E>>, Box<ErrorImpl<()>>>(inner),67            }68        }69    }7071    /// Wrap the error value with additional context.72    pub fn context<C>(self, context: C) -> Self73    where74        C: Display + Send + Sync + 'static,75    {76        Error::from(ContextError {77            error: self,78            context,79        })80    }8182    /// View this error object as the underlying error.83    pub fn as_dyn_error(&self) -> &(dyn StdError + Send + Sync + 'static) {84        &**self85    }8687    /// View this error object as the underlying error, mutably.88    pub fn as_dyn_error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {89        &mut **self90    }9192    /// Get the backtrace for this Error.93    pub fn backtrace(&self) -> &Backtrace {94        // NB: this unwrap can only fail if the underlying error's backtrace95        // method is nondeterministic, which would only happen in maliciously96        // constructed code97        self.inner98            .backtrace99            .as_ref()100            .or_else(|| self.inner.error().backtrace())101            .expect("backtrace capture failed")102    }103104    /// An iterator of the chain of source errors contained by this Error.105    ///106    /// This iterator will visit every error in the cause chain of this error107    /// object, beginning with the error that this error object was created108    /// from.109    pub fn chain(&self) -> Chain {110        Chain {111            next: Some(self.inner.error()),112        }113    }114115    /// Returns `true` if `E` is the type wrapped by this error object.116    pub fn is<E>(&self) -> bool117    where118        E: Display + Debug + Send + Sync + 'static,119    {120        TypeId::of::<E>() == self.inner.type_id121    }122123    /// Attempt to downcast the error object to a concrete type.124    pub fn downcast<E>(self) -> Result<E, Self>125    where126        E: Display + Debug + Send + Sync + 'static,127    {128        if let Some(error) = self.downcast_ref::<E>() {129            unsafe {130                let error = ptr::read(error);131                drop(ptr::read(&self.inner));132                mem::forget(self);133                Ok(error)134            }135        } else {136            Err(self)137        }138    }139140    /// Downcast this error object by reference.141    pub fn downcast_ref<E>(&self) -> Option<&E>142    where143        E: Display + Debug + Send + Sync + 'static,144    {145        if self.is::<E>() {146            unsafe { Some(&*(self.inner.error() as *const dyn StdError as *const E)) }147        } else {148            None149        }150    }151152    /// Downcast this error object by mutable reference.153    pub fn downcast_mut<E>(&mut self) -> Option<&mut E>154    where155        E: Display + Debug + Send + Sync + 'static,156    {157        if self.is::<E>() {158            unsafe { Some(&mut *(self.inner.error_mut() as *mut dyn StdError as *mut E)) }159        } else {160            None161        }162    }163}164165impl<E> From<E> for Error166where167    E: StdError + Send + Sync + 'static,168{169    fn from(error: E) -> Self {170        Error::new(error)171    }172}173174impl Deref for Error {175    type Target = dyn StdError + Send + Sync + 'static;176    fn deref(&self) -> &Self::Target {177        self.inner.error()178    }179}180181impl DerefMut for Error {182    fn deref_mut(&mut self) -> &mut Self::Target {183        self.inner.error_mut()184    }185}186187impl Debug for Error {188    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {189        writeln!(f, "{}", self.inner.error())?;190191        let mut errors = self.chain().skip(1).enumerate();192193        if let Some((n, error)) = errors.next() {194            writeln!(f, "\ncaused by:")?;195            writeln!(f, "\t{}: {}", n, error)?;196            for (n, error) in errors {197                writeln!(f, "\t{}: {}", n, error)?;198            }199        }200201        let backtrace = self.backtrace();202203        match backtrace.status() {204            BacktraceStatus::Captured => {205                writeln!(f, "\n{}", backtrace)?;206            }207            BacktraceStatus::Disabled => {208                writeln!(209                    f,210                    "\nbacktrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace"211                )?;212            }213            _ => {}214        }215216        Ok(())217    }218}219220impl Display for Error {221    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {222        write!(f, "{}", self.inner.error())223    }224}225226unsafe impl Send for Error {}227unsafe impl Sync for Error {}228229impl Drop for Error {230    fn drop(&mut self) {231        unsafe { ptr::drop_in_place(self.inner.error_mut()) }232    }233}234235// repr C to ensure that `E` remains in the final position236#[repr(C)]237struct ErrorImpl<E> {238    vtable: *const (),239    type_id: TypeId,240    backtrace: Option<Backtrace>,241    error: E,242}243244// repr C to ensure that transmuting from trait objects is safe245#[repr(C)]246struct TraitObject {247    data: *const (),248    vtable: *const (),249}250251#[repr(transparent)]252struct MessageError<M>(M);253254impl<M> Debug for MessageError<M>255where256    M: Display + Debug,257{258    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {259        Debug::fmt(&self.0, f)260    }261}262263impl<M> Display for MessageError<M>264where265    M: Display + Debug,266{267    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {268        Display::fmt(&self.0, f)269    }270}271272impl<M> StdError for MessageError<M> where M: Display + Debug + 'static {}273274impl ErrorImpl<()> {275    fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {276        let object = TraitObject {277            data: &self.error,278            vtable: self.vtable,279        };280281        unsafe { mem::transmute::<TraitObject, &(dyn StdError + Send + Sync + 'static)>(object) }282    }283284    fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {285        let object = TraitObject {286            data: &mut self.error,287            vtable: self.vtable,288        };289290        unsafe {291            mem::transmute::<TraitObject, &mut (dyn StdError + Send + Sync + 'static)>(object)292        }293    }294}295296/// Iterator of a chain of source errors.297pub struct Chain<'a> {298    next: Option<&'a (dyn StdError + 'static)>,299}300301impl<'a> Iterator for Chain<'a> {302    type Item = &'a (dyn StdError + 'static);303304    fn next(&mut self) -> Option<Self::Item> {305        let next = self.next.take()?;306        self.next = next.source();307        Some(next)308    }309}310311#[cfg(test)]312mod repr_correctness {313    use super::*;314315    use std::marker::Unpin;316    use std::mem;317318    #[test]319    fn size_of_error() {320        assert_eq!(mem::size_of::<Error>(), mem::size_of::<usize>());321    }322323    #[allow(dead_code)]324    fn assert_error_autotraits()325    where326        Error: Unpin + Send + Sync + 'static,327    {328    }329330    #[test]331    fn destructors_work() {332        use std::sync::*;333334        #[derive(Debug)]335        struct HasDrop(Box<Arc<Mutex<bool>>>);336        impl StdError for HasDrop {}337        impl Display for HasDrop {338            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {339                write!(f, "does something")340            }341        }342        impl Drop for HasDrop {343            fn drop(&mut self) {344                let mut has_dropped = self.0.lock().unwrap();345                assert!(!*has_dropped);346                *has_dropped = true;347            }348        }349350        let has_dropped = Arc::new(Mutex::new(false));351352        drop(Error::from(HasDrop(Box::new(has_dropped.clone()))));353354        assert!(*has_dropped.lock().unwrap());355    }356}