Skip to content
Myr

error.rs

This file

Path

src/error.rs

805 lines · 27.2 KiB · Rust

Last changed by

Merge pull request #128 from dtolnay/doc-cfgDavid Tolnaybefore adoption0c0e41f

History of this file

Take it

The walk stopped after 200 commits: lines older than 3adc96a 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};

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

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")))]

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 23–26why, one step back
23 pub fn new<E>(error: E) -> Self
24 where25 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–84why, one step back
80 let vtable = &ErrorVTable {
81 object_drop: object_drop::<E>,82 object_ref: object_ref::<E>,83 object_mut: object_mut::<E>,84 object_boxed: object_boxed::<E>,

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

line 87why, one step back
87 };

Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9

line 88why, one step back
88

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

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

Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Specify types where the manual vtable relies on themDavid Tolnaybefore adoptionb261a64

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

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

line 107why, one step back
107 };

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

line 108why, one step back
108

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

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

Merge pull request #8 from dtolnay/optionDavid Tolnaybefore adoption240cc83

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Specify types where the manual vtable relies on themDavid Tolnaybefore adoptionb261a64

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

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

line 128why, one step back
128 };

Merge pull request #8 from dtolnay/optionDavid Tolnaybefore adoption240cc83

line 129why, one step back
129

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

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

Merge pull request #8 from dtolnay/optionDavid Tolnaybefore adoption240cc83

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Expand ContextError vtable to prepare for extending downcast supportDavid Tolnaybefore adoption45e6fc6

line 136why, one step back
136 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 137–140why, one step back
137 where
138 C: Display + Send + Sync + 'static,139 E: StdError + Send + Sync + 'static,140 {

Expand ContextError vtable to prepare for extending downcast supportDavid Tolnaybefore adoption45e6fc6

lines 141–147why, one step back
141 let error: ContextError<C, E> = ContextError { context, error };
142143 let vtable = &ErrorVTable {144 object_drop: object_drop::<ContextError<C, E>>,145 object_ref: object_ref::<ContextError<C, E>>,146 object_mut: object_mut::<ContextError<C, E>>,147 object_boxed: object_boxed::<ContextError<C, E>>,

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Expand ContextError vtable to prepare for extending downcast supportDavid Tolnaybefore adoption45e6fc6

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

Merge pull request #50 from dtolnay/boxedDavid Tolnaybefore adoption74fbea6

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #50 from dtolnay/boxedDavid Tolnaybefore adoption74fbea6

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #50 from dtolnay/boxedDavid Tolnaybefore adoption74fbea6

lines 162–173why, one step back
162 let error = BoxedError(error);
163 let vtable = &ErrorVTable {164 object_drop: object_drop::<BoxedError>,165 object_ref: object_ref::<BoxedError>,166 object_mut: object_mut::<BoxedError>,167 object_boxed: object_boxed::<BoxedError>,168 object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,169 object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,170 };171172 // Safety: BoxedError is repr(transparent) so it is okay for the vtable173 // to allow casting to Box<dyn StdError + Send + Sync>.

Expand ContextError vtable to prepare for extending downcast supportDavid Tolnaybefore adoption45e6fc6

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

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

lines 175–176why, one step back
175 }
176

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

lines 177–178why, one step back
177 // Takes backtrace as argument rather than capturing it here so that the
178 // 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 179why, one step back
179 //

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 187–189why, one step back
187 where
188 E: StdError + Send + Sync + 'static,189 {

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

lines 190–192why, one step back
190 let inner = Box::new(ErrorImpl {
191 vtable,192 backtrace,

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

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

line 194why, one step back
194 });

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 195why, one step back
195 // Erase the concrete type of E from the compile-time type system. This

Fix typo coersion -> coercionDavid Tolnaybefore adoptionfd0268b

line 196why, one step back
196 // is equivalent to the safe unsize coercion from Box<ErrorImpl<E>> to

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 197–200why, one step back
197 // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the
198 // result is a thin pointer. The necessary behavior for manipulating the199 // underlying ErrorImpl<E> is preserved in the vtable provided by the200 // caller rather than a builtin fat pointer vtable.

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 204–206why, one step back
204 }
205206 /// Wrap the error value with additional context.

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

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

Explain the purpose of Error::contextDavid Tolnaybefore adoption896dd7a

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

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

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

Explain the purpose of Error::contextDavid Tolnaybefore adoption896dd7a

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

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

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

Explain the purpose of Error::contextDavid Tolnaybefore adoption896dd7a

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

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

Specify types where the manual vtable relies on themDavid Tolnaybefore adoptionb261a64

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

line 265why, one step back
265 context,

