Skip to content
Myr

error.rs

This file

Path

src/error.rs

801 lines · 27.0 KiB · Rust

Last changed by

Merge pull request #70 from dtolnay/envDavid Tolnaybefore adoption8d2acea

History of this file

Take it

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

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

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

Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9

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

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

line 29why, one step back
29

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

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9

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

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

lines 83–84why, one step back
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) }

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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) }

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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–145why, 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>>,

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Expand ContextError vtable to prepare for extending downcast supportDavid Tolnaybefore adoption45e6fc6

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Expand ContextError vtable to prepare for extending downcast supportDavid Tolnaybefore adoption45e6fc6

lines 151–153why, one step back
151 };
152153 // Safety: passing vtable that operates on the right type.

Merge pull request #50 from dtolnay/boxedDavid Tolnaybefore adoption74fbea6

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #50 from dtolnay/boxedDavid Tolnaybefore adoption74fbea6

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #50 from dtolnay/boxedDavid Tolnaybefore adoption74fbea6

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #50 from dtolnay/boxedDavid Tolnaybefore adoption74fbea6

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

Expand ContextError vtable to prepare for extending downcast supportDavid Tolnaybefore adoption45e6fc6

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

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

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

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

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

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

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

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

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

line 196why, one step back
196 });

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

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

Add context method to ErrorDavid Tolnaybefore adoption41fde4c

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

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

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

Explain the purpose of Error::contextDavid Tolnaybefore adoption896dd7a

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

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

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

Explain the purpose of Error::contextDavid Tolnaybefore adoption896dd7a

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

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

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

Explain the purpose of Error::contextDavid Tolnaybefore adoption896dd7a

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

Add context method to ErrorDavid Tolnaybefore adoption41fde4c

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

Specify types where the manual vtable relies on themDavid Tolnaybefore adoptionb261a64

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

Add context method to ErrorDavid Tolnaybefore adoption41fde4c

line 267why, one step back
267 context,

Swap ContextError type parameters to match type nameDavid Tolnaybefore adoption9f38495

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

Eliminate backtrace_if_absent in Error::contextDavid Tolnaybefore adoptiona2846fd

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Eliminate backtrace_if_absent in Error::contextDavid Tolnaybefore adoptiona2846fd

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Eliminate backtrace_if_absent in Error::contextDavid Tolnaybefore adoptiona2846fd

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Detect nightly and only expose backtrace if availableDavid Tolnaybefore adoption270ea5e

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

Merge pull request #70 from dtolnay/envDavid Tolnaybefore adoption8d2acea

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

Mention env var in Error::backtrace documentationDavid Tolnaybefore adoption4119806

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

Merge pull request #70 from dtolnay/envDavid Tolnaybefore adoption8d2acea

lines 298–304why, one step back
298 ///
299 /// - If you want panics and errors to both have backtraces, set300 /// `RUST_BACKTRACE=1`;301 /// - If you want only errors to have backtraces, set302 /// `RUST_LIB_BACKTRACE=1`;303 /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and304 /// `RUST_LIB_BACKTRACE=0`.

Mention env var in Error::backtrace documentationDavid Tolnaybefore adoption4119806

line 305why, one step back
305 ///

Detect nightly and only expose backtrace if availableDavid Tolnaybefore adoption270ea5e

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

lines 310–311why, one step back
310 }
311

Rename Errors to ChainDavid Tolnaybefore adoptionf972193

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

line 313why, one step back
313 ///

Rename Errors to ChainDavid Tolnaybefore adoptionf972193

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Add example of Error::chainDavid Tolnaybefore adoptiond159b79

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Rename Errors to ChainDavid Tolnaybefore adoptionf972193

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Add Error::root_cause accessorDavid Tolnaybefore adoption1ea72bb

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Add Error::root_cause accessorDavid Tolnaybefore adoption1ea72bb

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

lines 366–368why, one step back
366 }
367368 /// Attempt to downcast the error object to a concrete type.

Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 396why, one step back
396

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

lines 398–401why, one step back
398 }
399 }400401 /// Downcast this error object by reference.

Add example to Error::downcast_refDavid Tolnaybefore adoption0c21b7a

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Remove use of attributes on function parametersDavid Tolnaybefore adoptiona2d7e2f

line 464why, one step back
464

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

lines 466–469why, one step back
466impl<E> From<E> for Error
467where468 E: StdError + Send + Sync + 'static,469{

Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337

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

Capture backtraces earlierDavid Tolnaybefore adoptionc06155e

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Remove as_dyn_error methods from ErrorDavid Tolnaybefore adoption73c7283

line 479why, one step back
479

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

lines 501–505why, one step back
501 }
502}503504impl Drop for Error {505 fn drop(&mut self) {

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

line 506why, one step back
506 unsafe {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Ptr read only needs a const ptrDavid Tolnaybefore adoption83f63a6

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

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

line 517why, one step back
517struct ErrorVTable {

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

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

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

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

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

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

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

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

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

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

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

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

line 575why, one step back
575where

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

line 577why, one step back
577{

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

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

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

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

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

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

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

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

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

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

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Add a Chain::new constructorDavid Tolnaybefore adoptionca2b8b9

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

line 743why, one step back
743

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

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

Merge pull request #16 from johnschug/masterDavid Tolnaybefore adoptioneeaf2ef

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

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 755–762why, one step back
755 }
756}757758impl<E> Display for ErrorImpl<E>759where760 E: Display,761{762 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {

Merge pull request #16 from johnschug/masterDavid Tolnaybefore adoptioneeaf2ef

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Merge pull request #28 from dtolnay/fromDavid Tolnaybefore adoption68225d2

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

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

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

Add AsRef impls for ErrorDavid Tolnaybefore adoption2c88164

line 788why, one step back
788

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Add AsRef impls for ErrorDavid Tolnaybefore adoption2c88164

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Add AsRef impls for ErrorDavid Tolnaybefore adoption2c88164

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