error.rs
This file
Path
src/error.rs
317 lines · 8.7 KiB · Rust
Last changed by
Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
History of this fileTake it
Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 1–2why, one step back1use std::any::TypeId;2use std::backtrace::{Backtrace, BacktraceStatus};Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 3why, one step back3use std::error::Error as StdError;Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 4–30why, one step back4use std::fmt::{self, Debug, Display};5use std::mem;6use std::ops::{Deref, DerefMut};7use std::ptr;89/// The `Exception type, a wrapper around a dynamic error type.10///11/// `Exception` functions a lot like `Box<dyn Error>`, with these differences:12///13/// - `Exception` requires that the error is `Send`, `Sync`, and `'static`14/// - `Exception` guarantees that a backtrace will exist, even if the error type15/// did not provide one16/// - `Exception` is represented as a narrow pointer - exactly one word in size,17/// instead of two.18pub struct Exception {19 inner: Box<InnerException<()>>,20}2122impl Exception {23 /// Create a new exception from any error type.24 ///25 /// The error type must be threadsafe and `'static`, so that the `Exception` will be as well.26 ///27 /// If the error type does not provide a backtrace, a backtrace will be created here to ensure28 /// that a backtrace exists.29 pub fn new<E>(error: E) -> Exception30 whereImport std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 31why, one step back31 E: StdError + Send + Sync + 'static,Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 32–45why, one step back32 {33 Exception::construct(error, TypeId::of::<E>())34 }3536 #[doc(hidden)]37 pub fn new_adhoc<M>(message: M) -> Exception38 where39 M: Display + Debug + Send + Sync + 'static,40 {41 Exception::construct(MessageError(message), TypeId::of::<M>())42 }4344 fn construct<E>(error: E, type_id: TypeId) -> Exception45 whereImport std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 46why, one step back46 E: StdError + Send + Sync + 'static,Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 47–52why, one step back47 {48 unsafe {49 let backtrace = match error.backtrace() {50 Some(_) => None,51 None => Some(Backtrace::capture()),52 };Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 53why, one step back53 let obj: TraitObject = mem::transmute(&error as &dyn StdError);Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 54–67why, one step back54 let vtable = obj.vtable;55 let inner = InnerException {56 vtable,57 type_id,58 backtrace,59 error,60 };61 Exception {62 inner: mem::transmute(Box::new(inner)),63 }64 }65 }6667 /// View this exception as the underlying error.Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 68why, one step back68 pub fn as_error(&self) -> &(dyn StdError + Send + Sync + 'static) {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 69–72why, one step back69 &**self70 }7172 /// View this exception as the underlying error, mutably.Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 73why, one step back73 pub fn as_error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 74–119why, one step back74 &mut **self75 }7677 /// Get the backtrace for this Exception.78 pub fn backtrace(&self) -> &Backtrace {79 // NB: this unwrap can only fail if the underlying error's backtrace method is80 // nondeterministic, which would only happen in maliciously constructed code81 self.inner82 .backtrace83 .as_ref()84 .or_else(|| self.inner.error().backtrace())85 .expect("exception backtrace capture failed")86 }8788 /// An iterator of errors contained by this Exception.89 ///90 /// This iterator will visit every error in the "cause chain" of this exception, beginning with91 /// the error that this exception was created from.92 pub fn errors(&self) -> Errors<'_> {93 Errors {94 next: Some(self.inner.error()),95 }96 }9798 /// Returns `true` if `E` is the type wrapped by this exception.99 pub fn is<E: Display + Debug + Send + Sync + 'static>(&self) -> bool {100 TypeId::of::<E>() == self.inner.type_id101 }102103 /// Attempt to downcast the exception to a concrete type.104 pub fn downcast<E: Display + Debug + Send + Sync + 'static>(self) -> Result<E, Exception> {105 if let Some(error) = self.downcast_ref::<E>() {106 unsafe {107 let error = ptr::read(error);108 drop(ptr::read(&self.inner));109 mem::forget(self);110 Ok(error)111 }112 } else {113 Err(self)114 }115 }116117 /// Downcast this exception by reference.118 pub fn downcast_ref<E: Display + Debug + Send + Sync + 'static>(&self) -> Option<&E> {119 if self.is::<E>() {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 120why, one step back120 unsafe { Some(&*(self.inner.error() as *const dyn StdError as *const E)) }Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 121–128why, one step back121 } else {122 None123 }124 }125126 /// Downcast this exception by mutable reference.127 pub fn downcast_mut<E: Display + Debug + Send + Sync + 'static>(&mut self) -> Option<&mut E> {128 if self.is::<E>() {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 129why, one step back129 unsafe { Some(&mut *(self.inner.error_mut() as *mut dyn StdError as *mut E)) }Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 130–135why, one step back130 } else {131 None132 }133 }134}135Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 136why, one step back136impl<E: StdError + Send + Sync + 'static> From<E> for Exception {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 137–142why, one step back137 fn from(error: E) -> Exception {138 Exception::new(error)139 }140}141142impl Deref for Exception {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 143why, one step back143 type Target = dyn StdError + Send + Sync + 'static;Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 144–234why, one step back144 fn deref(&self) -> &Self::Target {145 self.inner.error()146 }147}148149impl DerefMut for Exception {150 fn deref_mut(&mut self) -> &mut Self::Target {151 self.inner.error_mut()152 }153}154155impl Debug for Exception {156 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {157 writeln!(f, "{}", self.inner.error())?;158159 let mut errors = self.errors().skip(1).enumerate();160161 if let Some((n, error)) = errors.next() {162 writeln!(f, "\ncaused by:")?;163 writeln!(f, "\t{}: {}", n, error)?;164 for (n, error) in errors {165 writeln!(f, "\t{}: {}", n, error)?;166 }167 }168169 let backtrace = self.backtrace();170171 match backtrace.status() {172 BacktraceStatus::Captured => {173 writeln!(f, "\n{}", backtrace)?;174 }175 BacktraceStatus::Disabled => {176 writeln!(177 f,178 "\nbacktrace disabled; run with RUST_BACKTRACE=1 environment variable \179 to display a backtrace"180 )?;181 }182 _ => {}183 }184185 Ok(())186 }187}188189impl Display for Exception {190 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {191 write!(f, "{}", self.inner.error())192 }193}194195unsafe impl Send for Exception {}196unsafe impl Sync for Exception {}197198impl Drop for Exception {199 fn drop(&mut self) {200 unsafe { ptr::drop_in_place(self.inner.error_mut()) }201 }202}203204// repr C to ensure that `E` remains in the final position205#[repr(C)]206struct InnerException<E> {207 vtable: *const (),208 type_id: TypeId,209 backtrace: Option<Backtrace>,210 error: E,211}212213// repr C to ensure that transmuting from trait objects is safe214#[repr(C)]215struct TraitObject {216 data: *const (),217 vtable: *const (),218}219220#[repr(transparent)]221struct MessageError<M: Display + Debug>(M);222223impl<M: Display + Debug> Debug for MessageError<M> {224 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {225 Debug::fmt(&self.0, f)226 }227}228229impl<M: Display + Debug> Display for MessageError<M> {230 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {231 Display::fmt(&self.0, f)232 }233}234Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 235why, one step back235impl<M: Display + Debug + 'static> StdError for MessageError<M> {}Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 236–237why, one step back236237impl InnerException<()> {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 238why, one step back238 fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 239–246why, one step back239 unsafe {240 mem::transmute(TraitObject {241 data: &self.error,242 vtable: self.vtable,243 })244 }245 }246Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 247why, one step back247 fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 248–258why, one step back248 unsafe {249 mem::transmute(TraitObject {250 data: &mut self.error,251 vtable: self.vtable,252 })253 }254 }255}256257/// Iterator of errors in an `Exception`.258pub struct Errors<'a> {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 259why, one step back259 next: Option<&'a (dyn StdError + 'static)>,Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 260–262why, one step back260}261262impl<'a> Iterator for Errors<'a> {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 263why, one step back263 type Item = &'a (dyn StdError + 'static);Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 264–296why, one step back264265 fn next(&mut self) -> Option<Self::Item> {266 let next = self.next.take()?;267 self.next = next.source();268 Some(next)269 }270}271272#[cfg(test)]273mod repr_correctness {274 use super::*;275276 use std::marker::Unpin;277 use std::mem;278279 #[test]280 fn size_of_exception() {281 assert_eq!(mem::size_of::<Exception>(), mem::size_of::<usize>());282 }283284 #[allow(dead_code)]285 fn assert_exception_autotraits()286 where287 Exception: Unpin + Send + Sync + 'static,288 {289 }290291 #[test]292 fn destructors_work() {293 use std::sync::*;294295 #[derive(Debug)]296 struct HasDrop(Box<Arc<Mutex<bool>>>);Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 297why, one step back297 impl StdError for HasDrop {}Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 298–317why, one step back298 impl Display for HasDrop {299 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {300 write!(f, "does something")301 }302 }303 impl Drop for HasDrop {304 fn drop(&mut self) {305 let mut has_dropped = self.0.lock().unwrap();306 assert!(!*has_dropped);307 *has_dropped = true;308 }309 }310311 let has_dropped = Arc::new(Mutex::new(false));312313 drop(Exception::from(HasDrop(Box::new(has_dropped.clone()))));314315 assert!(*has_dropped.lock().unwrap());316 }317}