Swap ContextError type parameters to match type nameDavid Tolnaybefore adoption9f38495

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

Eliminate backtrace_if_absent in Error::contextDavid Tolnaybefore adoptiona2846fd

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Eliminate backtrace_if_absent in Error::contextDavid Tolnaybefore adoptiona2846fd

lines 273–274why, one step back
273 object_mut: object_mut::<ContextError<C, Error>>,
274 object_boxed: object_boxed::<ContextError<C, Error>>,

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 275–276why, one step back
275 object_downcast: context_chain_downcast::<C>,
276 object_drop_rest: context_chain_drop_rest::<C>,

Eliminate backtrace_if_absent in Error::contextDavid Tolnaybefore adoptiona2846fd

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 284–286why, one step back
284 }
285286 /// Get the backtrace for this Error.

Detect nightly and only expose backtrace if availableDavid Tolnaybefore adoption270ea5e

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

Merge pull request #70 from dtolnay/envDavid Tolnaybefore adoption8d2acea

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

Mention env var in Error::backtrace documentationDavid Tolnaybefore adoption4119806

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

Merge pull request #70 from dtolnay/envDavid Tolnaybefore adoption8d2acea

lines 296–302why, one step back
296 ///
297 /// - If you want panics and errors to both have backtraces, set298 /// `RUST_BACKTRACE=1`;299 /// - If you want only errors to have backtraces, set300 /// `RUST_LIB_BACKTRACE=1`;301 /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and302 /// `RUST_LIB_BACKTRACE=0`.

Mention env var in Error::backtrace documentationDavid Tolnaybefore adoption4119806

line 303why, one step back
303 ///

Detect nightly and only expose backtrace if availableDavid Tolnaybefore adoption270ea5e

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 308–314why, one step back
308 }
309310 /// An iterator of the chain of source errors contained by this Error.311 ///312 /// This iterator will visit every error in the cause chain of this error313 /// object, beginning with the error that this error object was created314 /// from.

Add example of Error::chainDavid Tolnaybefore adoptiond159b79

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #128 from dtolnay/doc-cfgDavid Tolnaybefore adoption0c0e41f

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

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

Add Error::root_cause accessorDavid Tolnaybefore adoption1ea72bb

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #128 from dtolnay/doc-cfgDavid Tolnaybefore adoption0c0e41f

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

Add Error::root_cause accessorDavid Tolnaybefore adoption1ea72bb

line 344why, one step back
344 pub fn root_cause(&self) -> &(dyn StdError + 'static) {

Merge pull request #108 from hbina/patch-1David Tolnaybefore adoption7954754

line 345why, one step back
345 self.chain().last().unwrap()

Add Error::root_cause accessorDavid Tolnaybefore adoption1ea72bb

lines 346–347why, one step back
346 }
347

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 356–359why, one step back
356 pub fn is<E>(&self) -> bool
357 where358 E: Display + Debug + Send + Sync + 'static,359 {

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 361–367why, one step back
361 }
362363 /// Attempt to downcast the error object to a concrete type.364 pub fn downcast<E>(self) -> Result<E, Self>365 where366 E: Display + Debug + Send + Sync + 'static,367 {

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 372–375why, one step back
372 let addr = match (self.inner.vtable.object_downcast)(&self.inner, target) {
373 Some(addr) => addr,374 None => return Err(self),375 };

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 376–378why, one step back
376
377 // Prepare to read E out of the data structure. We'll drop the rest378 // of the data structure separately so that E is not dropped.

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 391why, one step back
391

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 393–396why, one step back
393 }
394 }395396 /// Downcast this error object by reference.

Add example to Error::downcast_refDavid Tolnaybefore adoption0c21b7a

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 432–435why, one step back
432 pub fn downcast_ref<E>(&self) -> Option<&E>
433 where434 E: Display + Debug + Send + Sync + 'static,435 {

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 442–449why, one step back
442 }
443 }444445 /// Downcast this error object by mutable reference.446 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>447 where448 E: Display + Debug + Send + Sync + 'static,449 {

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 456–458why, one step back
456 }
457 }458}

Remove use of attributes on function parametersDavid Tolnaybefore adoptiona2d7e2f

line 459why, one step back
459

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #128 from dtolnay/doc-cfgDavid Tolnaybefore adoption0c0e41f

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 462–466why, one step back
462impl<E> From<E> for Error
463where464 E: StdError + Send + Sync + 'static,465{466 fn from(error: E) -> Self {

Capture backtraces earlierDavid Tolnaybefore adoptionc06155e

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 469–471why, one step back
469 }
470}471

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #128 from dtolnay/doc-cfgDavid Tolnaybefore adoption0c0e41f

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

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

