Skip to content
Myr

error.rs

This file

Path

src/error.rs

802 lines · 27.0 KiB · Rust

Last changed by

Merge pull request #78 from dtolnay/cfgDavid Tolnaybefore adoptione2eb1f5

History of this file

Take it

The walk stopped after 200 commits: lines older than d28ff29 point at it.

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 1why, one step back
1use crate::alloc::Box;

Move backtrace capture to backtrace module and macroDavid Tolnaybefore adoptionebd9101

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

lines 3–8why, one step back
3use crate::chain::Chain;
4use crate::{Error, StdError};5use core::any::TypeId;6use core::fmt::{self, Debug, Display};7use core::mem::{self, ManuallyDrop};8use core::ptr::{self, NonNull};

Add readme stubDavid Tolnaybefore adoptiond28ff29

line 9why, one step back
9

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

lines 10–12why, one step back
10#[cfg(feature = "std")]
11use core::ops::{Deref, DerefMut};12

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 13–20why, one step back
13impl Error {
14 /// Create a new error object from any error type.15 ///16 /// The error type must be threadsafe and `'static`, so that the `Error`17 /// will be as well.18 ///19 /// If the error type does not provide a backtrace, a backtrace will be20 /// created here to ensure that a backtrace exists.

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 21why, one step back
21 #[cfg(feature = "std")]

Merge pull request #78 from dtolnay/cfgDavid Tolnaybefore adoptione2eb1f5

line 22why, one step back
22 #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]

Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337

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

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 24–26why, one step back
24 where
25 E: StdError + Send + Sync + 'static,26 {

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

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

Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9

lines 28–29why, one step back
28 Error::from_std(error, backtrace)
29 }

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

line 30why, one step back
30

Add Error::msg constructor to simplify map_err combinatorsDavid Tolnaybefore adoption04b11c5

lines 31–74why, one step back
31 /// Create a new error object from a printable error message.
32 ///33 /// If the argument implements std::error::Error, prefer `Error::new`34 /// instead which preserves the underlying error's cause chain and35 /// backtrace. If the argument may or may not implement std::error::Error36 /// now or in the future, use `anyhow!(err)` which handles either way37 /// correctly.38 ///39 /// `Error::msg("...")` is equivalent to `anyhow!("...")` but occasionally40 /// convenient in places where a function is preferable over a macro, such41 /// as iterator or stream combinators:42 ///43 /// ```44 /// # mod ffi {45 /// # pub struct Input;46 /// # pub struct Output;47 /// # pub async fn do_some_work(_: Input) -> Result<Output, &'static str> {48 /// # unimplemented!()49 /// # }50 /// # }51 /// #52 /// # use ffi::{Input, Output};53 /// #54 /// use anyhow::{Error, Result};55 /// use futures::stream::{Stream, StreamExt, TryStreamExt};56 ///57 /// async fn demo<S>(stream: S) -> Result<Vec<Output>>58 /// where59 /// S: Stream<Item = Input>,60 /// {61 /// stream62 /// .then(ffi::do_some_work) // returns Result<Output, &str>63 /// .map_err(Error::msg)64 /// .try_collect()65 /// .await66 /// }67 /// ```68 pub fn msg<M>(message: M) -> Self69 where70 M: Display + Debug + Send + Sync + 'static,71 {72 Error::from_adhoc(message, backtrace!())73 }74

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 75why, one step back
75 #[cfg(feature = "std")]

Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9

lines 76–79why, one step back
76 pub(crate) fn from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self
77 where78 E: StdError + Send + Sync + 'static,79 {

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

lines 80–82why, one step back
80 let vtable = &ErrorVTable {
81 object_drop: object_drop::<E>,82 object_ref: object_ref::<E>,

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 83why, one step back
83 #[cfg(feature = "std")]

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

lines 84–85why, one step back
84 object_mut: object_mut::<E>,
85 object_boxed: object_boxed::<E>,

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 86–87why, one step back
86 object_downcast: object_downcast::<E>,
87 object_drop_rest: object_drop_front::<E>,

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

line 88why, one step back
88 };

Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9

line 89why, one step back
89

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

lines 90–91why, one step back
90 // Safety: passing vtable that operates on the right type E.
91 unsafe { Error::construct(error, vtable, backtrace) }

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 92–93why, one step back
92 }
93

Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9

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

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 95–97why, one step back
95 where
96 M: Display + Debug + Send + Sync + 'static,97 {

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 98why, one step back
98 use crate::wrapper::MessageError;

Specify types where the manual vtable relies on themDavid Tolnaybefore adoptionb261a64

line 99why, one step back
99 let error: MessageError<M> = MessageError(message);

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

