Skip to content
Myr

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 file

Take it

Move backtrace capture to backtrace module and macroDavid Tolnaybefore adoptionebd9101

line 1why, one step back
1use crate::backtrace::Backtrace;

Add context method to ErrorDavid Tolnaybefore adoption41fde4c

line 2why, one step back
2use crate::context::ContextError;

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 3why, one step back
3use std::any::TypeId;

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 4why, one step back
4use std::error::Error as StdError;

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 5why, one step back
5use std::fmt::{self, Debug, Display};

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

line 6why, one step back
6use std::mem::{self, ManuallyDrop};

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 7–9why, one step back
7use std::ops::{Deref, DerefMut};
8use std::ptr;9

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 10why, one step back
10/// The `Error` type, a wrapper around a dynamic error type.

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 11why, one step back
11///

Touch up documentation on Error structDavid Tolnaybefore adoptiona8ce6e4

line 12why, one step back
12/// `Error` works a lot like `Box<dyn std::error::Error>`, but with these

Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066

line 13why, one step back
13/// differences:

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 14why, one step back
14///

Touch up documentation on Error structDavid Tolnaybefore adoptiona8ce6e4

lines 15–19why, one step back
15/// - `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 &mdash; exactly one word in19/// size instead of two.

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 20why, one step back
20pub struct Error {

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

line 21why, one step back
21 inner: ManuallyDrop<Box<ErrorImpl<()>>>,

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 22–23why, one step back
22}
23

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 24why, one step back
24impl Error {

Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c

line 25why, one step back
25 /// Create a new error object from any error type.

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 26why, one step back
26 ///

Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066

lines 27–28why, one step back
27 /// 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 back
29 ///

Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066

lines 30–31why, one step back
30 /// If the error type does not provide a backtrace, a backtrace will be
31 /// created here to ensure that a backtrace exists.

Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337

line 32why, one step back
32 pub fn new<E>(error: E) -> Self

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 33why, one step back
33 where

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 34why, one step back
34 E: StdError + Send + Sync + 'static,

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 35why, one step back
35 {

Move Error::new backtrace capture to backtrace_if_absent macroDavid Tolnaybefore adoptioneaa819d

line 36why, one step back
36 let backtrace = backtrace_if_absent!(error);

Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9

lines 37–38why, one step back
37 Error::from_std(error, backtrace)
38 }

Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298

line 39why, one step back
39

Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9

lines 40–45why, one step back
40 pub(crate) fn from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self
41 where42 E: StdError + Send + Sync + 'static,43 {44 let type_id = TypeId::of::<E>();45

Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298

line 46why, one step back
46 // Safety: passing typeid of the right type E.

Format with rustfmt 2019-09-08David Tolnaybefore adoption2a9e5b6

line 47why, one step back
47 unsafe { Error::construct(error, type_id, backtrace) }

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 48–49why, one step back
48 }
49

Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9

line 50why, one step back
50 pub(crate) fn from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> Self

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 51–53why, one step back
51 where
52 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 back
54 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 back
59 unsafe { Error::construct(error, type_id, backtrace) }

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 60–61why, one step back
60 }
61

Merge pull request #8 from dtolnay/optionDavid Tolnaybefore adoption240cc83

lines 62–73why, one step back
62 pub(crate) fn from_display<M>(message: M, backtrace: Option<Backtrace>) -> Self
63 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 }73

Move Error::new backtrace capture to backtrace_if_absent macroDavid Tolnaybefore adoptioneaa819d

lines 74–75why, one step back
74 // Takes backtrace as argument rather than capturing it here so that the
75 // 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 back
76 //
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>) -> Self

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 80why, one step back
80 where

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 81why, one step back
81 E: StdError + Send + Sync + 'static,

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 82why, one step back
82 {

Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298

line 83why, one step back
83 let vtable = &ErrorVTable {

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

line 84why, one step back
84 object_drop: object_drop::<E>,

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

line 85why, one step back
85 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 back
86 object_ref: object_ref::<E>,
87 object_mut: object_mut::<E>,

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

line 88why, one step back
88 object_boxed: object_boxed::<E>,

Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298

lines 89–93why, one step back
89 };
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 back
94 _error: error,

Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298

line 95why, one step back
95 });

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

lines 96–98why, one step back
96 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 back
99 }
100101 /// Wrap the error value with additional context.

Link to Context trait from Error::context methodDavid Tolnaybefore adoption61e587f

lines 102–105why, one step back
102 ///
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 back
106 ///
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 back
128 /// use anyhow::Result;

Explain the purpose of Error::contextDavid Tolnaybefore adoption896dd7a

lines 129–143why, one step back
129 /// 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 back
144 /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {

Explain the purpose of Error::contextDavid Tolnaybefore adoption896dd7a

lines 145–154why, one step back
145 /// 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 back
155 pub fn context<C>(self, context: C) -> Self
156 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 back
159 Error::new(ContextError {

Add context method to ErrorDavid Tolnaybefore adoption41fde4c

lines 160–162why, one step back
160 error: self,
161 context,162 })

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 163–164why, one step back
163 }
164

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 165why, one step back
165 /// Get the backtrace for this Error.