Remove as_dyn_error methods from ErrorDavid Tolnaybefore adoption73c7283

line 476why, one step back
476

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 477–481why, one step back
477 fn deref(&self) -> &Self::Target {
478 self.inner.error()479 }480}481

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #128 from dtolnay/doc-cfgDavid Tolnaybefore adoption0c0e41f

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

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

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 493–495why, one step back
493 }
494}495

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 499–503why, one step back
499 }
500}501502impl Drop for Error {503 fn drop(&mut self) {

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

line 504why, one step back
504 unsafe {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Ptr read only needs a const ptrDavid Tolnaybefore adoption83f63a6

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

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

lines 510–511why, one step back
510 (erased.vtable.object_drop)(erased);
511 }

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 512–514why, one step back
512 }
513}514

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

line 515why, one step back
515struct ErrorVTable {

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

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

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

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

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

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

lines 523–524why, one step back
523}
524

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

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

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

lines 530–532why, one step back
530 drop(unerased);
531}532

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

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

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

lines 541–542why, one step back
541}
542

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 543why, one step back
543// 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 544why, one step back
544unsafe fn object_ref<E>(e: &ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static)

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

lines 545–547why, one step back
545where
546 E: StdError + Send + Sync + 'static,547{

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

lines 550–551why, one step back
550}
551

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

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

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

lines 555–557why, one step back
555where
556 E: StdError + Send + Sync + 'static,557{

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

lines 560–561why, one step back
560}
561

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 568–570why, one step back
568 mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e)
569}570

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

line 573why, one step back
573where

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

line 575why, one step back
575{

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

lines 585–586why, one step back
585}
586

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 672–676why, one step back
672 (erased.vtable.object_drop_rest)(erased, target);
673 }674}675676// repr C to ensure that E remains in the final position.

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

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

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

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

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

lines 684–685why, one step back
684}
685

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

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

lines 689–691why, one step back
689pub(crate) struct ContextError<C, E> {
690 pub context: C,691 pub error: E,

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 692–693why, one step back
692}
693

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 696–697why, one step back
696 // Erase the concrete type of E but preserve the vtable in self.vtable
697 // for manipulating the resulting thin pointer. This is analogous to an

Fix typo coersion -> coercionDavid Tolnaybefore adoptionfd0268b

line 698why, one step back
698 // unsize coercion.

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

lines 699–702why, one step back
699 unsafe { &*(self as *const ErrorImpl<E> as *const ErrorImpl<()>) }
700 }701}702

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

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

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

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

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 708–709why, one step back
708 }
709

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

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

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 715–717why, one step back
715 }
716717 #[cfg(backtrace)]

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 719–727why, one step back
719 // This unwrap can only panic if the underlying error's backtrace method
720 // is nondeterministic, which would only happen in maliciously721 // constructed code.722 self.backtrace723 .as_ref()724 .or_else(|| self.error().backtrace())725 .expect("backtrace capture failed")726 }727

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Add a Chain::new constructorDavid Tolnaybefore adoptionca2b8b9

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 730–732why, one step back
730 }
731}732

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

line 741why, one step back
741

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

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

Merge pull request #16 from johnschug/masterDavid Tolnaybefore adoptioneeaf2ef

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

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

lines 744–746why, one step back
744 }
745}746

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 753–760why, one step back
753 }
754}755756impl<E> Display for ErrorImpl<E>757where758 E: Display,759{760 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {

Merge pull request #16 from johnschug/masterDavid Tolnaybefore adoptioneeaf2ef

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 762–768why, one step back
762 }
763}764765impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {766 fn from(error: Error) -> Self {767 let outer = ManuallyDrop::new(error);768 unsafe {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 773–775why, one step back
773
774 // Use vtable to attach ErrorImpl<E>'s native StdError vtable for775 // the right original type E.

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 776–777why, one step back
776 (erased.vtable.object_boxed)(erased)
777 }

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 778–780why, one step back
778 }
779}780

Merge pull request #104 from dtolnay/fromDavid Tolnaybefore adoption03a1916

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

Merge pull request #28 from dtolnay/fromDavid Tolnaybefore adoption68225d2

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

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 790–791why, one step back
790 }
791}

Add AsRef impls for ErrorDavid Tolnaybefore adoption2c88164

line 792why, one step back
792

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Add AsRef impls for ErrorDavid Tolnaybefore adoption2c88164

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Add AsRef impls for ErrorDavid Tolnaybefore adoption2c88164

lines 801–805why, one step back
801impl AsRef<dyn StdError> for Error {
802 fn as_ref(&self) -> &(dyn StdError + 'static) {803 &**self804 }805}