lines 100–102why, one step back
100 let vtable = &ErrorVTable {
101 object_drop: object_drop::<MessageError<M>>,102 object_ref: object_ref::<MessageError<M>>,

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 103why, one step back
103 #[cfg(feature = "std")]

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

lines 104–105why, one step back
104 object_mut: object_mut::<MessageError<M>>,
105 object_boxed: object_boxed::<MessageError<M>>,

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 106–107why, one step back
106 object_downcast: object_downcast::<M>,
107 object_drop_rest: object_drop_front::<M>,

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

line 108why, one step back
108 };

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

line 109why, one step back
109

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

lines 110–112why, one step back
110 // Safety: MessageError is repr(transparent) so it is okay for the
111 // vtable to allow casting the MessageError<M> to M.112 unsafe { Error::construct(error, vtable, backtrace) }

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 113–114why, one step back
113 }
114

Merge pull request #8 from dtolnay/optionDavid Tolnaybefore adoption240cc83

lines 115–118why, one step back
115 pub(crate) fn from_display<M>(message: M, backtrace: Option<Backtrace>) -> Self
116 where117 M: Display + Send + Sync + 'static,118 {

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 119why, one step back
119 use crate::wrapper::DisplayError;

Specify types where the manual vtable relies on themDavid Tolnaybefore adoptionb261a64

line 120why, one step back
120 let error: DisplayError<M> = DisplayError(message);

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

lines 121–123why, one step back
121 let vtable = &ErrorVTable {
122 object_drop: object_drop::<DisplayError<M>>,123 object_ref: object_ref::<DisplayError<M>>,

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 124why, one step back
124 #[cfg(feature = "std")]

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

lines 125–126why, one step back
125 object_mut: object_mut::<DisplayError<M>>,
126 object_boxed: object_boxed::<DisplayError<M>>,

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 127–128why, one step back
127 object_downcast: object_downcast::<M>,
128 object_drop_rest: object_drop_front::<M>,

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

line 129why, one step back
129 };

Merge pull request #8 from dtolnay/optionDavid Tolnaybefore adoption240cc83

line 130why, one step back
130

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

lines 131–133why, one step back
131 // Safety: DisplayError is repr(transparent) so it is okay for the
132 // vtable to allow casting the DisplayError<M> to M.133 unsafe { Error::construct(error, vtable, backtrace) }

Merge pull request #8 from dtolnay/optionDavid Tolnaybefore adoption240cc83

lines 134–135why, one step back
134 }
135

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 136why, one step back
136 #[cfg(feature = "std")]

Expand ContextError vtable to prepare for extending downcast supportDavid Tolnaybefore adoption45e6fc6

line 137why, one step back
137 pub(crate) fn from_context<C, E>(context: C, error: E, backtrace: Option<Backtrace>) -> Self

Move ContextError to error.rs in preparation for refactorDavid Tolnaybefore adoption30c2eab

lines 138–141why, one step back
138 where
139 C: Display + Send + Sync + 'static,140 E: StdError + Send + Sync + 'static,141 {

Expand ContextError vtable to prepare for extending downcast supportDavid Tolnaybefore adoption45e6fc6

lines 142–146why, one step back
142 let error: ContextError<C, E> = ContextError { context, error };
143144 let vtable = &ErrorVTable {145 object_drop: object_drop::<ContextError<C, E>>,146 object_ref: object_ref::<ContextError<C, E>>,

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 147why, one step back
147 #[cfg(feature = "std")]

Expand ContextError vtable to prepare for extending downcast supportDavid Tolnaybefore adoption45e6fc6

lines 148–149why, one step back
148 object_mut: object_mut::<ContextError<C, E>>,
149 object_boxed: object_boxed::<ContextError<C, E>>,

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 150–151why, one step back
150 object_downcast: context_downcast::<C, E>,
151 object_drop_rest: context_drop_rest::<C, E>,

Expand ContextError vtable to prepare for extending downcast supportDavid Tolnaybefore adoption45e6fc6

lines 152–154why, one step back
152 };
153154 // Safety: passing vtable that operates on the right type.

Merge pull request #50 from dtolnay/boxedDavid Tolnaybefore adoption74fbea6

lines 155–157why, one step back
155 unsafe { Error::construct(error, vtable, backtrace) }
156 }157

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 158why, one step back
158 #[cfg(feature = "std")]

Merge pull request #50 from dtolnay/boxedDavid Tolnaybefore adoption74fbea6

