Skip to content
Myr

error.rs

This file

Path

src/error.rs

599 lines · 16.9 KiB · Rust

Last changed by

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

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>,

Update vtable function names to match the implementation namesDavid Tolnaybefore adoption470db19

lines 86–87why, one step back
86 object_raw: object_raw::<E>,
87 object_mut_raw: object_mut_raw::<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–95why, one step back
89 };
90 let inner = Box::new(ErrorImpl {91 vtable,92 type_id,93 backtrace,94 error,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 {

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

lines 236–239why, one step back
236 let error = ptr::read(&outer.inner.error as *const () as *const E);
237 let inner = ptr::read(&outer.inner);238 let erased = ManuallyDrop::into_inner(inner);239 (erased.vtable.object_drop_front)(erased);

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 240–246why, one step back
240 Ok(error)
241 }242 } else {243 Err(self)244 }245 }246

Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c

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

Add example to Error::downcast_refDavid Tolnaybefore adoption0c21b7a

lines 248–282why, one step back
248 ///
249 /// # Example250 ///251 /// ```252 /// # use anyhow::anyhow;253 /// # use std::fmt::{self, Display};254 /// # use std::task::Poll;255 /// #256 /// # #[derive(Debug)]257 /// # enum DataStoreError {258 /// # Censored(()),259 /// # }260 /// #261 /// # impl Display for DataStoreError {262 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {263 /// # unimplemented!()264 /// # }265 /// # }266 /// #267 /// # impl std::error::Error for DataStoreError {}268 /// #269 /// # const REDACTED_CONTENT: () = ();270 /// #271 /// # let error = anyhow!("...");272 /// # let root_cause = &error;273 /// #274 /// # let ret =275 /// // If the error was caused by redaction, then return a tombstone instead276 /// // of the content.277 /// match root_cause.downcast_ref::<DataStoreError>() {278 /// Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),279 /// None => Err(error),280 /// }281 /// # ;282 /// ```

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

lines 283–286why, one step back
283 pub fn downcast_ref<E>(&self) -> Option<&E>
284 where285 E: Display + Debug + Send + Sync + 'static,286 {

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 287why, one step back
287 if self.is::<E>() {

Simplify downcast_ref and downcast_mutDavid Tolnaybefore adoption8895b00

line 288why, one step back
288 Some(unsafe { &*(&self.inner.error as *const () as *const E) })

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 289–293why, one step back
289 } else {
290 None291 }292 }293

Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c

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

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

lines 295–298why, one step back
295 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>
296 where297 E: Display + Debug + Send + Sync + 'static,298 {

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 299why, one step back
299 if self.is::<E>() {

Simplify downcast_ref and downcast_mutDavid Tolnaybefore adoption8895b00

line 300why, one step back
300 Some(unsafe { &mut *(&mut self.inner.error as *mut () as *mut E) })

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 301–305why, one step back
301 } else {
302 None303 }304 }305}

Remove use of attributes on function parametersDavid Tolnaybefore adoptiona2d7e2f

line 306why, one step back
306

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

lines 307–310why, one step back
307impl<E> From<E> for Error
308where309 E: StdError + Send + Sync + 'static,310{

Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337

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

Capture backtraces earlierDavid Tolnaybefore adoptionc06155e

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 314–316why, one step back
314 }
315}316

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

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

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

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

Remove as_dyn_error methods from ErrorDavid Tolnaybefore adoption73c7283

line 319why, one step back
319

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 320–324why, one step back
320 fn deref(&self) -> &Self::Target {
321 self.inner.error()322 }323}324

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

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

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 332–333why, one step back
332 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
333 self.inner.debug(formatter)

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 334–336why, one step back
334 }
335}336

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 338–342why, one step back
338 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
339 write!(f, "{}", self.inner.error())340 }341}342

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

lines 343–344why, one step back
343unsafe impl Send for Error {}
344unsafe impl Sync for Error {}

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 345why, one step back
345

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

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

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

