Skip to content
Myr

error.rs

This file

Path

src/error.rs

793 lines · 26.6 KiB · Rust

Last changed by

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

History of this file

Take 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 exception module to errorDavid Tolnaybefore adoption2000930

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 Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 13why, one step back
13impl Error {

Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 15why, one step back
15 ///

Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066

lines 16–17why, one step back
16 /// The error type must be threadsafe and `'static`, so that the `Error`
17 /// will be as well.

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 18why, one step back
18 ///

Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066

lines 19–20why, one step back
19 /// If the error type does not provide a backtrace, a backtrace will be
20 /// 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 exception module to errorDavid Tolnaybefore adoption2000930

line 23why, one step back
23 where

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

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 25why, one step back
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 exception module to errorDavid Tolnaybefore adoption2000930

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 exception module to errorDavid Tolnaybefore adoption2000930

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 exception module to errorDavid Tolnaybefore adoption2000930

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 exception module to errorDavid Tolnaybefore adoption2000930

line 189why, one step back
189 where

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

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 191why, one step back
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 exception module to errorDavid Tolnaybefore adoption2000930

lines 286–287why, one step back
286 }
287

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 288why, one step back
288 /// 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 ///

Mention env var in Error::backtrace documentationDavid Tolnaybefore adoption4119806

lines 293–297why, one step back
293 /// In order for the backtrace to be meaningful, the environment variable
294 /// `RUST_LIB_BACKTRACE=1` must be defined. Backtraces are somewhat295 /// expensive to capture in Rust, so we don't necessarily want to be296 /// capturing them all over the place all the time.297 ///

Detect nightly and only expose backtrace if availableDavid Tolnaybefore adoption270ea5e

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 302–303why, one step back
302 }
303

Rename Errors to ChainDavid Tolnaybefore adoptionf972193

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 305why, one step back
305 ///

Rename Errors to ChainDavid Tolnaybefore adoptionf972193

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

Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066

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

Add example of Error::chainDavid Tolnaybefore adoptiond159b79

lines 309–324why, one step back
309 ///
310 /// # Example311 ///312 /// ```313 /// use anyhow::Error;314 /// use std::io;315 ///316 /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {317 /// for cause in error.chain() {318 /// if let Some(io_error) = cause.downcast_ref::<io::Error>() {319 /// return Some(io_error.kind());320 /// }321 /// }322 /// None323 /// }324 /// ```

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Rename Errors to ChainDavid Tolnaybefore adoptionf972193

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 328–329why, one step back
328 }
329

Add Error::root_cause accessorDavid Tolnaybefore adoption1ea72bb

lines 330–334why, one step back
330 /// The lowest level cause of this error &mdash; this error's cause's
331 /// cause's cause etc.332 ///333 /// The root cause is the last error in the iterator produced by334 /// [`chain()`][Error::chain].

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Add Error::root_cause accessorDavid Tolnaybefore adoption1ea72bb

lines 336–344why, one step back
336 pub fn root_cause(&self) -> &(dyn StdError + 'static) {
337 let mut chain = self.chain();338 let mut root_cause = chain.next().unwrap();339 for cause in chain {340 root_cause = cause;341 }342 root_cause343 }344

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 345–352why, one step back
345 /// Returns true if `E` is the type held by this error object.
346 ///347 /// For errors with context, this method returns true if `E` matches the348 /// type of the context `C` **or** the type of the error on which the349 /// context has been attached. For details about the interaction between350 /// context and downcasting, [see here].351 ///352 /// [see here]: trait.Context.html#effect-on-downcasting

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 358–359why, one step back
358 }
359

Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c

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

Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337

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

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

lines 362–364why, one step back
362 where
363 E: Display + Debug + Send + Sync + 'static,364 {

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 373–375why, one step back
373
374 // Prepare to read E out of the data structure. We'll drop the rest375 // of the data structure separately so that E is not dropped.

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 388why, one step back
388

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

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

Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c

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

Add example to Error::downcast_refDavid Tolnaybefore adoption0c21b7a

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

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 439–441why, one step back
439 }
440 }441

Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c

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

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

lines 443–446why, one step back
443 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>
444 where445 E: Display + Debug + Send + Sync + 'static,446 {

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 453–455why, one step back
453 }
454 }455}

Remove use of attributes on function parametersDavid Tolnaybefore adoptiona2d7e2f

line 456why, one step back
456

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

lines 458–461why, one step back
458impl<E> From<E> for Error
459where460 E: StdError + Send + Sync + 'static,461{

Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337

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

Capture backtraces earlierDavid Tolnaybefore adoptionc06155e

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 465–467why, one step back
465 }
466}467

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

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

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

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

Remove as_dyn_error methods from ErrorDavid Tolnaybefore adoption73c7283

line 471why, one step back
471

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 472–476why, one step back
472 fn deref(&self) -> &Self::Target {
473 self.inner.error()474 }475}476

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 479–483why, one step back
479 fn deref_mut(&mut self) -> &mut Self::Target {
480 self.inner.error_mut()481 }482}483

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 487–489why, one step back
487 }
488}489

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

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

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

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

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

line 498why, one step back
498 unsafe {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Ptr read only needs a const ptrDavid Tolnaybefore adoption83f63a6

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

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

lines 504–505why, one step back
504 (erased.vtable.object_drop)(erased);
505 }

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 506–508why, one step back
506 }
507}508

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

line 509why, one step back
509struct ErrorVTable {

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

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

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

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

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

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

lines 517–518why, one step back
517}
518

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

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

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

lines 524–526why, one step back
524 drop(unerased);
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>.

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608

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

Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

lines 535–536why, one step back
535}
536

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