lines 159–162why, one step back
159 pub(crate) fn from_boxed(
160 error: Box<dyn StdError + Send + Sync>,161 backtrace: Option<Backtrace>,162 ) -> Self {

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 163why, one step back
163 use crate::wrapper::BoxedError;

Merge pull request #50 from dtolnay/boxedDavid Tolnaybefore adoption74fbea6

lines 164–167why, one step back
164 let error = BoxedError(error);
165 let vtable = &ErrorVTable {166 object_drop: object_drop::<BoxedError>,167 object_ref: object_ref::<BoxedError>,

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 168why, one step back
168 #[cfg(feature = "std")]

Merge pull request #50 from dtolnay/boxedDavid Tolnaybefore adoption74fbea6

lines 169–176why, one step back
169 object_mut: object_mut::<BoxedError>,
170 object_boxed: object_boxed::<BoxedError>,171 object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,172 object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,173 };174175 // Safety: BoxedError is repr(transparent) so it is okay for the vtable176 // to allow casting to Box<dyn StdError + Send + Sync>.

Expand ContextError vtable to prepare for extending downcast supportDavid Tolnaybefore adoption45e6fc6

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

Move ContextError to error.rs in preparation for refactorDavid Tolnaybefore adoption30c2eab

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

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

lines 180–181why, one step back
180 // Takes backtrace as argument rather than capturing it here so that the
181 // user sees one fewer layer of wrapping noise in the backtrace.

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

line 182why, one step back
182 //

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

lines 183–189why, one step back
183 // Unsafe because the given vtable must have sensible behavior on the error
184 // value of type E.185 unsafe fn construct<E>(186 error: E,187 vtable: &'static ErrorVTable,188 backtrace: Option<Backtrace>,189 ) -> Self

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 190–192why, one step back
190 where
191 E: StdError + Send + Sync + 'static,192 {

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

lines 193–195why, one step back
193 let inner = Box::new(ErrorImpl {
194 vtable,195 backtrace,

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

line 196why, one step back
196 _object: error,

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

line 197why, one step back
197 });

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 198–203why, one step back
198 // Erase the concrete type of E from the compile-time type system. This
199 // is equivalent to the safe unsize coersion from Box<ErrorImpl<E>> to200 // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the201 // result is a thin pointer. The necessary behavior for manipulating the202 // underlying ErrorImpl<E> is preserved in the vtable provided by the203 // caller rather than a builtin fat pointer vtable.

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

lines 204–206why, one step back
204 let erased = mem::transmute::<Box<ErrorImpl<E>>, Box<ErrorImpl<()>>>(inner);
205 let inner = ManuallyDrop::new(erased);206 Error { inner }

Add context method to ErrorDavid Tolnaybefore adoption41fde4c

lines 207–209why, one step back
207 }
208209 /// Wrap the error value with additional context.

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

lines 210–213why, one step back
210 ///
211 /// For attaching context to a `Result` as it is propagated, the212 /// [`Context`][crate::Context] extension trait may be more convenient than213 /// this function.

Explain the purpose of Error::contextDavid Tolnaybefore adoption896dd7a

lines 214–235why, one step back
214 ///
215 /// The primary reason to use `error.context(...)` instead of216 /// `result.context(...)` via the `Context` trait would be if the context217 /// needs to depend on some data held by the underlying error:218 ///219 /// ```220 /// # use std::fmt::{self, Debug, Display};221 /// #222 /// # type T = ();223 /// #224 /// # impl std::error::Error for ParseError {}225 /// # impl Debug for ParseError {226 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {227 /// # unimplemented!()228 /// # }229 /// # }230 /// # impl Display for ParseError {231 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {232 /// # unimplemented!()233 /// # }234 /// # }235 /// #

Clean up Error::context example using anyhow ResultDavid Tolnaybefore adoptionf8457fb

line 236why, one step back
236 /// use anyhow::Result;

Explain the purpose of Error::contextDavid Tolnaybefore adoption896dd7a

lines 237–251why, one step back
237 /// use std::fs::File;
238 /// use std::path::Path;239 ///240 /// struct ParseError {241 /// line: usize,242 /// column: usize,243 /// }244 ///245 /// fn parse_impl(file: File) -> Result<T, ParseError> {246 /// # const IGNORE: &str = stringify! {247 /// ...248 /// # };249 /// # unimplemented!()250 /// }251 ///

Clean up Error::context example using anyhow ResultDavid Tolnaybefore adoptionf8457fb

