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
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///Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066
lines 11–12why, one step back11/// `Error` functions a lot like `Box<dyn std::error::Error>`, with these12/// differences:Rename exception module to errorDavid Tolnaybefore adoption2000930
line 13why, one step back13///Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
lines 14–15why, one step back14/// - `Error` requires that the error is `Send`, `Sync`, and `'static`15/// - `Error` guarantees that a backtrace will exist, even if the error typeRename exception module to errorDavid Tolnaybefore adoption2000930
line 16why, one step back16/// did not provide oneRename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 17why, one step back17/// - `Error` is represented as a narrow pointer - exactly one word in size,Rename exception module to errorDavid Tolnaybefore adoption2000930
line 18why, one step back18/// instead of two.Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 19why, one step back19pub struct Error {Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84
line 20why, one step back20 inner: Box<ErrorImpl<()>>,Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 21–22why, one step back21}22Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 23why, one step back23impl Error {Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 24why, one step back24 /// Create a new error object from any error type.Rename exception module to errorDavid Tolnaybefore adoption2000930
line 25why, one step back25 ///Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066
lines 26–27why, one step back26 /// The error type must be threadsafe and `'static`, so that the `Error`27 /// will be as well.Rename exception module to errorDavid Tolnaybefore adoption2000930
line 28why, one step back28 ///Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066
lines 29–30why, one step back29 /// If the error type does not provide a backtrace, a backtrace will be30 /// created here to ensure that a backtrace exists.Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 31why, one step back31 pub fn new<E>(error: E) -> ErrorRename exception module to errorDavid Tolnaybefore adoption2000930
line 32why, one step back32 whereImport std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 33why, one step back33 E: StdError + Send + Sync + 'static,Rename exception module to errorDavid Tolnaybefore adoption2000930
line 34why, one step back34 {Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 35why, one step back35 Error::construct(error, TypeId::of::<E>())Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 36–38why, one step back36 }3738 #[doc(hidden)]Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 39why, one step back39 pub fn new_adhoc<M>(message: M) -> ErrorRename exception module to errorDavid Tolnaybefore adoption2000930
lines 40–42why, one step back40 where41 M: Display + Debug + Send + Sync + 'static,42 {Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 43why, one step back43 Error::construct(MessageError(message), TypeId::of::<M>())Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 44–45why, one step back44 }45Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 46why, one step back46 fn construct<E>(error: E, type_id: TypeId) -> ErrorRename exception module to errorDavid Tolnaybefore adoption2000930
line 47why, one step back47 whereImport std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 48why, one step back48 E: StdError + Send + Sync + 'static,Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 49–54why, one step back49 {50 unsafe {51 let backtrace = match error.backtrace() {52 Some(_) => None,53 None => Some(Backtrace::capture()),54 };Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 55why, one step back55 let obj: TraitObject = mem::transmute(&error as &dyn StdError);Rename exception module to errorDavid Tolnaybefore adoption2000930
line 56why, one step back56 let vtable = obj.vtable;Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84
line 57why, one step back57 let inner = ErrorImpl {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 58–62why, one step back58 vtable,59 type_id,60 backtrace,61 error,62 };Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 63why, one step back63 Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 64–68why, one step back64 inner: mem::transmute(Box::new(inner)),65 }66 }67 }68Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 69why, one step back69 /// View this error object as the underlying error.Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383
line 70why, one step back70 pub fn as_dyn_error(&self) -> &(dyn StdError + Send + Sync + 'static) {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 71–73why, one step back71 &**self72 }73Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 74why, one step back74 /// View this error object as the underlying error, mutably.Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383
line 75why, one step back75 pub fn as_dyn_error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 76–78why, one step back76 &mut **self77 }78Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 79why, one step back79 /// Get the backtrace for this Error.Rename exception module to errorDavid Tolnaybefore adoption2000930
line 80why, one step back80 pub fn backtrace(&self) -> &Backtrace {Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066
lines 81–83why, one step back81 // NB: this unwrap can only fail if the underlying error's backtrace82 // method is nondeterministic, which would only happen in maliciously83 // constructed codeRename exception module to errorDavid Tolnaybefore adoption2000930
lines 84–87why, one step back84 self.inner85 .backtrace86 .as_ref()87 .or_else(|| self.inner.error().backtrace())Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 88why, one step back88 .expect("backtrace capture failed")Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 89–90why, one step back89 }90Rename Errors to ChainDavid Tolnaybefore adoptionf972193
line 91why, one step back91 /// An iterator of the chain of source errors contained by this Error.Rename exception module to errorDavid Tolnaybefore adoption2000930
line 92why, one step back92 ///Rename Errors to ChainDavid Tolnaybefore adoptionf972193
line 93why, one step back93 /// This iterator will visit every error in the cause chain of this errorWrap comments to 80 columnsDavid Tolnaybefore adoption9745066
lines 94–95why, one step back94 /// object, beginning with the error that this error object was created95 /// from.Rename Errors to ChainDavid Tolnaybefore adoptionf972193
lines 96–97why, one step back96 pub fn chain(&self) -> Chain {97 Chain {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 98–101why, one step back98 next: Some(self.inner.error()),99 }100 }101Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 102why, one step back102 /// Returns `true` if `E` is the type wrapped by this error object.Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 103–106why, one step back103 pub fn is<E>(&self) -> bool104 where105 E: Display + Debug + Send + Sync + 'static,106 {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 107–109why, one step back107 TypeId::of::<E>() == self.inner.type_id108 }109Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 110why, one step back110 /// Attempt to downcast the error object to a concrete type.Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 111–114why, one step back111 pub fn downcast<E>(self) -> Result<E, Error>112 where113 E: Display + Debug + Send + Sync + 'static,114 {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 115–126why, one step back115 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 }126Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 127why, one step back127 /// Downcast this error object by reference.Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 128–131why, one step back128 pub fn downcast_ref<E>(&self) -> Option<&E>129 where130 E: Display + Debug + Send + Sync + 'static,131 {Rename exception module to errorDavid Tolnaybefore adoption2000930
line 132why, one step back132 if self.is::<E>() {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 133why, one step back133 unsafe { Some(&*(self.inner.error() as *const dyn StdError as *const E)) }Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 134–138why, one step back134 } else {135 None136 }137 }138Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 139why, one step back139 /// Downcast this error object by mutable reference.Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 140–143why, one step back140 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>141 where142 E: Display + Debug + Send + Sync + 'static,143 {Rename exception module to errorDavid Tolnaybefore adoption2000930
line 144why, one step back144 if self.is::<E>() {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 145why, one step back145 unsafe { Some(&mut *(self.inner.error_mut() as *mut dyn StdError as *mut E)) }Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 146–151why, one step back146 } else {147 None148 }149 }150}151Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 152–155why, one step back152impl<E> From<E> for Error153where154 E: StdError + Send + Sync + 'static,155{Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
lines 156–157why, one step back156 fn from(error: E) -> Error {157 Error::new(error)Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 158–160why, one step back158 }159}160Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 161why, one step back161impl Deref for Error {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 162why, one step back162 type Target = dyn StdError + Send + Sync + 'static;Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 163–167why, one step back163 fn deref(&self) -> &Self::Target {164 self.inner.error()165 }166}167Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 168why, one step back168impl DerefMut for Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 169–173why, one step back169 fn deref_mut(&mut self) -> &mut Self::Target {170 self.inner.error_mut()171 }172}173Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 174why, one step back174impl Debug for Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 175–177why, one step back175 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {176 writeln!(f, "{}", self.inner.error())?;177Rename Errors to ChainDavid Tolnaybefore adoptionf972193
line 178why, one step back178 let mut errors = self.chain().skip(1).enumerate();Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 179–196why, one step back179180 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,Un-wrap backtrace disabled message for easier greppingDavid Tolnaybefore adoptiondf575e5
line 197why, one step back197 "\nbacktrace disabled; run with RUST_BACKTRACE=1 environment variable to display a backtrace"Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 198–206why, one step back198 )?;199 }200 _ => {}201 }202203 Ok(())204 }205}206Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 207why, one step back207impl Display for Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 208–212why, one step back208 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {209 write!(f, "{}", self.inner.error())210 }211}212Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
lines 213–214why, one step back213unsafe impl Send for Error {}214unsafe impl Sync for Error {}Rename exception module to errorDavid Tolnaybefore adoption2000930
line 215why, one step back215Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 216why, one step back216impl Drop for Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 217–223why, one step back217 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)]Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84
line 224why, one step back224struct ErrorImpl<E> {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 225–238why, one step back225 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)]Remove trait bounds from MessageError structDavid Tolnaybefore adoptioneac05d1
line 239why, one step back239struct MessageError<M>(M);Rename exception module to errorDavid Tolnaybefore adoption2000930
line 240why, one step back240Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 241–244why, one step back241impl<M> Debug for MessageError<M>242where243 M: Display + Debug,244{Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 245–249why, one step back245 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {246 Debug::fmt(&self.0, f)247 }248}249Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 250–253why, one step back250impl<M> Display for MessageError<M>251where252 M: Display + Debug,253{Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 254–258why, one step back254 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {255 Display::fmt(&self.0, f)256 }257}258Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
line 259why, one step back259impl<M> StdError for MessageError<M> where M: Display + Debug + 'static {}Rename exception module to errorDavid Tolnaybefore adoption2000930
line 260why, one step back260Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84
line 261why, one step back261impl ErrorImpl<()> {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 262why, one step back262 fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 263–270why, one step back263 unsafe {264 mem::transmute(TraitObject {265 data: &self.error,266 vtable: self.vtable,267 })268 }269 }270Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 271why, one step back271 fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 272–280why, one step back272 unsafe {273 mem::transmute(TraitObject {274 data: &mut self.error,275 vtable: self.vtable,276 })277 }278 }279}280Rename Errors to ChainDavid Tolnaybefore adoptionf972193
lines 281–282why, one step back281/// Iterator of a chain of source errors.282pub struct Chain<'a> {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 283why, one step back283 next: Option<&'a (dyn StdError + 'static)>,Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 284–285why, one step back284}285Rename Errors to ChainDavid Tolnaybefore adoptionf972193
line 286why, one step back286impl<'a> Iterator for Chain<'a> {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 287why, one step back287 type Item = &'a (dyn StdError + 'static);Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 288–303why, one step back288289 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]Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 304why, one step back304 fn size_of_error() {Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 305why, one step back305 assert_eq!(mem::size_of::<Error>(), mem::size_of::<usize>());Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 306–308why, one step back306 }307308 #[allow(dead_code)]Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 309why, one step back309 fn assert_error_autotraits()Rename exception module to errorDavid Tolnaybefore adoption2000930
line 310why, one step back310 whereRename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 311why, one step back311 Error: Unpin + Send + Sync + 'static,Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 312–320why, one step back312 {313 }314315 #[test]316 fn destructors_work() {317 use std::sync::*;318319 #[derive(Debug)]320 struct HasDrop(Box<Arc<Mutex<bool>>>);Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 321why, one step back321 impl StdError for HasDrop {}Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 322–336why, one step back322 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));336Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 337why, one step back337 drop(Error::from(HasDrop(Box::new(has_dropped.clone()))));Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 338–341why, one step back338339 assert!(*has_dropped.lock().unwrap());340 }341}