line 348why, one step back
348 unsafe {

Ptr read only needs a const ptrDavid Tolnaybefore adoption83f63a6

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

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

lines 350–352why, one step back
350 let erased = ManuallyDrop::into_inner(inner);
351 (erased.vtable.object_drop)(erased);352 }

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 353–355why, one step back
353 }
354}355

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

line 356why, one step back
356struct ErrorVTable {

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

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

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

line 358why, one step back
358 object_drop_front: unsafe fn(Box<ErrorImpl<()>>),

Update vtable function names to match the implementation namesDavid Tolnaybefore adoption470db19

lines 359–360why, one step back
359 object_raw: fn(*const ()) -> *const (dyn StdError + Send + Sync + 'static),
360 object_mut_raw: fn(*mut ()) -> *mut (dyn StdError + Send + Sync + 'static),

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

line 361why, one step back
361 object_boxed: unsafe fn(Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>,

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

lines 362–367why, one step back
362}
363364unsafe fn object_drop<E>(e: Box<ErrorImpl<()>>) {365 // Cast back to ErrorImpl<E> so that the allocator receives the correct366 // Layout to deallocate the Box's memory.367 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e);

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

lines 368–375why, one step back
368 drop(unerased);
369}370371unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>) {372 // Drop the fields of ErrorImpl other than E as well as the Box allocation,373 // without dropping E itself. This is used by downcast after doing a374 // ptr::read to take ownership of the E.375 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<ManuallyDrop<E>>>>(e);

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

line 376why, one step back
376 drop(unerased);

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

lines 377–378why, one step back
377}
378

No need for object_raw, object_mut_raw to be unsafeDavid Tolnaybefore adoption42e5c93

line 379why, one step back
379fn object_raw<E>(e: *const ()) -> *const (dyn StdError + Send + Sync + 'static)

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

lines 380–385why, one step back
380where
381 E: StdError + Send + Sync + 'static,382{383 e as *const E384}385

No need for object_raw, object_mut_raw to be unsafeDavid Tolnaybefore adoption42e5c93

line 386why, one step back
386fn object_mut_raw<E>(e: *mut ()) -> *mut (dyn StdError + Send + Sync + 'static)

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

lines 387–392why, one step back
387where
388 E: StdError + Send + Sync + 'static,389{390 e as *mut E391}392

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 393–399why, one step back
393unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>
394where395 E: StdError + Send + Sync + 'static,396{397 mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e)398}399

Rename exception module to errorDavid Tolnaybefore adoption2000930

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

Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 404–409why, one step back
404 type_id: TypeId,
405 backtrace: Option<Backtrace>,406 error: E,407}408409#[repr(transparent)]

Remove trait bounds from MessageError structDavid Tolnaybefore adoptioneac05d1

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 411why, one step back
411

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

lines 412–415why, one step back
412impl<M> Debug for MessageError<M>
413where414 M: Display + Debug,415{

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 416–420why, one step back
416 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
417 Debug::fmt(&self.0, f)418 }419}420

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

lines 421–424why, one step back
421impl<M> Display for MessageError<M>
422where423 M: Display + Debug,424{

Rename exception module to errorDavid Tolnaybefore adoption2000930

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

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

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

Merge pull request #8 from dtolnay/optionDavid Tolnaybefore adoption240cc83

lines 431–453why, one step back
431
432#[repr(transparent)]433struct DisplayError<M>(M);434435impl<M> Debug for DisplayError<M>436where437 M: Display,438{439 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {440 Display::fmt(&self.0, f)441 }442}443444impl<M> Display for DisplayError<M>445where446 M: Display,447{448 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {449 Display::fmt(&self.0, f)450 }451}452453impl<M> StdError for DisplayError<M> where M: Display + 'static {}

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 454why, one step back
454

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

lines 455–460why, one step back
455impl<E> ErrorImpl<E> {
456 fn erase(&self) -> &ErrorImpl<()> {457 unsafe { &*(self as *const ErrorImpl<E> as *const ErrorImpl<()>) }458 }459}460

Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84

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

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

line 462why, one step back
462 fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {

Update vtable function names to match the implementation namesDavid Tolnaybefore adoption470db19

line 463why, one step back
463 unsafe { &*(self.vtable.object_raw)(&self.error) }

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 464–465why, one step back
464 }
465

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

line 466why, one step back
466 fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {

Update vtable function names to match the implementation namesDavid Tolnaybefore adoption470db19

line 467why, one step back
467 unsafe { &mut *(self.vtable.object_mut_raw)(&mut self.error) }

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 468–524why, one step back
468 }
469470 #[cfg(backtrace)]471 fn backtrace(&self) -> &Backtrace {472 // This unwrap can only panic if the underlying error's backtrace method473 // is nondeterministic, which would only happen in maliciously474 // constructed code.475 self.backtrace476 .as_ref()477 .or_else(|| self.error().backtrace())478 .expect("backtrace capture failed")479 }480481 fn chain(&self) -> Chain {482 Chain {483 next: Some(self.error()),484 }485 }486487 fn debug(&self, f: &mut fmt::Formatter) -> fmt::Result {488 writeln!(f, "{}", self.error())?;489490 let mut chain = self.chain().skip(1).enumerate().peekable();491 if let Some((n, error)) = chain.next() {492 write!(f, "\nCaused by:\n ")?;493 if chain.peek().is_some() {494 write!(f, "{}: ", n)?;495 }496 writeln!(f, "{}", error)?;497 for (n, error) in chain {498 writeln!(f, " {}: {}", n, error)?;499 }500 }501502 #[cfg(backtrace)]503 {504 use std::backtrace::BacktraceStatus;505506 let backtrace = self.backtrace();507 match backtrace.status() {508 BacktraceStatus::Captured => {509 writeln!(f, "\n{}", backtrace)?;510 }511 BacktraceStatus::Disabled => {512 writeln!(513 f,514 "\nBacktrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace"515 )?;516 }517 _ => {}518 }519 }520521 Ok(())522 }523}524

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

lines 525–532why, one step back
525impl<E> StdError for ErrorImpl<E>
526where527 E: StdError,528{529 #[cfg(backtrace)]530 fn backtrace(&self) -> Option<&Backtrace> {531 Some(self.erase().backtrace())532 }

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

line 533why, one step back
533

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

lines 534–538why, one step back
534 fn source(&self) -> Option<&(dyn StdError + 'static)> {
535 self.error.source()536 }537}538

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 539–543why, one step back
539impl<E> Debug for ErrorImpl<E>
540where541 E: Debug,542{543 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

line 544why, one step back
544 self.erase().debug(formatter)

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 545–564why, one step back
545 }
546}547548impl<E> Display for ErrorImpl<E>549where550 E: Display,551{552 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {553 Display::fmt(&self.error, formatter)554 }555}556557impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {558 fn from(error: Error) -> Self {559 let outer = ManuallyDrop::new(error);560 unsafe {561 let inner = ptr::read(&outer.inner);562 let erased = ManuallyDrop::into_inner(inner);563 (erased.vtable.object_boxed)(erased)564 }

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 565–567why, one step back
565 }
566}567

Rename Errors to ChainDavid Tolnaybefore adoptionf972193

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

Add example to Chain iteratorDavid Tolnaybefore adoptionfeb9f33

lines 569–586why, one step back
569///
570/// This type is the iterator returned by [`Error::chain`].571///572/// # Example573///574/// ```575/// use anyhow::Error;576/// use std::io;577///578/// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {579/// for cause in error.chain() {580/// if let Some(io_error) = cause.downcast_ref::<io::Error>() {581/// return Some(io_error.kind());582/// }583/// }584/// None585/// }586/// ```

Rename Errors to ChainDavid Tolnaybefore adoptionf972193

line 587why, one step back
587pub struct Chain<'a> {

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

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 589–590why, one step back
589}
590

Rename Errors to ChainDavid Tolnaybefore adoptionf972193

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

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

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 593–599why, one step back
593
594 fn next(&mut self) -> Option<Self::Item> {595 let next = self.next.take()?;596 self.next = next.source();597 Some(next)598 }599}