lines 539–541why, one step back
539where
540 E: StdError + Send + Sync + 'static,541{

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

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

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 557–560why, one step back
557unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>
558where559 E: StdError + Send + Sync + 'static,560{

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 562–564why, one step back
562 mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e)
563}564

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

line 567why, one step back
567where

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

line 569why, one step back
569{

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 573–578why, one step back
573 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<E>;
574 let addr = &(*unerased)._object as *const E as *mut ();575 Some(NonNull::new_unchecked(addr))576 } else {577 None578 }

Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93

lines 579–580why, one step back
579}
580

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 583–600why, one step back
583unsafe fn context_downcast<C, E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>
584where585 C: 'static,586 E: 'static,587{588 if TypeId::of::<C>() == target {589 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;590 let addr = &(*unerased)._object.context as *const C as *mut ();591 Some(NonNull::new_unchecked(addr))592 } else if TypeId::of::<E>() == target {593 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;594 let addr = &(*unerased)._object.error as *const E as *mut ();595 Some(NonNull::new_unchecked(addr))596 } else {597 None598 }599}600

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 603–624why, one step back
603unsafe fn context_drop_rest<C, E>(e: Box<ErrorImpl<()>>, target: TypeId)
604where605 C: 'static,606 E: 'static,607{608 // Called after downcasting by value to either the C or the E and doing a609 // ptr::read to take ownership of that value.610 if TypeId::of::<C>() == target {611 let unerased = mem::transmute::<612 Box<ErrorImpl<()>>,613 Box<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>,614 >(e);615 drop(unerased);616 } else {617 let unerased = mem::transmute::<618 Box<ErrorImpl<()>>,619 Box<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>,620 >(e);621 drop(unerased);622 }623}624

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 626–634why, one step back
626unsafe fn context_chain_downcast<C>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>
627where628 C: 'static,629{630 if TypeId::of::<C>() == target {631 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;632 let addr = &(*unerased)._object.context as *const C as *mut ();633 Some(NonNull::new_unchecked(addr))634 } else {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 636–641why, one step back
636 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;
637 let source = &(*unerased)._object.error;638 (source.inner.vtable.object_downcast)(&source.inner, target)639 }640}641

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 655–660why, one step back
655 drop(unerased);
656 } else {657 let unerased = mem::transmute::<658 Box<ErrorImpl<()>>,659 Box<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>,660 >(e);

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 666–670why, one step back
666 (erased.vtable.object_drop_rest)(erased, target);
667 }668}669670// repr C to ensure that E remains in the final position.

Rename exception module to errorDavid Tolnaybefore adoption2000930

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

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

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

Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

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

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

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

lines 678–679why, one step back
678}
679

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

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

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

lines 683–685why, one step back
683pub(crate) struct ContextError<C, E> {
684 pub context: C,685 pub error: E,

Rename exception module to errorDavid Tolnaybefore adoption2000930

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

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 690–692why, one step back
690 // Erase the concrete type of E but preserve the vtable in self.vtable
691 // for manipulating the resulting thin pointer. This is analogous to an692 // unsize coersion.

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

lines 693–696why, one step back
693 unsafe { &*(self as *const ErrorImpl<E> as *const ErrorImpl<()>) }
694 }695}696

Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84

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

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

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

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 702–703why, one step back
702 }
703

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

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

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 709–711why, one step back
709 }
710711 #[cfg(backtrace)]

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 713–721why, one step back
713 // This unwrap can only panic if the underlying error's backtrace method
714 // is nondeterministic, which would only happen in maliciously715 // constructed code.716 self.backtrace717 .as_ref()718 .or_else(|| self.error().backtrace())719 .expect("backtrace capture failed")720 }721

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

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

Add a Chain::new constructorDavid Tolnaybefore adoptionca2b8b9

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 724–726why, one step back
724 }
725}726

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

lines 727–734why, one step back
727impl<E> StdError for ErrorImpl<E>
728where729 E: StdError,730{731 #[cfg(backtrace)]732 fn backtrace(&self) -> Option<&Backtrace> {733 Some(self.erase().backtrace())734 }

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

line 735why, one step back
735

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

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

Merge pull request #16 from johnschug/masterDavid Tolnaybefore adoptioneeaf2ef

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

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

lines 738–740why, one step back
738 }
739}740

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 741–745why, one step back
741impl<E> Debug for ErrorImpl<E>
742where743 E: Debug,744{745 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {

Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Merge pull request #16 from johnschug/masterDavid Tolnaybefore adoptioneeaf2ef

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 756–762why, one step back
756 }
757}758759impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {760 fn from(error: Error) -> Self {761 let outer = ManuallyDrop::new(error);762 unsafe {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 767–769why, one step back
767
768 // Use vtable to attach ErrorImpl<E>'s native StdError vtable for769 // the right original type E.

Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8

lines 770–771why, one step back
770 (erased.vtable.object_boxed)(erased)
771 }

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 772–774why, one step back
772 }
773}774

Merge pull request #28 from dtolnay/fromDavid Tolnaybefore adoption68225d2

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

Rename exception module to errorDavid Tolnaybefore adoption2000930

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

Add AsRef impls for ErrorDavid Tolnaybefore adoption2c88164

line 780why, one step back
780

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Add AsRef impls for ErrorDavid Tolnaybefore adoption2c88164

lines 782–787why, one step back
782impl AsRef<dyn StdError + Send + Sync> for Error {
783 fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {784 &**self785 }786}787

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Add AsRef impls for ErrorDavid Tolnaybefore adoption2c88164

lines 789–793why, one step back
789impl AsRef<dyn StdError> for Error {
790 fn as_ref(&self) -> &(dyn StdError + 'static) {791 &**self792 }793}