line 252why, one step back
252 /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {

Explain the purpose of Error::contextDavid Tolnaybefore adoption896dd7a

lines 253–262why, one step back
253 /// let file = File::open(&path)?;
254 /// parse_impl(file).map_err(|error| {255 /// let context = format!(256 /// "only the first {} lines of {} are valid",257 /// error.line, path.as_ref().display(),258 /// );259 /// anyhow::Error::new(error).context(context)260 /// })261 /// }262 /// ```

Add context method to ErrorDavid Tolnaybefore adoption41fde4c

lines 263–266why, one step back
263 pub fn context<C>(self, context: C) -> Self
264 where265 C: Display + Send + Sync + 'static,266 {

Specify types where the manual vtable relies on themDavid Tolnaybefore adoptionb261a64

line 267why, one step back
267 let error: ContextError<C, Error> = ContextError {

Add context method to ErrorDavid Tolnaybefore adoption41fde4c

line 268why, one step back
268 context,

Swap ContextError type parameters to match type nameDavid Tolnaybefore adoption9f38495

line 269why, one step back
269 error: self,

Eliminate backtrace_if_absent in Error::contextDavid Tolnaybefore adoptiona2846fd

lines 270–274why, one step back
270 };
271272 let vtable = &ErrorVTable {273 object_drop: object_drop::<ContextError<C, Error>>,274 object_ref: object_ref::<ContextError<C, Error>>,

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 275why, one step back
275 #[cfg(feature = "std")]

Eliminate backtrace_if_absent in Error::contextDavid Tolnaybefore adoptiona2846fd

lines 276–277why, one step back
276 object_mut: object_mut::<ContextError<C, Error>>,
277 object_boxed: object_boxed::<ContextError<C, Error>>,

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 278–279why, one step back
278 object_downcast: context_chain_downcast::<C>,
279 object_drop_rest: context_chain_drop_rest::<C>,

Eliminate backtrace_if_absent in Error::contextDavid Tolnaybefore adoptiona2846fd

lines 280–286why, one step back
280 };
281282 // As the cause is anyhow::Error, we already have a backtrace for it.283 let backtrace = None;284285 // Safety: passing vtable that operates on the right type.286 unsafe { Error::construct(error, vtable, backtrace) }

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 287–289why, one step back
287 }
288289 /// Get the backtrace for this Error.

Detect nightly and only expose backtrace if availableDavid Tolnaybefore adoption270ea5e

lines 290–293why, one step back
290 ///
291 /// Backtraces are only available on the nightly channel. Tracking issue:292 /// [rust-lang/rust#53487][tracking].293 ///

Merge pull request #70 from dtolnay/envDavid Tolnaybefore adoption8d2acea

lines 294–296why, one step back
294 /// In order for the backtrace to be meaningful, one of the two environment
295 /// variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined296 /// and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhat

Mention env var in Error::backtrace documentationDavid Tolnaybefore adoption4119806

lines 297–298why, one step back
297 /// expensive to capture in Rust, so we don't necessarily want to be
298 /// capturing them all over the place all the time.

Merge pull request #70 from dtolnay/envDavid Tolnaybefore adoption8d2acea

lines 299–305why, one step back
299 ///
300 /// - If you want panics and errors to both have backtraces, set301 /// `RUST_BACKTRACE=1`;302 /// - If you want only errors to have backtraces, set303 /// `RUST_LIB_BACKTRACE=1`;304 /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and305 /// `RUST_LIB_BACKTRACE=0`.

Mention env var in Error::backtrace documentationDavid Tolnaybefore adoption4119806

line 306why, one step back
306 ///

Detect nightly and only expose backtrace if availableDavid Tolnaybefore adoption270ea5e

lines 307–308why, one step back
307 /// [tracking]: https://github.com/rust-lang/rust/issues/53487
308 #[cfg(backtrace)]

Add readme stubDavid Tolnaybefore adoptiond28ff29

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 311–317why, one step back
311 }
312313 /// An iterator of the chain of source errors contained by this Error.314 ///315 /// This iterator will visit every error in the cause chain of this error316 /// object, beginning with the error that this error object was created317 /// from.

Add example of Error::chainDavid Tolnaybefore adoptiond159b79

lines 318–333why, one step back
318 ///
319 /// # Example320 ///321 /// ```322 /// use anyhow::Error;323 /// use std::io;324 ///325 /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {326 /// for cause in error.chain() {327 /// if let Some(io_error) = cause.downcast_ref::<io::Error>() {328 /// return Some(io_error.kind());329 /// }330 /// }331 /// None332 /// }333 /// ```

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 334why, one step back
334 #[cfg(feature = "std")]

Add readme stubDavid Tolnaybefore adoptiond28ff29

line 335why, one step back
335 pub fn chain(&self) -> Chain {

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 337–338why, one step back
337 }
338

Add Error::root_cause accessorDavid Tolnaybefore adoption1ea72bb

