error.rs
This file
Path
src/error.rs
606 lines · 17.3 KiB · Rust
Last changed by
Format with rustfmt 2019-09-08David Tolnaybefore adoptiona727067
History of this fileTake it
Move backtrace capture to backtrace module and macroDavid Tolnaybefore adoptionebd9101
line 1why, one step back1use crate::backtrace::Backtrace;Add context method to ErrorDavid Tolnaybefore adoption41fde4c
line 2why, one step back2use crate::context::ContextError;Rename exception module to errorDavid Tolnaybefore adoption2000930
line 3why, one step back3use std::any::TypeId;Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 4why, one step back4use std::error::Error as StdError;Rename exception module to errorDavid Tolnaybefore adoption2000930
line 5why, one step back5use std::fmt::{self, Debug, Display};Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f
line 6why, one step back6use std::mem::{self, ManuallyDrop};Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 7–9why, one step back7use std::ops::{Deref, DerefMut};8use std::ptr;9Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 10why, one step back10/// The `Error` type, a wrapper around a dynamic error type.Rename exception module to errorDavid Tolnaybefore adoption2000930
line 11why, one step back11///Touch up documentation on Error structDavid Tolnaybefore adoptiona8ce6e4
line 12why, one step back12/// `Error` works a lot like `Box<dyn std::error::Error>`, but with theseWrap comments to 80 columnsDavid Tolnaybefore adoption9745066
line 13why, one step back13/// differences:Rename exception module to errorDavid Tolnaybefore adoption2000930
line 14why, one step back14///Touch up documentation on Error structDavid Tolnaybefore adoptiona8ce6e4
lines 15–19why, one step back15/// - `Error` requires that the error is `Send`, `Sync`, and `'static`.16/// - `Error` guarantees that a backtrace is available, even if the underlying17/// error type does not provide one.18/// - `Error` is represented as a narrow pointer — exactly one word in19/// size instead of two.Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 20why, one step back20pub struct Error {Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f
line 21why, one step back21 inner: ManuallyDrop<Box<ErrorImpl<()>>>,Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 22–23why, one step back22}23Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 24why, one step back24impl Error {Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 25why, one step back25 /// Create a new error object from any error type.Rename exception module to errorDavid Tolnaybefore adoption2000930
line 26why, one step back26 ///Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066
lines 27–28why, one step back27 /// The error type must be threadsafe and `'static`, so that the `Error`28 /// will be as well.Rename exception module to errorDavid Tolnaybefore adoption2000930
line 29why, one step back29 ///Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066
lines 30–31why, one step back30 /// If the error type does not provide a backtrace, a backtrace will be31 /// created here to ensure that a backtrace exists.Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337
line 32why, one step back32 pub fn new<E>(error: E) -> SelfRename exception module to errorDavid Tolnaybefore adoption2000930
line 33why, one step back33 whereImport std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 34why, one step back34 E: StdError + Send + Sync + 'static,Rename exception module to errorDavid Tolnaybefore adoption2000930
line 35why, one step back35 {Move Error::new backtrace capture to backtrace_if_absent macroDavid Tolnaybefore adoptioneaa819d
line 36why, one step back36 let backtrace = backtrace_if_absent!(error);Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9
lines 37–38why, one step back37 Error::from_std(error, backtrace)38 }Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298
line 39why, one step back39Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9
lines 40–45why, one step back40 pub(crate) fn from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self41 where42 E: StdError + Send + Sync + 'static,43 {44 let type_id = TypeId::of::<E>();45Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298
line 46why, one step back46 // Safety: passing typeid of the right type E.Format with rustfmt 2019-09-08David Tolnaybefore adoption2a9e5b6
line 47why, one step back47 unsafe { Error::construct(error, type_id, backtrace) }Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 48–49why, one step back48 }49Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9
line 50why, one step back50 pub(crate) fn from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> SelfRename exception module to errorDavid Tolnaybefore adoption2000930
lines 51–53why, one step back51 where52 M: Display + Debug + Send + Sync + 'static,53 {Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298
lines 54–58why, one step back54 let error = MessageError(message);55 let type_id = TypeId::of::<M>();5657 // Safety: MessageError is repr(transparent) so MessageError<M> has the58 // same layout as the typeid specifies.Format with rustfmt 2019-09-08David Tolnaybefore adoption2a9e5b6
line 59why, one step back59 unsafe { Error::construct(error, type_id, backtrace) }Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 60–61why, one step back60 }61Merge pull request #8 from dtolnay/optionDavid Tolnaybefore adoption240cc83
lines 62–73why, one step back62 pub(crate) fn from_display<M>(message: M, backtrace: Option<Backtrace>) -> Self63 where64 M: Display + Send + Sync + 'static,65 {66 let error = DisplayError(message);67 let type_id = TypeId::of::<M>();6869 // Safety: DisplayError is repr(transparent) so DisplayError<M> has the70 // same layout as the typeid specifies.71 unsafe { Error::construct(error, type_id, backtrace) }72 }73Move Error::new backtrace capture to backtrace_if_absent macroDavid Tolnaybefore adoptioneaa819d
lines 74–75why, one step back74 // Takes backtrace as argument rather than capturing it here so that the75 // user sees one fewer layer of wrapping noise in the backtrace.Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298
lines 76–79why, one step back76 //77 // Unsafe because the type represented by type_id must have the same layout78 // as E or else we allow invalid downcasts.79 unsafe fn construct<E>(error: E, type_id: TypeId, backtrace: Option<Backtrace>) -> SelfRename exception module to errorDavid Tolnaybefore adoption2000930
line 80why, one step back80 whereImport std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 81why, one step back81 E: StdError + Send + Sync + 'static,Rename exception module to errorDavid Tolnaybefore adoption2000930
line 82why, one step back82 {Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298
line 83why, one step back83 let vtable = &ErrorVTable {Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f
line 84why, one step back84 object_drop: object_drop::<E>,Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608
line 85why, one step back85 object_drop_front: object_drop_front::<E>,Rename vtable object ref and mut methods that are no longer raw ptrDavid Tolnaybefore adoptiond57f80c
lines 86–87why, one step back86 object_ref: object_ref::<E>,87 object_mut: object_mut::<E>,Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
line 88why, one step back88 object_boxed: object_boxed::<E>,Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298
lines 89–93why, one step back89 };90 let inner = Box::new(ErrorImpl {91 vtable,92 type_id,93 backtrace,Merge pull request #16 from johnschug/masterDavid Tolnaybefore adoptioneeaf2ef
line 94why, one step back94 _error: error,Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298
line 95why, one step back95 });Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f
lines 96–98why, one step back96 let erased = mem::transmute::<Box<ErrorImpl<E>>, Box<ErrorImpl<()>>>(inner);97 let inner = ManuallyDrop::new(erased);98 Error { inner }Add context method to ErrorDavid Tolnaybefore adoption41fde4c
lines 99–101why, one step back99 }100101 /// Wrap the error value with additional context.Link to Context trait from Error::context methodDavid Tolnaybefore adoption61e587f
lines 102–105why, one step back102 ///103 /// For attaching context to a `Result` as it is propagated, the104 /// [`Context`][crate::Context] extension trait may be more convenient than105 /// this function.Explain the purpose of Error::contextDavid Tolnaybefore adoption896dd7a
lines 106–127why, one step back106 ///107 /// The primary reason to use `error.context(...)` instead of108 /// `result.context(...)` via the `Context` trait would be if the context109 /// needs to depend on some data held by the underlying error:110 ///111 /// ```112 /// # use std::fmt::{self, Debug, Display};113 /// #114 /// # type T = ();115 /// #116 /// # impl std::error::Error for ParseError {}117 /// # impl Debug for ParseError {118 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {119 /// # unimplemented!()120 /// # }121 /// # }122 /// # impl Display for ParseError {123 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {124 /// # unimplemented!()125 /// # }126 /// # }127 /// #Clean up Error::context example using anyhow ResultDavid Tolnaybefore adoptionf8457fb
line 128why, one step back128 /// use anyhow::Result;Explain the purpose of Error::contextDavid Tolnaybefore adoption896dd7a
lines 129–143why, one step back129 /// use std::fs::File;130 /// use std::path::Path;131 ///132 /// struct ParseError {133 /// line: usize,134 /// column: usize,135 /// }136 ///137 /// fn parse_impl(file: File) -> Result<T, ParseError> {138 /// # const IGNORE: &str = stringify! {139 /// ...140 /// # };141 /// # unimplemented!()142 /// }143 ///Clean up Error::context example using anyhow ResultDavid Tolnaybefore adoptionf8457fb
line 144why, one step back144 /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {Explain the purpose of Error::contextDavid Tolnaybefore adoption896dd7a
lines 145–154why, one step back145 /// let file = File::open(&path)?;146 /// parse_impl(file).map_err(|error| {147 /// let context = format!(148 /// "only the first {} lines of {} are valid",149 /// error.line, path.as_ref().display(),150 /// );151 /// anyhow::Error::new(error).context(context)152 /// })153 /// }154 /// ```Add context method to ErrorDavid Tolnaybefore adoption41fde4c
lines 155–158why, one step back155 pub fn context<C>(self, context: C) -> Self156 where157 C: Display + Send + Sync + 'static,158 {Change Error::from calls to Error::new to cut one level of noise from backtracesDavid Tolnaybefore adoption2c7d3ca
line 159why, one step back159 Error::new(ContextError {Add context method to ErrorDavid Tolnaybefore adoption41fde4c
lines 160–162why, one step back160 error: self,161 context,162 })Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 163–164why, one step back163 }164Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 165why, one step back165 /// Get the backtrace for this Error.Detect nightly and only expose backtrace if availableDavid Tolnaybefore adoption270ea5e
lines 166–169why, one step back166 ///167 /// Backtraces are only available on the nightly channel. Tracking issue:168 /// [rust-lang/rust#53487][tracking].169 ///Mention env var in Error::backtrace documentationDavid Tolnaybefore adoption4119806
lines 170–174why, one step back170 /// In order for the backtrace to be meaningful, the environment variable171 /// `RUST_LIB_BACKTRACE=1` must be defined. Backtraces are somewhat172 /// expensive to capture in Rust, so we don't necessarily want to be173 /// capturing them all over the place all the time.174 ///Detect nightly and only expose backtrace if availableDavid Tolnaybefore adoption270ea5e
lines 175–176why, one step back175 /// [tracking]: https://github.com/rust-lang/rust/issues/53487176 #[cfg(backtrace)]Rename exception module to errorDavid Tolnaybefore adoption2000930
line 177why, one step back177 pub fn backtrace(&self) -> &Backtrace {Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
line 178why, one step back178 self.inner.backtrace()Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 179–180why, one step back179 }180Rename Errors to ChainDavid Tolnaybefore adoptionf972193
line 181why, one step back181 /// An iterator of the chain of source errors contained by this Error.Rename exception module to errorDavid Tolnaybefore adoption2000930
line 182why, one step back182 ///Rename Errors to ChainDavid Tolnaybefore adoptionf972193
line 183why, one step back183 /// This iterator will visit every error in the cause chain of this errorWrap comments to 80 columnsDavid Tolnaybefore adoption9745066
lines 184–185why, one step back184 /// object, beginning with the error that this error object was created185 /// from.Add example of Error::chainDavid Tolnaybefore adoptiond159b79
lines 186–201why, one step back186 ///187 /// # Example188 ///189 /// ```190 /// use anyhow::Error;191 /// use std::io;192 ///193 /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {194 /// for cause in error.chain() {195 /// if let Some(io_error) = cause.downcast_ref::<io::Error>() {196 /// return Some(io_error.kind());197 /// }198 /// }199 /// None200 /// }201 /// ```Rename Errors to ChainDavid Tolnaybefore adoptionf972193
line 202why, one step back202 pub fn chain(&self) -> Chain {Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
line 203why, one step back203 self.inner.chain()Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 204–205why, one step back204 }205Add Error::root_cause accessorDavid Tolnaybefore adoption1ea72bb
lines 206–219why, one step back206 /// The lowest level cause of this error — this error's cause's207 /// cause's cause etc.208 ///209 /// The root cause is the last error in the iterator produced by210 /// [`chain()`][Error::chain].211 pub fn root_cause(&self) -> &(dyn StdError + 'static) {212 let mut chain = self.chain();213 let mut root_cause = chain.next().unwrap();214 for cause in chain {215 root_cause = cause;216 }217 root_cause218 }219Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 220why, one step back220 /// Returns `true` if `E` is the type wrapped by this error object.Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 221–224why, one step back221 pub fn is<E>(&self) -> bool222 where223 E: Display + Debug + Send + Sync + 'static,224 {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 225–227why, one step back225 TypeId::of::<E>() == self.inner.type_id226 }227Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 228why, one step back228 /// Attempt to downcast the error object to a concrete type.Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337
line 229why, one step back229 pub fn downcast<E>(self) -> Result<E, Self>Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 230–232why, one step back230 where231 E: Display + Debug + Send + Sync + 'static,232 {Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608
lines 233–234why, one step back233 if self.is::<E>() {234 let outer = ManuallyDrop::new(self);Rename exception module to errorDavid Tolnaybefore adoption2000930
line 235why, one step back235 unsafe {Format with rustfmt 2019-09-08David Tolnaybefore adoptiona727067
lines 236–238why, one step back236 let error = ptr::read(237 outer.inner.error() as *const (dyn StdError + Send + Sync) as *const E238 );Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608
lines 239–241why, one step back239 let inner = ptr::read(&outer.inner);240 let erased = ManuallyDrop::into_inner(inner);241 (erased.vtable.object_drop_front)(erased);Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 242–248why, one step back242 Ok(error)243 }244 } else {245 Err(self)246 }247 }248Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 249why, one step back249 /// Downcast this error object by reference.Add example to Error::downcast_refDavid Tolnaybefore adoption0c21b7a
lines 250–284why, one step back250 ///251 /// # Example252 ///253 /// ```254 /// # use anyhow::anyhow;255 /// # use std::fmt::{self, Display};256 /// # use std::task::Poll;257 /// #258 /// # #[derive(Debug)]259 /// # enum DataStoreError {260 /// # Censored(()),261 /// # }262 /// #263 /// # impl Display for DataStoreError {264 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {265 /// # unimplemented!()266 /// # }267 /// # }268 /// #269 /// # impl std::error::Error for DataStoreError {}270 /// #271 /// # const REDACTED_CONTENT: () = ();272 /// #273 /// # let error = anyhow!("...");274 /// # let root_cause = &error;275 /// #276 /// # let ret =277 /// // If the error was caused by redaction, then return a tombstone instead278 /// // of the content.279 /// match root_cause.downcast_ref::<DataStoreError>() {280 /// Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),281 /// None => Err(error),282 /// }283 /// # ;284 /// ```Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 285–288why, one step back285 pub fn downcast_ref<E>(&self) -> Option<&E>286 where287 E: Display + Debug + Send + Sync + 'static,288 {Rename exception module to errorDavid Tolnaybefore adoption2000930
line 289why, one step back289 if self.is::<E>() {Format with rustfmt 2019-09-08David Tolnaybefore adoptiona727067
lines 290–292why, one step back290 Some(unsafe {291 &*(self.inner.error() as *const (dyn StdError + Send + Sync) as *const E)292 })Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 293–297why, one step back293 } else {294 None295 }296 }297Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 298why, one step back298 /// Downcast this error object by mutable reference.Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 299–302why, one step back299 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>300 where301 E: Display + Debug + Send + Sync + 'static,302 {Rename exception module to errorDavid Tolnaybefore adoption2000930
line 303why, one step back303 if self.is::<E>() {Format with rustfmt 2019-09-08David Tolnaybefore adoptiona727067
lines 304–306why, one step back304 Some(unsafe {305 &mut *(self.inner.error_mut() as *mut (dyn StdError + Send + Sync) as *mut E)306 })Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 307–311why, one step back307 } else {308 None309 }310 }311}Remove use of attributes on function parametersDavid Tolnaybefore adoptiona2d7e2f
line 312why, one step back312Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 313–316why, one step back313impl<E> From<E> for Error314where315 E: StdError + Send + Sync + 'static,316{Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337
line 317why, one step back317 fn from(error: E) -> Self {Capture backtraces earlierDavid Tolnaybefore adoptionc06155e
lines 318–319why, one step back318 let backtrace = backtrace_if_absent!(error);319 Error::from_std(error, backtrace)Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 320–322why, one step back320 }321}322Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 323why, one step back323impl Deref for Error {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 324why, one step back324 type Target = dyn StdError + Send + Sync + 'static;Remove as_dyn_error methods from ErrorDavid Tolnaybefore adoption73c7283
line 325why, one step back325Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 326–330why, one step back326 fn deref(&self) -> &Self::Target {327 self.inner.error()328 }329}330Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 331why, one step back331impl DerefMut for Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 332–336why, one step back332 fn deref_mut(&mut self) -> &mut Self::Target {333 self.inner.error_mut()334 }335}336Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 337why, one step back337impl Debug for Error {Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
lines 338–339why, one step back338 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {339 self.inner.debug(formatter)Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 340–342why, one step back340 }341}342Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 343why, one step back343impl Display for Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 344–348why, one step back344 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {345 write!(f, "{}", self.inner.error())346 }347}348Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
lines 349–350why, one step back349unsafe impl Send for Error {}350unsafe impl Sync for Error {}Rename exception module to errorDavid Tolnaybefore adoption2000930
line 351why, one step back351Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 352why, one step back352impl Drop for Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
line 353why, one step back353 fn drop(&mut self) {Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f
line 354why, one step back354 unsafe {Ptr read only needs a const ptrDavid Tolnaybefore adoption83f63a6
line 355why, one step back355 let inner = ptr::read(&self.inner);Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f
lines 356–358why, one step back356 let erased = ManuallyDrop::into_inner(inner);357 (erased.vtable.object_drop)(erased);358 }Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 359–361why, one step back359 }360}361Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a
line 362why, one step back362struct ErrorVTable {Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f
line 363why, one step back363 object_drop: unsafe fn(Box<ErrorImpl<()>>),Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608
line 364why, one step back364 object_drop_front: unsafe fn(Box<ErrorImpl<()>>),Rename vtable object ref and mut methods that are no longer raw ptrDavid Tolnaybefore adoptiond57f80c
lines 365–366why, one step back365 object_ref: unsafe fn(&ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static),366 object_mut: unsafe fn(&mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static),Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
line 367why, one step back367 object_boxed: unsafe fn(Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>,Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f
lines 368–373why, one step back368}369370unsafe fn object_drop<E>(e: Box<ErrorImpl<()>>) {371 // Cast back to ErrorImpl<E> so that the allocator receives the correct372 // Layout to deallocate the Box's memory.373 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e);Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608
lines 374–381why, one step back374 drop(unerased);375}376377unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>) {378 // Drop the fields of ErrorImpl other than E as well as the Box allocation,379 // without dropping E itself. This is used by downcast after doing a380 // ptr::read to take ownership of the E.381 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<ManuallyDrop<E>>>>(e);Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f
line 382why, one step back382 drop(unerased);Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a
lines 383–384why, one step back383}384Rename vtable object ref and mut methods that are no longer raw ptrDavid Tolnaybefore adoptiond57f80c
line 385why, one step back385unsafe fn object_ref<E>(e: &ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static)Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a
lines 386–388why, one step back386where387 E: StdError + Send + Sync + 'static,388{Merge pull request #16 from johnschug/masterDavid Tolnaybefore adoptioneeaf2ef
line 389why, one step back389 &(*(e as *const ErrorImpl<()> as *const ErrorImpl<E>))._errorMerge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a
lines 390–391why, one step back390}391Rename vtable object ref and mut methods that are no longer raw ptrDavid Tolnaybefore adoptiond57f80c
line 392why, one step back392unsafe fn object_mut<E>(e: &mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static)Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a
lines 393–395why, one step back393where394 E: StdError + Send + Sync + 'static,395{Merge pull request #16 from johnschug/masterDavid Tolnaybefore adoptioneeaf2ef
line 396why, one step back396 &mut (*(e as *mut ErrorImpl<()> as *mut ErrorImpl<E>))._errorMerge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a
lines 397–398why, one step back397}398Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
lines 399–405why, one step back399unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>400where401 E: StdError + Send + Sync + 'static,402{403 mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e)404}405Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 406–407why, one step back406// repr C to ensure that `E` remains in the final position407#[repr(C)]Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84
line 408why, one step back408struct ErrorImpl<E> {Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a
line 409why, one step back409 vtable: &'static ErrorVTable,Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 410–411why, one step back410 type_id: TypeId,411 backtrace: Option<Backtrace>,Merge pull request #16 from johnschug/masterDavid Tolnaybefore adoptioneeaf2ef
lines 412–413why, one step back412 // NOTE: Don't use directly. Use only through vtable. Erased type may have different alignment.413 _error: E,Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 414–416why, one step back414}415416#[repr(transparent)]Remove trait bounds from MessageError structDavid Tolnaybefore adoptioneac05d1
line 417why, one step back417struct MessageError<M>(M);Rename exception module to errorDavid Tolnaybefore adoption2000930
line 418why, one step back418Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 419–422why, one step back419impl<M> Debug for MessageError<M>420where421 M: Display + Debug,422{Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 423–427why, one step back423 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {424 Debug::fmt(&self.0, f)425 }426}427Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 428–431why, one step back428impl<M> Display for MessageError<M>429where430 M: Display + Debug,431{Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 432–436why, one step back432 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {433 Display::fmt(&self.0, f)434 }435}436Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
line 437why, one step back437impl<M> StdError for MessageError<M> where M: Display + Debug + 'static {}Merge pull request #8 from dtolnay/optionDavid Tolnaybefore adoption240cc83
lines 438–460why, one step back438439#[repr(transparent)]440struct DisplayError<M>(M);441442impl<M> Debug for DisplayError<M>443where444 M: Display,445{446 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {447 Display::fmt(&self.0, f)448 }449}450451impl<M> Display for DisplayError<M>452where453 M: Display,454{455 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {456 Display::fmt(&self.0, f)457 }458}459460impl<M> StdError for DisplayError<M> where M: Display + 'static {}Rename exception module to errorDavid Tolnaybefore adoption2000930
line 461why, one step back461Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452
lines 462–467why, one step back462impl<E> ErrorImpl<E> {463 fn erase(&self) -> &ErrorImpl<()> {464 unsafe { &*(self as *const ErrorImpl<E> as *const ErrorImpl<()>) }465 }466}467Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84
line 468why, one step back468impl ErrorImpl<()> {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 469why, one step back469 fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {Rename vtable object ref and mut methods that are no longer raw ptrDavid Tolnaybefore adoptiond57f80c
line 470why, one step back470 unsafe { &*(self.vtable.object_ref)(self) }Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 471–472why, one step back471 }472Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 473why, one step back473 fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {Rename vtable object ref and mut methods that are no longer raw ptrDavid Tolnaybefore adoptiond57f80c
line 474why, one step back474 unsafe { &mut *(self.vtable.object_mut)(self) }Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
lines 475–531why, one step back475 }476477 #[cfg(backtrace)]478 fn backtrace(&self) -> &Backtrace {479 // This unwrap can only panic if the underlying error's backtrace method480 // is nondeterministic, which would only happen in maliciously481 // constructed code.482 self.backtrace483 .as_ref()484 .or_else(|| self.error().backtrace())485 .expect("backtrace capture failed")486 }487488 fn chain(&self) -> Chain {489 Chain {490 next: Some(self.error()),491 }492 }493494 fn debug(&self, f: &mut fmt::Formatter) -> fmt::Result {495 writeln!(f, "{}", self.error())?;496497 let mut chain = self.chain().skip(1).enumerate().peekable();498 if let Some((n, error)) = chain.next() {499 write!(f, "\nCaused by:\n ")?;500 if chain.peek().is_some() {501 write!(f, "{}: ", n)?;502 }503 writeln!(f, "{}", error)?;504 for (n, error) in chain {505 writeln!(f, " {}: {}", n, error)?;506 }507 }508509 #[cfg(backtrace)]510 {511 use std::backtrace::BacktraceStatus;512513 let backtrace = self.backtrace();514 match backtrace.status() {515 BacktraceStatus::Captured => {516 writeln!(f, "\n{}", backtrace)?;517 }518 BacktraceStatus::Disabled => {519 writeln!(520 f,521 "\nBacktrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace"522 )?;523 }524 _ => {}525 }526 }527528 Ok(())529 }530}531Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452
lines 532–539why, one step back532impl<E> StdError for ErrorImpl<E>533where534 E: StdError,535{536 #[cfg(backtrace)]537 fn backtrace(&self) -> Option<&Backtrace> {538 Some(self.erase().backtrace())539 }Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
line 540why, one step back540Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452
line 541why, one step back541 fn source(&self) -> Option<&(dyn StdError + 'static)> {Merge pull request #16 from johnschug/masterDavid Tolnaybefore adoptioneeaf2ef
line 542why, one step back542 self.erase().error().source()Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452
lines 543–545why, one step back543 }544}545Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
lines 546–550why, one step back546impl<E> Debug for ErrorImpl<E>547where548 E: Debug,549{550 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452
line 551why, one step back551 self.erase().debug(formatter)Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
lines 552–559why, one step back552 }553}554555impl<E> Display for ErrorImpl<E>556where557 E: Display,558{559 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {Merge pull request #16 from johnschug/masterDavid Tolnaybefore adoptioneeaf2ef
line 560why, one step back560 Display::fmt(&self.erase().error(), formatter)Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
lines 561–571why, one step back561 }562}563564impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {565 fn from(error: Error) -> Self {566 let outer = ManuallyDrop::new(error);567 unsafe {568 let inner = ptr::read(&outer.inner);569 let erased = ManuallyDrop::into_inner(inner);570 (erased.vtable.object_boxed)(erased)571 }Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 572–574why, one step back572 }573}574Rename Errors to ChainDavid Tolnaybefore adoptionf972193
line 575why, one step back575/// Iterator of a chain of source errors.Add example to Chain iteratorDavid Tolnaybefore adoptionfeb9f33
lines 576–593why, one step back576///577/// This type is the iterator returned by [`Error::chain`].578///579/// # Example580///581/// ```582/// use anyhow::Error;583/// use std::io;584///585/// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {586/// for cause in error.chain() {587/// if let Some(io_error) = cause.downcast_ref::<io::Error>() {588/// return Some(io_error.kind());589/// }590/// }591/// None592/// }593/// ```Rename Errors to ChainDavid Tolnaybefore adoptionf972193
line 594why, one step back594pub struct Chain<'a> {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 595why, one step back595 next: Option<&'a (dyn StdError + 'static)>,Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 596–597why, one step back596}597Rename Errors to ChainDavid Tolnaybefore adoptionf972193
line 598why, one step back598impl<'a> Iterator for Chain<'a> {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 599why, one step back599 type Item = &'a (dyn StdError + 'static);Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 600–606why, one step back600601 fn next(&mut self) -> Option<Self::Item> {602 let next = self.next.take()?;603 self.next = next.source();604 Some(next)605 }606}