Detect nightly and only expose backtrace if availableDavid Tolnaybefore adoption270ea5e

lines 166–169why, one step back
166 ///
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 back
170 /// In order for the backtrace to be meaningful, the environment variable
171 /// `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 back
175 /// [tracking]: https://github.com/rust-lang/rust/issues/53487
176 #[cfg(backtrace)]

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 177why, one step back
177 pub fn backtrace(&self) -> &Backtrace {

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

line 178why, one step back
178 self.inner.backtrace()

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 179–180why, one step back
179 }
180

Rename Errors to ChainDavid Tolnaybefore adoptionf972193

line 181why, one step back
181 /// An iterator of the chain of source errors contained by this Error.

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 182why, one step back
182 ///

Rename Errors to ChainDavid Tolnaybefore adoptionf972193

line 183why, one step back
183 /// This iterator will visit every error in the cause chain of this error

Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066

lines 184–185why, one step back
184 /// object, beginning with the error that this error object was created
185 /// from.

Add example of Error::chainDavid Tolnaybefore adoptiond159b79

lines 186–201why, one step back
186 ///
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 back
202 pub fn chain(&self) -> Chain {

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

line 203why, one step back
203 self.inner.chain()

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 204–205why, one step back
204 }
205

Add Error::root_cause accessorDavid Tolnaybefore adoption1ea72bb

lines 206–219why, one step back
206 /// The lowest level cause of this error &mdash; this error's cause's
207 /// 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 }219

Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c

line 220why, one step back
220 /// 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 back
221 pub fn is<E>(&self) -> bool
222 where223 E: Display + Debug + Send + Sync + 'static,224 {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 225–227why, one step back
225 TypeId::of::<E>() == self.inner.type_id
226 }227

Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c

line 228why, one step back
228 /// Attempt to downcast the error object to a concrete type.

Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337

line 229why, one step back
229 pub fn downcast<E>(self) -> Result<E, Self>

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

lines 230–232why, one step back
230 where
231 E: Display + Debug + Send + Sync + 'static,232 {

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

lines 233–234why, one step back
233 if self.is::<E>() {
234 let outer = ManuallyDrop::new(self);

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 235why, one step back
235 unsafe {

Format with rustfmt 2019-09-08David Tolnaybefore adoptiona727067

lines 236–238why, one step back
236 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 back
239 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 back
242 Ok(error)
243 }244 } else {245 Err(self)246 }247 }248

Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c

line 249why, one step back
249 /// Downcast this error object by reference.

Add example to Error::downcast_refDavid Tolnaybefore adoption0c21b7a

lines 250–284why, one step back
250 ///
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 back
285 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 back
289 if self.is::<E>() {

Format with rustfmt 2019-09-08David Tolnaybefore adoptiona727067

lines 290–292why, one step back
290 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 back
293 } else {
294 None295 }296 }297

Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c

line 298why, one step back
298 /// Downcast this error object by mutable reference.

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

lines 299–302why, one step back
299 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 back
303 if self.is::<E>() {

Format with rustfmt 2019-09-08David Tolnaybefore adoptiona727067

lines 304–306why, one step back
304 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 back
307 } else {
308 None309 }310 }311}

Remove use of attributes on function parametersDavid Tolnaybefore adoptiona2d7e2f

line 312why, one step back
312

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

lines 313–316why, one step back
313impl<E> From<E> for Error
314where315 E: StdError + Send + Sync + 'static,316{

Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337

line 317why, one step back
317 fn from(error: E) -> Self {

Capture backtraces earlierDavid Tolnaybefore adoptionc06155e

lines 318–319why, one step back
318 let backtrace = backtrace_if_absent!(error);
319 Error::from_std(error, backtrace)

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 320–322why, one step back
320 }
321}322

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 323why, one step back
323impl Deref for Error {

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 324why, one step back
324 type Target = dyn StdError + Send + Sync + 'static;

Remove as_dyn_error methods from ErrorDavid Tolnaybefore adoption73c7283

line 325why, one step back
325

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 326–330why, one step back
326 fn deref(&self) -> &Self::Target {
327 self.inner.error()328 }329}330

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 331why, one step back
331impl DerefMut for Error {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 332–336why, one step back
332 fn deref_mut(&mut self) -> &mut Self::Target {
333 self.inner.error_mut()334 }335}336

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 337why, one step back
337impl Debug for Error {

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 338–339why, one step back
338 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 back
340 }
341}342

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 343why, one step back
343impl Display for Error {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 344–348why, one step back
344 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
345 write!(f, "{}", self.inner.error())346 }347}348

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

