error.rs
This file
Path
src/error.rs
341 lines · 8.7 KiB · Rust
Last changed by
Rename Errors to ChainDavid Tolnaybefore adoptionf972193
History of this fileTake it
1use std::any::TypeId;2use std::backtrace::{Backtrace, BacktraceStatus};3use std::error::Error as StdError;4use std::fmt::{self, Debug, Display};5use std::mem;6use std::ops::{Deref, DerefMut};7use std::ptr;89/// The `Error` type, a wrapper around a dynamic error type.10///11/// `Error` functions a lot like `Box<dyn std::error::Error>`, with these12/// differences:13///14/// - `Error` requires that the error is `Send`, `Sync`, and `'static`15/// - `Error` guarantees that a backtrace will exist, even if the error type16/// did not provide one17/// - `Error` is represented as a narrow pointer - exactly one word in size,18/// instead of two.19pub struct Error {20 inner: Box<ErrorImpl<()>>,21}2223impl Error {24 /// Create a new error object from any error type.25 ///26 /// The error type must be threadsafe and `'static`, so that the `Error`27 /// will be as well.28 ///29 /// If the error type does not provide a backtrace, a backtrace will be30 /// created here to ensure that a backtrace exists.31 pub fn new<E>(error: E) -> Error32 where33 E: StdError + Send + Sync + 'static,34 {35 Error::construct(error, TypeId::of::<E>())36 }3738 #[doc(hidden)]39 pub fn new_adhoc<M>(message: M) -> Error40 where41 M: Display + Debug + Send + Sync + 'static,42 {43 Error::construct(MessageError(message), TypeId::of::<M>())44 }4546 fn construct<E>(error: E, type_id: TypeId) -> Error47 where48 E: StdError + Send + Sync + 'static,49 {50 unsafe {51 let backtrace = match error.backtrace() {52 Some(_) => None,53 None => Some(Backtrace::capture()),54 };55 let obj: TraitObject = mem::transmute(&error as &dyn StdError);56 let vtable = obj.vtable;57 let inner = ErrorImpl {58 vtable,59 type_id,60 backtrace,61 error,62 };63 Error {64 inner: mem::transmute(Box::new(inner)),65 }66 }67 }6869 /// View this error object as the underlying error.70 pub fn as_dyn_error(&self) -> &(dyn StdError + Send + Sync + 'static) {71 &**self72 }7374 /// View this error object as the underlying error, mutably.75 pub fn as_dyn_error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {76 &mut **self77 }7879 /// Get the backtrace for this Error.80 pub fn backtrace(&self) -> &Backtrace {81 // NB: this unwrap can only fail if the underlying error's backtrace82 // method is nondeterministic, which would only happen in maliciously83 // constructed code84 self.inner85 .backtrace86 .as_ref()87 .or_else(|| self.inner.error().backtrace())88 .expect("backtrace capture failed")89 }9091 /// An iterator of the chain of source errors contained by this Error.92 ///93 /// This iterator will visit every error in the cause chain of this error94 /// object, beginning with the error that this error object was created95 /// from.96 pub fn chain(&self) -> Chain {97 Chain {98 next: Some(self.inner.error()),99 }100 }101102 /// Returns `true` if `E` is the type wrapped by this error object.103 pub fn is<E>(&self) -> bool104 where105 E: Display + Debug + Send + Sync + 'static,106 {107 TypeId::of::<E>() == self.inner.type_id108 }109110 /// Attempt to downcast the error object to a concrete type.111 pub fn downcast<E>(self) -> Result<E, Error>112 where113 E: Display + Debug + Send + Sync + 'static,114 {115 if let Some(error) = self.downcast_ref::<E>() {116 unsafe {117 let error = ptr::read(error);118 drop(ptr::read(&self.inner));119 mem::forget(self);120 Ok(error)121 }122 } else {123 Err(self)124 }125 }126127 /// Downcast this error object by reference.128 pub fn downcast_ref<E>(&self) -> Option<&E>129 where130 E: Display + Debug + Send + Sync + 'static,131 {132 if self.is::<E>() {133 unsafe { Some(&*(self.inner.error() as *const dyn StdError as *const E)) }134 } else {135 None136 }137 }138139 /// Downcast this error object by mutable reference.140 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>141 where142 E: Display + Debug + Send + Sync + 'static,143 {144 if self.is::<E>() {145 unsafe { Some(&mut *(self.inner.error_mut() as *mut dyn StdError as *mut E)) }146 } else {147 None148 }149 }150}151152impl<E> From<E> for Error153where154 E: StdError + Send + Sync + 'static,155{156 fn from(error: E) -> Error {157 Error::new(error)158 }159}160161impl Deref for Error {162 type Target = dyn StdError + Send + Sync + 'static;163 fn deref(&self) -> &Self::Target {164 self.inner.error()165 }166}167168impl DerefMut for Error {169 fn deref_mut(&mut self) -> &mut Self::Target {170 self.inner.error_mut()171 }172}173174impl Debug for Error {175 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {176 writeln!(f, "{}", self.inner.error())?;177178 let mut errors = self.chain().skip(1).enumerate();179180 if let Some((n, error)) = errors.next() {181 writeln!(f, "\ncaused by:")?;182 writeln!(f, "\t{}: {}", n, error)?;183 for (n, error) in errors {184 writeln!(f, "\t{}: {}", n, error)?;185 }186 }187188 let backtrace = self.backtrace();189190 match backtrace.status() {191 BacktraceStatus::Captured => {192 writeln!(f, "\n{}", backtrace)?;193 }194 BacktraceStatus::Disabled => {195 writeln!(196 f,197 "\nbacktrace disabled; run with RUST_BACKTRACE=1 environment variable to display a backtrace"198 )?;199 }200 _ => {}201 }202203 Ok(())204 }205}206207impl Display for Error {208 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {209 write!(f, "{}", self.inner.error())210 }211}212213unsafe impl Send for Error {}214unsafe impl Sync for Error {}215216impl Drop for Error {217 fn drop(&mut self) {218 unsafe { ptr::drop_in_place(self.inner.error_mut()) }219 }220}221222// repr C to ensure that `E` remains in the final position223#[repr(C)]224struct ErrorImpl<E> {225 vtable: *const (),226 type_id: TypeId,227 backtrace: Option<Backtrace>,228 error: E,229}230231// repr C to ensure that transmuting from trait objects is safe232#[repr(C)]233struct TraitObject {234 data: *const (),235 vtable: *const (),236}237238#[repr(transparent)]239struct MessageError<M>(M);240241impl<M> Debug for MessageError<M>242where243 M: Display + Debug,244{245 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {246 Debug::fmt(&self.0, f)247 }248}249250impl<M> Display for MessageError<M>251where252 M: Display + Debug,253{254 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {255 Display::fmt(&self.0, f)256 }257}258259impl<M> StdError for MessageError<M> where M: Display + Debug + 'static {}260261impl ErrorImpl<()> {262 fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {263 unsafe {264 mem::transmute(TraitObject {265 data: &self.error,266 vtable: self.vtable,267 })268 }269 }270271 fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {272 unsafe {273 mem::transmute(TraitObject {274 data: &mut self.error,275 vtable: self.vtable,276 })277 }278 }279}280281/// Iterator of a chain of source errors.282pub struct Chain<'a> {283 next: Option<&'a (dyn StdError + 'static)>,284}285286impl<'a> Iterator for Chain<'a> {287 type Item = &'a (dyn StdError + 'static);288289 fn next(&mut self) -> Option<Self::Item> {290 let next = self.next.take()?;291 self.next = next.source();292 Some(next)293 }294}295296#[cfg(test)]297mod repr_correctness {298 use super::*;299300 use std::marker::Unpin;301 use std::mem;302303 #[test]304 fn size_of_error() {305 assert_eq!(mem::size_of::<Error>(), mem::size_of::<usize>());306 }307308 #[allow(dead_code)]309 fn assert_error_autotraits()310 where311 Error: Unpin + Send + Sync + 'static,312 {313 }314315 #[test]316 fn destructors_work() {317 use std::sync::*;318319 #[derive(Debug)]320 struct HasDrop(Box<Arc<Mutex<bool>>>);321 impl StdError for HasDrop {}322 impl Display for HasDrop {323 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {324 write!(f, "does something")325 }326 }327 impl Drop for HasDrop {328 fn drop(&mut self) {329 let mut has_dropped = self.0.lock().unwrap();330 assert!(!*has_dropped);331 *has_dropped = true;332 }333 }334335 let has_dropped = Arc::new(Mutex::new(false));336337 drop(Error::from(HasDrop(Box::new(has_dropped.clone()))));338339 assert!(*has_dropped.lock().unwrap());340 }341}