lines 339–343why, one step back
339 /// The lowest level cause of this error &mdash; this error's cause's
340 /// cause's cause etc.341 ///342 /// The root cause is the last error in the iterator produced by343 /// [`chain()`][Error::chain].

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 344why, one step back
344 #[cfg(feature = "std")]

Add Error::root_cause accessorDavid Tolnaybefore adoption1ea72bb

lines 345–353why, one step back
345 pub fn root_cause(&self) -> &(dyn StdError + 'static) {
346 let mut chain = self.chain();347 let mut root_cause = chain.next().unwrap();348 for cause in chain {349 root_cause = cause;350 }351 root_cause352 }353

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 354–361why, one step back
354 /// Returns true if `E` is the type held by this error object.
355 ///356 /// For errors with context, this method returns true if `E` matches the357 /// type of the context `C` **or** the type of the error on which the358 /// context has been attached. For details about the interaction between359 /// context and downcasting, [see here].360 ///361 /// [see here]: trait.Context.html#effect-on-downcasting

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 362–365why, one step back
362 pub fn is<E>(&self) -> bool
363 where364 E: Display + Debug + Send + Sync + 'static,365 {

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

line 366why, one step back
366 self.downcast_ref::<E>().is_some()

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 367–369why, one step back
367 }
368369 /// Attempt to downcast the error object to a concrete type.

Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337

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

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 371–373why, one step back
371 where
372 E: Display + Debug + Send + Sync + 'static,373 {

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 374–375why, one step back
374 let target = TypeId::of::<E>();
375 unsafe {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 376–377why, one step back
376 // Use vtable to find NonNull<()> which points to a value of type E
377 // somewhere inside the data structure.

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 378–381why, one step back
378 let addr = match (self.inner.vtable.object_downcast)(&self.inner, target) {
379 Some(addr) => addr,380 None => return Err(self),381 };

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 382–384why, one step back
382
383 // Prepare to read E out of the data structure. We'll drop the rest384 // of the data structure separately so that E is not dropped.

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

line 385why, one step back
385 let outer = ManuallyDrop::new(self);

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 386–387why, one step back
386
387 // Read E from where the vtable found it.

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

line 388why, one step back
388 let error = ptr::read(addr.cast::<E>().as_ptr());

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 389–391why, one step back
389
390 // Read Box<ErrorImpl<()>> from self. Can't move it out because391 // Error has a Drop impl which we want to not run.

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 392–393why, one step back
392 let inner = ptr::read(&outer.inner);
393 let erased = ManuallyDrop::into_inner(inner);

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 394–395why, one step back
394
395 // Drop rest of the data structure outside of E.

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

line 396why, one step back
396 (erased.vtable.object_drop_rest)(erased, target);

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 397why, one step back
397

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

line 398why, one step back
398 Ok(error)

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 399–402why, one step back
399 }
400 }401402 /// Downcast this error object by reference.

Add example to Error::downcast_refDavid Tolnaybefore adoption0c21b7a

lines 403–437why, one step back
403 ///
404 /// # Example405 ///406 /// ```407 /// # use anyhow::anyhow;408 /// # use std::fmt::{self, Display};409 /// # use std::task::Poll;410 /// #411 /// # #[derive(Debug)]412 /// # enum DataStoreError {413 /// # Censored(()),414 /// # }415 /// #416 /// # impl Display for DataStoreError {417 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {418 /// # unimplemented!()419 /// # }420 /// # }421 /// #422 /// # impl std::error::Error for DataStoreError {}423 /// #424 /// # const REDACTED_CONTENT: () = ();425 /// #426 /// # let error = anyhow!("...");427 /// # let root_cause = &error;428 /// #429 /// # let ret =430 /// // If the error was caused by redaction, then return a tombstone instead431 /// // of the content.432 /// match root_cause.downcast_ref::<DataStoreError>() {433 /// Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),434 /// None => Err(error),435 /// }436 /// # ;437 /// ```

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 438–441why, one step back
438 pub fn downcast_ref<E>(&self) -> Option<&E>
439 where440 E: Display + Debug + Send + Sync + 'static,441 {

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 442–443why, one step back
442 let target = TypeId::of::<E>();
443 unsafe {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 444–445why, one step back
444 // Use vtable to find NonNull<()> which points to a value of type E
445 // somewhere inside the data structure.

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 446–447why, one step back
446 let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;
447 Some(&*addr.cast::<E>().as_ptr())

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 448–455why, one step back
448 }
449 }450451 /// Downcast this error object by mutable reference.452 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>453 where454 E: Display + Debug + Send + Sync + 'static,455 {

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 456–457why, one step back
456 let target = TypeId::of::<E>();
457 unsafe {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 458–459why, one step back
458 // Use vtable to find NonNull<()> which points to a value of type E
459 // somewhere inside the data structure.

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 460–461why, one step back
460 let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;
461 Some(&mut *addr.cast::<E>().as_ptr())

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 462–464why, one step back
462 }
463 }464}

