error.rs
This file
Path
src/error.rs
317 lines · 8.6 KiB · Rust
Last changed by
Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84
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–8why, one step back4use std::fmt::{self, Debug, Display};5use std::mem;6use std::ops::{Deref, DerefMut};7use std::ptr;8Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 9why, one step back9/// The `Error` type, a wrapper around a dynamic error type.Rename exception module to errorDavid Tolnaybefore adoption2000930
line 10why, one step back10///Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 11why, one step back11/// `Error` functions a lot like `Box<dyn std::error::Error>`, with these differences:Rename exception module to errorDavid Tolnaybefore adoption2000930
line 12why, one step back12///Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
lines 13–14why, one step back13/// - `Error` requires that the error is `Send`, `Sync`, and `'static`14/// - `Error` guarantees that a backtrace will exist, even if the error typeRename exception module to errorDavid Tolnaybefore adoption2000930
line 15why, one step back15/// did not provide oneRename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 16why, one step back16/// - `Error` is represented as a narrow pointer - exactly one word in size,Rename exception module to errorDavid Tolnaybefore adoption2000930
line 17why, one step back17/// instead of two.Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 18why, one step back18pub struct Error {Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84
line 19why, one step back19 inner: Box<ErrorImpl<()>>,Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 20–21why, one step back20}21Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 22why, one step back22impl Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 23–24why, one step back23 /// Create a new exception from any error type.24 ///Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 25why, one step back25 /// The error type must be threadsafe and `'static`, so that the `Error` will be as well.Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 26–28why, one step back26 ///27 /// If the error type does not provide a backtrace, a backtrace will be created here to ensure28 /// that a backtrace exists.Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 29why, one step back29 pub fn new<E>(error: E) -> ErrorRename exception module to errorDavid Tolnaybefore adoption2000930
line 30why, one step back30 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
line 32why, one step back32 {Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 33why, one step back33 Error::construct(error, TypeId::of::<E>())Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 34–36why, one step back34 }3536 #[doc(hidden)]Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 37why, one step back37 pub fn new_adhoc<M>(message: M) -> ErrorRename exception module to errorDavid Tolnaybefore adoption2000930
lines 38–40why, one step back38 where39 M: Display + Debug + Send + Sync + 'static,40 {Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 41why, one step back41 Error::construct(MessageError(message), TypeId::of::<M>())Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 42–43why, one step back42 }43Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 44why, one step back44 fn construct<E>(error: E, type_id: TypeId) -> ErrorRename exception module to errorDavid Tolnaybefore adoption2000930
line 45why, one step back45 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
line 54why, one step back54 let vtable = obj.vtable;Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84
line 55why, one step back55 let inner = ErrorImpl {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 56–60why, one step back56 vtable,57 type_id,58 backtrace,59 error,60 };Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 61why, one step back61 Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 62–67why, one step back62 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–76why, one step back74 &mut **self75 }76Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 77why, one step back77 /// Get the backtrace for this Error.Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 78–87why, one step back78 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 }87Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 88why, one step back88 /// An iterator of errors contained by this Error.Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 89–103why, one step back89 ///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.Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 104why, one step back104 pub fn downcast<E: Display + Debug + Send + Sync + 'static>(self) -> Result<E, Error> {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 105–119why, one step back105 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}135Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
lines 136–138why, one step back136impl<E: StdError + Send + Sync + 'static> From<E> for Error {137 fn from(error: E) -> Error {138 Error::new(error)Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 139–141why, one step back139 }140}141Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 142why, one step back142impl Deref for Error {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–148why, one step back144 fn deref(&self) -> &Self::Target {145 self.inner.error()146 }147}148Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 149why, one step back149impl DerefMut for Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 150–154why, one step back150 fn deref_mut(&mut self) -> &mut Self::Target {151 self.inner.error_mut()152 }153}154Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 155why, one step back155impl Debug for Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 156–188why, one step back156 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}188Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 189why, one step back189impl Display for Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 190–194why, one step back190 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {191 write!(f, "{}", self.inner.error())192 }193}194Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
lines 195–196why, one step back195unsafe impl Send for Error {}196unsafe impl Sync for Error {}Rename exception module to errorDavid Tolnaybefore adoption2000930
line 197why, one step back197Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 198why, one step back198impl Drop for Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 199–205why, one step back199 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)]Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84
line 206why, one step back206struct ErrorImpl<E> {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 207–234why, one step back207 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
line 236why, one step back236Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84
line 237why, one step back237impl ErrorImpl<()> {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–256why, one step back248 unsafe {249 mem::transmute(TraitObject {250 data: &mut self.error,251 vtable: self.vtable,252 })253 }254 }255}256Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 257why, one step back257/// Iterator of errors in an `Error`.Rename exception module to errorDavid Tolnaybefore adoption2000930
line 258why, one step back258pub 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–280why, 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() {Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 281why, one step back281 assert_eq!(mem::size_of::<Error>(), mem::size_of::<usize>());Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 282–286why, one step back282 }283284 #[allow(dead_code)]285 fn assert_exception_autotraits()286 whereRename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 287why, one step back287 Error: Unpin + Send + Sync + 'static,Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 288–296why, one step back288 {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–312why, 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));312Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 313why, one step back313 drop(Error::from(HasDrop(Box::new(has_dropped.clone()))));Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 314–317why, one step back314315 assert!(*has_dropped.lock().unwrap());316 }317}