lines 349–350why, one step back
349unsafe impl Send for Error {}
350unsafe impl Sync for Error {}

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 351why, one step back
351

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 352why, one step back
352impl Drop for Error {

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 353why, one step back
353 fn drop(&mut self) {

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

line 354why, one step back
354 unsafe {

Ptr read only needs a const ptrDavid Tolnaybefore adoption83f63a6

line 355why, one step back
355 let inner = ptr::read(&self.inner);

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

lines 356–358why, one step back
356 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 back
359 }
360}361

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

line 362why, one step back
362struct ErrorVTable {

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

line 363why, one step back
363 object_drop: unsafe fn(Box<ErrorImpl<()>>),

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

line 364why, one step back
364 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 back
365 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 back
367 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 back
368}
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 back
374 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 back
382 drop(unerased);

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

lines 383–384why, one step back
383}
384

Rename vtable object ref and mut methods that are no longer raw ptrDavid Tolnaybefore adoptiond57f80c

line 385why, one step back
385unsafe 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 back
386where
387 E: StdError + Send + Sync + 'static,388{

Merge pull request #16 from johnschug/masterDavid Tolnaybefore adoptioneeaf2ef

line 389why, one step back
389 &(*(e as *const ErrorImpl<()> as *const ErrorImpl<E>))._error

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

lines 390–391why, one step back
390}
391

Rename vtable object ref and mut methods that are no longer raw ptrDavid Tolnaybefore adoptiond57f80c

line 392why, one step back
392unsafe 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 back
393where
394 E: StdError + Send + Sync + 'static,395{

Merge pull request #16 from johnschug/masterDavid Tolnaybefore adoptioneeaf2ef

line 396why, one step back
396 &mut (*(e as *mut ErrorImpl<()> as *mut ErrorImpl<E>))._error

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

lines 397–398why, one step back
397}
398

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 399–405why, one step back
399unsafe 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}405

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 406–407why, one step back
406// repr C to ensure that `E` remains in the final position
407#[repr(C)]

Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84

line 408why, one step back
408struct ErrorImpl<E> {

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

line 409why, one step back
409 vtable: &'static ErrorVTable,

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 410–411why, one step back
410 type_id: TypeId,
411 backtrace: Option<Backtrace>,

Merge pull request #16 from johnschug/masterDavid Tolnaybefore adoptioneeaf2ef

lines 412–413why, one step back
412 // 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 back
414}
415416#[repr(transparent)]

Remove trait bounds from MessageError structDavid Tolnaybefore adoptioneac05d1

line 417why, one step back
417struct MessageError<M>(M);

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 418why, one step back
418

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

lines 419–422why, one step back
419impl<M> Debug for MessageError<M>
420where421 M: Display + Debug,422{

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 423–427why, one step back
423 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
424 Debug::fmt(&self.0, f)425 }426}427

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

lines 428–431why, one step back
428impl<M> Display for MessageError<M>
429where430 M: Display + Debug,431{

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 432–436why, one step back
432 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
433 Display::fmt(&self.0, f)434 }435}436

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

line 437why, one step back
437impl<M> StdError for MessageError<M> where M: Display + Debug + 'static {}

Merge pull request #8 from dtolnay/optionDavid Tolnaybefore adoption240cc83

lines 438–460why, one step back
438
439#[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 back
461

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

lines 462–467why, one step back
462impl<E> ErrorImpl<E> {
463 fn erase(&self) -> &ErrorImpl<()> {464 unsafe { &*(self as *const ErrorImpl<E> as *const ErrorImpl<()>) }465 }466}467

Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84

line 468why, one step back
468impl ErrorImpl<()> {

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 469why, one step back
469 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 back
470 unsafe { &*(self.vtable.object_ref)(self) }

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 471–472why, one step back
471 }
472

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 473why, one step back
473 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 back
474 unsafe { &mut *(self.vtable.object_mut)(self) }

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 475–531why, one step back
475 }
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}531

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

lines 532–539why, one step back
532impl<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 back
540

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

line 541why, one step back
541 fn source(&self) -> Option<&(dyn StdError + 'static)> {

Merge pull request #16 from johnschug/masterDavid Tolnaybefore adoptioneeaf2ef

line 542why, one step back
542 self.erase().error().source()

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

lines 543–545why, one step back
543 }
544}545

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 546–550why, one step back
546impl<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 back
551 self.erase().debug(formatter)

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 552–559why, one step back
552 }
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 back
560 Display::fmt(&self.erase().error(), formatter)

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 561–571why, one step back
561 }
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 back
572 }
573}574

Rename Errors to ChainDavid Tolnaybefore adoptionf972193

line 575why, one step back
575/// Iterator of a chain of source errors.

Add example to Chain iteratorDavid Tolnaybefore adoptionfeb9f33

lines 576–593why, one step back
576///
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 back
594pub struct Chain<'a> {

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 595why, one step back
595 next: Option<&'a (dyn StdError + 'static)>,

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 596–597why, one step back
596}
597

Rename Errors to ChainDavid Tolnaybefore adoptionf972193

line 598why, one step back
598impl<'a> Iterator for Chain<'a> {

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 599why, one step back
599 type Item = &'a (dyn StdError + 'static);

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 600–606why, one step back
600
601 fn next(&mut self) -> Option<Self::Item> {602 let next = self.next.take()?;603 self.next = next.source();604 Some(next)605 }606}