Remove use of attributes on function parametersDavid Tolnaybefore adoptiona2d7e2f

line 465why, one step back
465

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 466why, one step back
466#[cfg(feature = "std")]

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 467–470why, one step back
467impl<E> From<E> for Error
468where469 E: StdError + Send + Sync + 'static,470{

Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337

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

Capture backtraces earlierDavid Tolnaybefore adoptionc06155e

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

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 474–476why, one step back
474 }
475}476

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 477why, one step back
477#[cfg(feature = "std")]

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 478–479why, one step back
478impl Deref for Error {
479 type Target = dyn StdError + Send + Sync + 'static;

Remove as_dyn_error methods from ErrorDavid Tolnaybefore adoption73c7283

line 480why, one step back
480

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 481–485why, one step back
481 fn deref(&self) -> &Self::Target {
482 self.inner.error()483 }484}485

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 486why, one step back
486#[cfg(feature = "std")]

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 487–492why, one step back
487impl DerefMut for Error {
488 fn deref_mut(&mut self) -> &mut Self::Target {489 self.inner.error_mut()490 }491}492

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

line 494why, one step back
494 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

line 495why, one step back
495 self.inner.display(formatter)

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 496–498why, one step back
496 }
497}498

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

lines 499–501why, one step back
499impl Debug for Error {
500 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {501 self.inner.debug(formatter)

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 502–506why, one step back
502 }
503}504505impl Drop for Error {506 fn drop(&mut self) {

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

line 507why, one step back
507 unsafe {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 508why, one step back
508 // Read Box<ErrorImpl<()>> from self.

Ptr read only needs a const ptrDavid Tolnaybefore adoption83f63a6

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

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

line 510why, one step back
510 let erased = ManuallyDrop::into_inner(inner);

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 511–512why, one step back
511
512 // Invoke the vtable's drop behavior.

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

lines 513–514why, one step back
513 (erased.vtable.object_drop)(erased);
514 }

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 515–517why, one step back
515 }
516}517

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

line 518why, one step back
518struct ErrorVTable {

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

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

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

line 520why, one step back
520 object_ref: unsafe fn(&ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static),

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 521why, one step back
521 #[cfg(feature = "std")]

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

line 522why, one step back
522 object_mut: unsafe fn(&mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static),

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 524–525why, one step back
524 object_downcast: unsafe fn(&ErrorImpl<()>, TypeId) -> Option<NonNull<()>>,
525 object_drop_rest: unsafe fn(Box<ErrorImpl<()>>, TypeId),

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

lines 526–527why, one step back
526}
527

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 528why, one step back
528// Safety: requires layout of *e to match ErrorImpl<E>.

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

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

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

lines 533–535why, one step back
533 drop(unerased);
534}535

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 536why, one step back
536// Safety: requires layout of *e to match ErrorImpl<E>.

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

line 537why, one step back
537unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>, target: TypeId) {

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

lines 538–540why, one step back
538 // Drop the fields of ErrorImpl other than E as well as the Box allocation,
539 // without dropping E itself. This is used by downcast after doing a540 // ptr::read to take ownership of the E.

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

line 541why, one step back
541 let _ = target;

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

line 542why, one step back
542 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<ManuallyDrop<E>>>>(e);

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 546why, one step back
546// Safety: requires layout of *e to match ErrorImpl<E>.

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

line 547why, one step back
547unsafe fn object_ref<E>(e: &ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static)

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

lines 548–550why, one step back
548where
549 E: StdError + Send + Sync + 'static,550{

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 551why, one step back
551 // Attach E's native StdError vtable onto a pointer to self._object.

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

lines 553–554why, one step back
553}
554

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 555why, one step back
555// Safety: requires layout of *e to match ErrorImpl<E>.

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 556why, one step back
556#[cfg(feature = "std")]

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

line 557why, one step back
557unsafe fn object_mut<E>(e: &mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static)

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

lines 558–560why, one step back
558where
559 E: StdError + Send + Sync + 'static,560{

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 561why, one step back
561 // Attach E's native StdError vtable onto a pointer to self._object.

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

lines 563–564why, one step back
563}
564

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 565why, one step back
565// Safety: requires layout of *e to match ErrorImpl<E>.

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 566–569why, one step back
566unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>
567where568 E: StdError + Send + Sync + 'static,569{

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 570why, one step back
570 // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 571–573why, one step back
571 mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e)
572}573

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 574why, one step back
574// Safety: requires layout of *e to match ErrorImpl<E>.

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

line 575why, one step back
575unsafe fn object_downcast<E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

line 576why, one step back
576where

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

line 577why, one step back
577 E: 'static,

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

line 578why, one step back
578{

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

line 579why, one step back
579 if TypeId::of::<E>() == target {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 580–581why, one step back
580 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a
581 // pointer to its E field.

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 582–587why, one step back
582 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<E>;
583 let addr = &(*unerased)._object as *const E as *mut ();584 Some(NonNull::new_unchecked(addr))585 } else {586 None587 }

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 590why, one step back
590// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 591why, one step back
591#[cfg(feature = "std")]

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 592–609why, one step back
592unsafe fn context_downcast<C, E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>
593where594 C: 'static,595 E: 'static,596{597 if TypeId::of::<C>() == target {598 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;599 let addr = &(*unerased)._object.context as *const C as *mut ();600 Some(NonNull::new_unchecked(addr))601 } else if TypeId::of::<E>() == target {602 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;603 let addr = &(*unerased)._object.error as *const E as *mut ();604 Some(NonNull::new_unchecked(addr))605 } else {606 None607 }608}609

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 610why, one step back
610// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 611why, one step back
611#[cfg(feature = "std")]

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 612–633why, one step back
612unsafe fn context_drop_rest<C, E>(e: Box<ErrorImpl<()>>, target: TypeId)
613where614 C: 'static,615 E: 'static,616{617 // Called after downcasting by value to either the C or the E and doing a618 // ptr::read to take ownership of that value.619 if TypeId::of::<C>() == target {620 let unerased = mem::transmute::<621 Box<ErrorImpl<()>>,622 Box<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>,623 >(e);624 drop(unerased);625 } else {626 let unerased = mem::transmute::<627 Box<ErrorImpl<()>>,628 Box<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>,629 >(e);630 drop(unerased);631 }632}633

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 634why, one step back
634// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 635–643why, one step back
635unsafe fn context_chain_downcast<C>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>
636where637 C: 'static,638{639 if TypeId::of::<C>() == target {640 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;641 let addr = &(*unerased)._object.context as *const C as *mut ();642 Some(NonNull::new_unchecked(addr))643 } else {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 644why, one step back
644 // Recurse down the context chain per the inner error's vtable.

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 645–650why, one step back
645 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;
646 let source = &(*unerased)._object.error;647 (source.inner.vtable.object_downcast)(&source.inner, target)648 }649}650

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 651why, one step back
651// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 652–662why, one step back
652unsafe fn context_chain_drop_rest<C>(e: Box<ErrorImpl<()>>, target: TypeId)
653where654 C: 'static,655{656 // Called after downcasting by value to either the C or one of the causes657 // and doing a ptr::read to take ownership of that value.658 if TypeId::of::<C>() == target {659 let unerased = mem::transmute::<660 Box<ErrorImpl<()>>,661 Box<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>,662 >(e);

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 663why, one step back
663 // Drop the entire rest of the data structure rooted in the next Error.

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 664–669why, one step back
664 drop(unerased);
665 } else {666 let unerased = mem::transmute::<667 Box<ErrorImpl<()>>,668 Box<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>,669 >(e);

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 670why, one step back
670 // Read out a ManuallyDrop<Box<ErrorImpl<()>>> from the next error.

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 671–673why, one step back
671 let inner = ptr::read(&unerased._object.error.inner);
672 drop(unerased);673 let erased = ManuallyDrop::into_inner(inner);

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 674why, one step back
674 // Recursively drop the next error using the same target typeid.

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 675–679why, one step back
675 (erased.vtable.object_drop_rest)(erased, target);
676 }677}678679// repr C to ensure that E remains in the final position.

Add readme stubDavid Tolnaybefore adoptiond28ff29

line 680why, one step back
680#[repr(C)]

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

line 681why, one step back
681pub(crate) struct ErrorImpl<E> {

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

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

Add readme stubDavid Tolnaybefore adoptiond28ff29

line 683why, one step back
683 backtrace: Option<Backtrace>,

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 684–686why, one step back
684 // NOTE: Don't use directly. Use only through vtable. Erased type may have
685 // different alignment.686 _object: E,

Move ContextError to error.rs in preparation for refactorDavid Tolnaybefore adoption30c2eab

lines 687–688why, one step back
687}
688

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 689–691why, one step back
689// repr C to ensure that ContextError<C, E> has the same layout as
690// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.691#[repr(C)]

Move ContextError to error.rs in preparation for refactorDavid Tolnaybefore adoption30c2eab

lines 692–694why, one step back
692pub(crate) struct ContextError<C, E> {
693 pub context: C,694 pub error: E,

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 695–696why, one step back
695}
696

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

lines 697–698why, one step back
697impl<E> ErrorImpl<E> {
698 fn erase(&self) -> &ErrorImpl<()> {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 699–701why, one step back
699 // Erase the concrete type of E but preserve the vtable in self.vtable
700 // for manipulating the resulting thin pointer. This is analogous to an701 // unsize coersion.

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

lines 702–705why, one step back
702 unsafe { &*(self as *const ErrorImpl<E> as *const ErrorImpl<()>) }
703 }704}705

Add readme stubDavid Tolnaybefore adoptiond28ff29

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

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 708–709why, one step back
708 // Use vtable to attach E's native StdError vtable for the right
709 // original type E.

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

line 710why, one step back
710 unsafe { &*(self.vtable.object_ref)(self) }

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 711–712why, one step back
711 }
712

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 713why, one step back
713 #[cfg(feature = "std")]

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 715–716why, one step back
715 // Use vtable to attach E's native StdError vtable for the right
716 // original type E.

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

line 717why, one step back
717 unsafe { &mut *(self.vtable.object_mut)(self) }

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 718–720why, one step back
718 }
719720 #[cfg(backtrace)]

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 722–730why, one step back
722 // This unwrap can only panic if the underlying error's backtrace method
723 // is nondeterministic, which would only happen in maliciously724 // constructed code.725 self.backtrace726 .as_ref()727 .or_else(|| self.error().backtrace())728 .expect("backtrace capture failed")729 }730

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

line 731why, one step back
731 pub(crate) fn chain(&self) -> Chain {

Add a Chain::new constructorDavid Tolnaybefore adoptionca2b8b9

line 732why, one step back
732 Chain::new(self.error())

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 733–735why, one step back
733 }
734}735

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

lines 736–743why, one step back
736impl<E> StdError for ErrorImpl<E>
737where738 E: StdError,739{740 #[cfg(backtrace)]741 fn backtrace(&self) -> Option<&Backtrace> {742 Some(self.erase().backtrace())743 }

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

line 744why, one step back
744

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

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

Merge pull request #16 from johnschug/masterDavid Tolnaybefore adoptioneeaf2ef

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

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

lines 747–749why, one step back
747 }
748}749

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 750–754why, one step back
750impl<E> Debug for ErrorImpl<E>
751where752 E: Debug,753{754 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 756–763why, one step back
756 }
757}758759impl<E> Display for ErrorImpl<E>760where761 E: Display,762{763 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {

Merge pull request #16 from johnschug/masterDavid Tolnaybefore adoptioneeaf2ef

line 764why, one step back
764 Display::fmt(&self.erase().error(), formatter)

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 765–771why, one step back
765 }
766}767768impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {769 fn from(error: Error) -> Self {770 let outer = ManuallyDrop::new(error);771 unsafe {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 772–773why, one step back
772 // Read Box<ErrorImpl<()>> from error. Can't move it out because
773 // Error has a Drop impl which we want to not run.

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 774–775why, one step back
774 let inner = ptr::read(&outer.inner);
775 let erased = ManuallyDrop::into_inner(inner);

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 776–778why, one step back
776
777 // Use vtable to attach ErrorImpl<E>'s native StdError vtable for778 // the right original type E.

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 779–780why, one step back
779 (erased.vtable.object_boxed)(erased)
780 }

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 781–783why, one step back
781 }
782}783

Merge pull request #28 from dtolnay/fromDavid Tolnaybefore adoption68225d2

lines 784–786why, one step back
784impl From<Error> for Box<dyn StdError + 'static> {
785 fn from(error: Error) -> Self {786 Box::<dyn StdError + Send + Sync>::from(error)

Add readme stubDavid Tolnaybefore adoptiond28ff29

lines 787–788why, one step back
787 }
788}

Add AsRef impls for ErrorDavid Tolnaybefore adoption2c88164

line 789why, one step back
789

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 790why, one step back
790#[cfg(feature = "std")]

Add AsRef impls for ErrorDavid Tolnaybefore adoption2c88164

lines 791–796why, one step back
791impl AsRef<dyn StdError + Send + Sync> for Error {
792 fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {793 &**self794 }795}796

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 797why, one step back
797#[cfg(feature = "std")]

Add AsRef impls for ErrorDavid Tolnaybefore adoption2c88164

lines 798–802why, one step back
798impl AsRef<dyn StdError> for Error {
799 fn as_ref(&self) -> &(dyn StdError + 'static) {800 &**self801 }802}