Skip to content
Myr

error.rs

This file

Path

src/error.rs

967 lines · 32.9 KiB · Rust

Last changed by

Merge pull request #178 from dtolnay/upDavid Tolnaybefore adoption3c586dd

History of this file

Take it

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 2why, one step back
2use crate::chain::Chain;

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

lines 3–5why, one step back
3#[cfg(any(feature = "std", anyhow_no_ptr_addr_of))]
4use crate::ptr::Mut;5use crate::ptr::{Own, Ref};

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 6why, one step back
6use crate::{Error, StdError};

Merge pull request #178 from dtolnay/upDavid Tolnaybefore adoption3c586dd

line 7why, one step back
7use alloc::boxed::Box;

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

lines 8–9why, one step back
8use core::any::TypeId;
9use core::fmt::{self, Debug, Display};

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

line 10why, one step back
10use core::mem::ManuallyDrop;

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

lines 11–12why, one step back
11#[cfg(not(anyhow_no_ptr_addr_of))]
12use core::ptr;

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 13why, one step back
13use core::ptr::NonNull;

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

line 14why, one step back
14

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 18–25why, one step back
18impl Error {
19 /// Create a new error object from any error type.20 ///21 /// The error type must be threadsafe and `'static`, so that the `Error`22 /// will be as well.23 ///24 /// If the error type does not provide a backtrace, a backtrace will be25 /// created here to ensure that a backtrace exists.

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #78 from dtolnay/cfgDavid Tolnaybefore adoptione2eb1f5

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

Merge pull request #166 from stepancheg/coldDavid Tolnaybefore adoption447eff8

line 28why, one step back
28 #[cold]

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 29–73why, one step back
29 pub fn new<E>(error: E) -> Self
30 where31 E: StdError + Send + Sync + 'static,32 {33 let backtrace = backtrace_if_absent!(error);34 Error::from_std(error, backtrace)35 }3637 /// Create a new error object from a printable error message.38 ///39 /// If the argument implements std::error::Error, prefer `Error::new`40 /// instead which preserves the underlying error's cause chain and41 /// backtrace. If the argument may or may not implement std::error::Error42 /// now or in the future, use `anyhow!(err)` which handles either way43 /// correctly.44 ///45 /// `Error::msg("...")` is equivalent to `anyhow!("...")` but occasionally46 /// convenient in places where a function is preferable over a macro, such47 /// as iterator or stream combinators:48 ///49 /// ```50 /// # mod ffi {51 /// # pub struct Input;52 /// # pub struct Output;53 /// # pub async fn do_some_work(_: Input) -> Result<Output, &'static str> {54 /// # unimplemented!()55 /// # }56 /// # }57 /// #58 /// # use ffi::{Input, Output};59 /// #60 /// use anyhow::{Error, Result};61 /// use futures::stream::{Stream, StreamExt, TryStreamExt};62 ///63 /// async fn demo<S>(stream: S) -> Result<Vec<Output>>64 /// where65 /// S: Stream<Item = Input>,66 /// {67 /// stream68 /// .then(ffi::do_some_work) // returns Result<Output, &str>69 /// .map_err(Error::msg)70 /// .try_collect()71 /// .await72 /// }73 /// ```

Merge pull request #166 from stepancheg/coldDavid Tolnaybefore adoption447eff8

line 74why, one step back
74 #[cold]

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 75–81why, one step back
75 pub fn msg<M>(message: M) -> Self
76 where77 M: Display + Debug + Send + Sync + 'static,78 {79 Error::from_adhoc(message, backtrace!())80 }81

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #166 from stepancheg/coldDavid Tolnaybefore adoption447eff8

line 83why, one step back
83 #[cold]

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 84–90why, one step back
84 pub(crate) fn from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self
85 where86 E: StdError + Send + Sync + 'static,87 {88 let vtable = &ErrorVTable {89 object_drop: object_drop::<E>,90 object_ref: object_ref::<E>,

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

line 91why, one step back
91 #[cfg(anyhow_no_ptr_addr_of)]

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 92–94why, one step back
92 object_mut: object_mut::<E>,
93 object_boxed: object_boxed::<E>,94 object_downcast: object_downcast::<E>,

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

line 95why, one step back
95 #[cfg(anyhow_no_ptr_addr_of)]

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

line 96why, one step back
96 object_downcast_mut: object_downcast_mut::<E>,

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

line 97why, one step back
97 object_drop_rest: object_drop_front::<E>,

Merge pull request #143 from dtolnay/backtraceDavid Tolnaybefore adoptiond65af36

lines 98–99why, one step back
98 #[cfg(all(not(backtrace), feature = "backtrace"))]
99 object_backtrace: no_backtrace,

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 100–105why, one step back
100 };
101102 // Safety: passing vtable that operates on the right type E.103 unsafe { Error::construct(error, vtable, backtrace) }104 }105

Merge pull request #166 from stepancheg/coldDavid Tolnaybefore adoption447eff8

line 106why, one step back
106 #[cold]

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 107–110why, one step back
107 pub(crate) fn from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> Self
108 where109 M: Display + Debug + Send + Sync + 'static,110 {

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 112–115why, one step back
112 let error: MessageError<M> = MessageError(message);
113 let vtable = &ErrorVTable {114 object_drop: object_drop::<MessageError<M>>,115 object_ref: object_ref::<MessageError<M>>,

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 117–119why, one step back
117 object_mut: object_mut::<MessageError<M>>,
118 object_boxed: object_boxed::<MessageError<M>>,119 object_downcast: object_downcast::<M>,

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

line 120why, one step back
120 #[cfg(anyhow_no_ptr_addr_of)]

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

line 121why, one step back
121 object_downcast_mut: object_downcast_mut::<M>,

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

line 122why, one step back
122 object_drop_rest: object_drop_front::<M>,

Merge pull request #143 from dtolnay/backtraceDavid Tolnaybefore adoptiond65af36

lines 123–124why, one step back
123 #[cfg(all(not(backtrace), feature = "backtrace"))]
124 object_backtrace: no_backtrace,

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

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

Merge pull request #166 from stepancheg/coldDavid Tolnaybefore adoption447eff8

line 132why, one step back
132 #[cold]

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 133–136why, one step back
133 pub(crate) fn from_display<M>(message: M, backtrace: Option<Backtrace>) -> Self
134 where135 M: Display + Send + Sync + 'static,136 {

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 138–141why, one step back
138 let error: DisplayError<M> = DisplayError(message);
139 let vtable = &ErrorVTable {140 object_drop: object_drop::<DisplayError<M>>,141 object_ref: object_ref::<DisplayError<M>>,

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 143–145why, one step back
143 object_mut: object_mut::<DisplayError<M>>,
144 object_boxed: object_boxed::<DisplayError<M>>,145 object_downcast: object_downcast::<M>,

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

line 146why, one step back
146 #[cfg(anyhow_no_ptr_addr_of)]

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

line 147why, one step back
147 object_downcast_mut: object_downcast_mut::<M>,

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

line 148why, one step back
148 object_drop_rest: object_drop_front::<M>,

Merge pull request #143 from dtolnay/backtraceDavid Tolnaybefore adoptiond65af36

lines 149–150why, one step back
149 #[cfg(all(not(backtrace), feature = "backtrace"))]
150 object_backtrace: no_backtrace,

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 151–157why, one step back
151 };
152153 // Safety: DisplayError is repr(transparent) so it is okay for the154 // vtable to allow casting the DisplayError<M> to M.155 unsafe { Error::construct(error, vtable, backtrace) }156 }157

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #166 from stepancheg/coldDavid Tolnaybefore adoption447eff8

line 159why, one step back
159 #[cold]

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 160–169why, one step back
160 pub(crate) fn from_context<C, E>(context: C, error: E, backtrace: Option<Backtrace>) -> Self
161 where162 C: Display + Send + Sync + 'static,163 E: StdError + Send + Sync + 'static,164 {165 let error: ContextError<C, E> = ContextError { context, error };166167 let vtable = &ErrorVTable {168 object_drop: object_drop::<ContextError<C, E>>,169 object_ref: object_ref::<ContextError<C, E>>,

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

line 170why, one step back
170 #[cfg(anyhow_no_ptr_addr_of)]

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 171–173why, one step back
171 object_mut: object_mut::<ContextError<C, E>>,
172 object_boxed: object_boxed::<ContextError<C, E>>,173 object_downcast: context_downcast::<C, E>,

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

line 174why, one step back
174 #[cfg(anyhow_no_ptr_addr_of)]

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

line 175why, one step back
175 object_downcast_mut: context_downcast_mut::<C, E>,

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

line 176why, one step back
176 object_drop_rest: context_drop_rest::<C, E>,

Merge pull request #143 from dtolnay/backtraceDavid Tolnaybefore adoptiond65af36

lines 177–178why, one step back
177 #[cfg(all(not(backtrace), feature = "backtrace"))]
178 object_backtrace: no_backtrace,

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 179–181why, one step back
179 };
180181 // Safety: passing vtable that operates on the right type.

Merge pull request #50 from dtolnay/boxedDavid Tolnaybefore adoption74fbea6

lines 182–184why, one step back
182 unsafe { Error::construct(error, vtable, backtrace) }
183 }184

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #166 from stepancheg/coldDavid Tolnaybefore adoption447eff8

line 186why, one step back
186 #[cold]

Merge pull request #50 from dtolnay/boxedDavid Tolnaybefore adoption74fbea6

lines 187–190why, one step back
187 pub(crate) fn from_boxed(
188 error: Box<dyn StdError + Send + Sync>,189 backtrace: Option<Backtrace>,190 ) -> Self {

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Merge pull request #50 from dtolnay/boxedDavid Tolnaybefore adoption74fbea6

lines 192–195why, one step back
192 let error = BoxedError(error);
193 let vtable = &ErrorVTable {194 object_drop: object_drop::<BoxedError>,195 object_ref: object_ref::<BoxedError>,

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

line 196why, one step back
196 #[cfg(anyhow_no_ptr_addr_of)]

Merge pull request #50 from dtolnay/boxedDavid Tolnaybefore adoption74fbea6

lines 197–199why, one step back
197 object_mut: object_mut::<BoxedError>,
198 object_boxed: object_boxed::<BoxedError>,199 object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

line 200why, one step back
200 #[cfg(anyhow_no_ptr_addr_of)]

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

line 201why, one step back
201 object_downcast_mut: object_downcast_mut::<Box<dyn StdError + Send + Sync>>,

Merge pull request #50 from dtolnay/boxedDavid Tolnaybefore adoption74fbea6

line 202why, one step back
202 object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,

Merge pull request #143 from dtolnay/backtraceDavid Tolnaybefore adoptiond65af36

lines 203–204why, one step back
203 #[cfg(all(not(backtrace), feature = "backtrace"))]
204 object_backtrace: no_backtrace,

Merge pull request #50 from dtolnay/boxedDavid Tolnaybefore adoption74fbea6

lines 205–208why, one step back
205 };
206207 // Safety: BoxedError is repr(transparent) so it is okay for the vtable208 // to allow casting to Box<dyn StdError + Send + Sync>.

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 209–216why, one step back
209 unsafe { Error::construct(error, vtable, backtrace) }
210 }211212 // Takes backtrace as argument rather than capturing it here so that the213 // user sees one fewer layer of wrapping noise in the backtrace.214 //215 // Unsafe because the given vtable must have sensible behavior on the error216 // value of type E.

Merge pull request #166 from stepancheg/coldDavid Tolnaybefore adoption447eff8

line 217why, one step back
217 #[cold]

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 218–225why, one step back
218 unsafe fn construct<E>(
219 error: E,220 vtable: &'static ErrorVTable,221 backtrace: Option<Backtrace>,222 ) -> Self223 where224 E: StdError + Send + Sync + 'static,225 {

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

line 226why, one step back
226 let inner: Box<ErrorImpl<E>> = Box::new(ErrorImpl {

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 227–230why, one step back
227 vtable,
228 backtrace,229 _object: error,230 });

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Fix typo coersion -> coercionDavid Tolnaybefore adoptionfd0268b

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 237why, one step back
237 let inner = Own::new(inner).cast::<ErrorImpl>();

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 238–294why, one step back
238 Error { inner }
239 }240241 /// Wrap the error value with additional context.242 ///243 /// For attaching context to a `Result` as it is propagated, the244 /// [`Context`][crate::Context] extension trait may be more convenient than245 /// this function.246 ///247 /// The primary reason to use `error.context(...)` instead of248 /// `result.context(...)` via the `Context` trait would be if the context249 /// needs to depend on some data held by the underlying error:250 ///251 /// ```252 /// # use std::fmt::{self, Debug, Display};253 /// #254 /// # type T = ();255 /// #256 /// # impl std::error::Error for ParseError {}257 /// # impl Debug for ParseError {258 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {259 /// # unimplemented!()260 /// # }261 /// # }262 /// # impl Display for ParseError {263 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {264 /// # unimplemented!()265 /// # }266 /// # }267 /// #268 /// use anyhow::Result;269 /// use std::fs::File;270 /// use std::path::Path;271 ///272 /// struct ParseError {273 /// line: usize,274 /// column: usize,275 /// }276 ///277 /// fn parse_impl(file: File) -> Result<T, ParseError> {278 /// # const IGNORE: &str = stringify! {279 /// ...280 /// # };281 /// # unimplemented!()282 /// }283 ///284 /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {285 /// let file = File::open(&path)?;286 /// parse_impl(file).map_err(|error| {287 /// let context = format!(288 /// "only the first {} lines of {} are valid",289 /// error.line, path.as_ref().display(),290 /// );291 /// anyhow::Error::new(error).context(context)292 /// })293 /// }294 /// ```

Merge pull request #166 from stepancheg/coldDavid Tolnaybefore adoption447eff8

line 295why, one step back
295 #[cold]

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 296–307why, one step back
296 pub fn context<C>(self, context: C) -> Self
297 where298 C: Display + Send + Sync + 'static,299 {300 let error: ContextError<C, Error> = ContextError {301 context,302 error: self,303 };304305 let vtable = &ErrorVTable {306 object_drop: object_drop::<ContextError<C, Error>>,307 object_ref: object_ref::<ContextError<C, Error>>,

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 309–311why, one step back
309 object_mut: object_mut::<ContextError<C, Error>>,
310 object_boxed: object_boxed::<ContextError<C, Error>>,311 object_downcast: context_chain_downcast::<C>,

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

line 312why, one step back
312 #[cfg(anyhow_no_ptr_addr_of)]

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

line 313why, one step back
313 object_downcast_mut: context_chain_downcast_mut::<C>,

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

line 314why, one step back
314 object_drop_rest: context_chain_drop_rest::<C>,

Merge pull request #143 from dtolnay/backtraceDavid Tolnaybefore adoptiond65af36

lines 315–316why, one step back
315 #[cfg(all(not(backtrace), feature = "backtrace"))]
316 object_backtrace: context_backtrace::<C>,

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 317–327why, one step back
317 };
318319 // As the cause is anyhow::Error, we already have a backtrace for it.320 let backtrace = None;321322 // Safety: passing vtable that operates on the right type.323 unsafe { Error::construct(error, vtable, backtrace) }324 }325326 /// Get the backtrace for this Error.327 ///

Merge pull request #70 from dtolnay/envDavid Tolnaybefore adoption8d2acea

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

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

Merge pull request #70 from dtolnay/envDavid Tolnaybefore adoption8d2acea

lines 333–339why, one step back
333 ///
334 /// - If you want panics and errors to both have backtraces, set335 /// `RUST_BACKTRACE=1`;336 /// - If you want only errors to have backtraces, set337 /// `RUST_LIB_BACKTRACE=1`;338 /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and339 /// `RUST_LIB_BACKTRACE=0`.

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

line 340why, one step back
340 ///

Merge pull request #143 from dtolnay/backtraceDavid Tolnaybefore adoptiond65af36

lines 341–354why, one step back
341 /// # Stability
342 ///343 /// Standard library backtraces are only available on the nightly channel.344 /// Tracking issue: [rust-lang/rust#53487][tracking].345 ///346 /// On stable compilers, this function is only available if the crate's347 /// "backtrace" feature is enabled, and will use the `backtrace` crate as348 /// the underlying backtrace implementation.349 ///350 /// ```toml351 /// [dependencies]352 /// anyhow = { version = "1.0", features = ["backtrace"] }353 /// ```354 ///

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

line 355why, one step back
355 /// [tracking]: https://github.com/rust-lang/rust/issues/53487

Merge pull request #143 from dtolnay/backtraceDavid Tolnaybefore adoptiond65af36

lines 356–358why, one step back
356 #[cfg(any(backtrace, feature = "backtrace"))]
357 #[cfg_attr(doc_cfg, doc(cfg(any(nightly, feature = "backtrace"))))]358 pub fn backtrace(&self) -> &impl_backtrace!() {

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 359why, one step back
359 unsafe { ErrorImpl::backtrace(self.inner.by_ref()) }

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 360–382why, one step back
360 }
361362 /// An iterator of the chain of source errors contained by this Error.363 ///364 /// This iterator will visit every error in the cause chain of this error365 /// object, beginning with the error that this error object was created366 /// from.367 ///368 /// # Example369 ///370 /// ```371 /// use anyhow::Error;372 /// use std::io;373 ///374 /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {375 /// for cause in error.chain() {376 /// if let Some(io_error) = cause.downcast_ref::<io::Error>() {377 /// return Some(io_error.kind());378 /// }379 /// }380 /// None381 /// }382 /// ```

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

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

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

Merge pull request #166 from stepancheg/coldDavid Tolnaybefore adoption447eff8

line 385why, one step back
385 #[cold]

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 387why, one step back
387 unsafe { ErrorImpl::chain(self.inner.by_ref()) }

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 388–394why, one step back
388 }
389390 /// The lowest level cause of this error &mdash; this error's cause's391 /// cause's cause etc.392 ///393 /// The root cause is the last error in the iterator produced by394 /// [`chain()`][Error::chain].

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

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

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

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

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

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 399–416why, one step back
399 }
400401 /// Returns true if `E` is the type held by this error object.402 ///403 /// For errors with context, this method returns true if `E` matches the404 /// type of the context `C` **or** the type of the error on which the405 /// context has been attached. For details about the interaction between406 /// context and downcasting, [see here].407 ///408 /// [see here]: trait.Context.html#effect-on-downcasting409 pub fn is<E>(&self) -> bool410 where411 E: Display + Debug + Send + Sync + 'static,412 {413 self.downcast_ref::<E>().is_some()414 }415416 /// Attempt to downcast the error object to a concrete type.

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 418–421why, one step back
418 where
419 E: Display + Debug + Send + Sync + 'static,420 {421 let target = TypeId::of::<E>();

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

line 422why, one step back
422 let inner = self.inner.by_mut();

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

line 423why, one step back
423 unsafe {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

lines 426–435why, one step back
426 #[cfg(not(anyhow_no_ptr_addr_of))]
427 let addr = match (vtable(inner.ptr).object_downcast)(inner.by_ref(), target) {428 Some(addr) => addr.by_mut().extend(),429 None => return Err(self),430 };431 #[cfg(anyhow_no_ptr_addr_of)]432 let addr = match (vtable(inner.ptr).object_downcast_mut)(inner, target) {433 Some(addr) => addr.extend(),434 None => return Err(self),435 };

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 436–438why, one step back
436
437 // Prepare to read E out of the data structure. We'll drop the rest438 // of the data structure separately so that E is not dropped.

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 445why, one step back
445 (vtable(outer.inner.ptr).object_drop_rest)(outer.inner, target);

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 446why, one step back
446

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 447–492why, one step back
447 Ok(error)
448 }449 }450451 /// Downcast this error object by reference.452 ///453 /// # Example454 ///455 /// ```456 /// # use anyhow::anyhow;457 /// # use std::fmt::{self, Display};458 /// # use std::task::Poll;459 /// #460 /// # #[derive(Debug)]461 /// # enum DataStoreError {462 /// # Censored(()),463 /// # }464 /// #465 /// # impl Display for DataStoreError {466 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {467 /// # unimplemented!()468 /// # }469 /// # }470 /// #471 /// # impl std::error::Error for DataStoreError {}472 /// #473 /// # const REDACTED_CONTENT: () = ();474 /// #475 /// # let error = anyhow!("...");476 /// # let root_cause = &error;477 /// #478 /// # let ret =479 /// // If the error was caused by redaction, then return a tombstone instead480 /// // of the content.481 /// match root_cause.downcast_ref::<DataStoreError>() {482 /// Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),483 /// None => Err(error),484 /// }485 /// # ;486 /// ```487 pub fn downcast_ref<E>(&self) -> Option<&E>488 where489 E: Display + Debug + Send + Sync + 'static,490 {491 let target = TypeId::of::<E>();492 unsafe {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

lines 495–496why, one step back
495 let addr = (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?;
496 Some(addr.cast::<E>().deref())

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 497–506why, one step back
497 }
498 }499500 /// Downcast this error object by mutable reference.501 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>502 where503 E: Display + Debug + Send + Sync + 'static,504 {505 let target = TypeId::of::<E>();506 unsafe {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

lines 509–514why, one step back
509
510 #[cfg(not(anyhow_no_ptr_addr_of))]511 let addr =512 (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?.by_mut();513514 #[cfg(anyhow_no_ptr_addr_of)]

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 515why, one step back
515 let addr = (vtable(self.inner.ptr).object_downcast_mut)(self.inner.by_mut(), target)?;

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

line 516why, one step back
516

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 517why, one step back
517 Some(addr.cast::<E>().deref_mut())

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 518–521why, one step back
518 }
519 }520}521

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

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

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 524–527why, one step back
524impl<E> From<E> for Error
525where526 E: StdError + Send + Sync + 'static,527{

Merge pull request #166 from stepancheg/coldDavid Tolnaybefore adoption447eff8

line 528why, one step back
528 #[cold]

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 529–534why, one step back
529 fn from(error: E) -> Self {
530 let backtrace = backtrace_if_absent!(error);531 Error::from_std(error, backtrace)532 }533}534

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

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

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 537–540why, one step back
537impl Deref for Error {
538 type Target = dyn StdError + Send + Sync + 'static;539540 fn deref(&self) -> &Self::Target {

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 541why, one step back
541 unsafe { ErrorImpl::error(self.inner.by_ref()) }

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

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

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 547–548why, one step back
547impl DerefMut for Error {
548 fn deref_mut(&mut self) -> &mut Self::Target {

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 549why, one step back
549 unsafe { ErrorImpl::error_mut(self.inner.by_mut()) }

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 550–554why, one step back
550 }
551}552553impl Display for Error {554 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 555why, one step back
555 unsafe { ErrorImpl::display(self.inner.by_ref(), formatter) }

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 556–560why, one step back
556 }
557}558559impl Debug for Error {560 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 561why, one step back
561 unsafe { ErrorImpl::debug(self.inner.by_ref(), formatter) }

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 562–567why, one step back
562 }
563}564565impl Drop for Error {566 fn drop(&mut self) {567 unsafe {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

line 568why, one step back
568 // Invoke the vtable's drop behavior.

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 569why, one step back
569 (vtable(self.inner.ptr).object_drop)(self.inner);

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 570–574why, one step back
570 }
571 }572}573574struct ErrorVTable {

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 575why, one step back
575 object_drop: unsafe fn(Own<ErrorImpl>),

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

lines 576–577why, one step back
576 object_ref: unsafe fn(Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>,
577 #[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

lines 578–580why, one step back
578 object_mut: unsafe fn(Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static),
579 object_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,580 object_downcast: unsafe fn(Ref<ErrorImpl>, TypeId) -> Option<Ref<()>>,

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

line 581why, one step back
581 #[cfg(anyhow_no_ptr_addr_of)]

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

lines 582–583why, one step back
582 object_downcast_mut: unsafe fn(Mut<ErrorImpl>, TypeId) -> Option<Mut<()>>,
583 object_drop_rest: unsafe fn(Own<ErrorImpl>, TypeId),

Merge pull request #143 from dtolnay/backtraceDavid Tolnaybefore adoptiond65af36

lines 584–585why, one step back
584 #[cfg(all(not(backtrace), feature = "backtrace"))]
585 object_backtrace: unsafe fn(Ref<ErrorImpl>) -> Option<&Backtrace>,

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

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

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 589why, one step back
589unsafe fn object_drop<E>(e: Own<ErrorImpl>) {

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 590–591why, one step back
590 // Cast back to ErrorImpl<E> so that the allocator receives the correct
591 // Layout to deallocate the Box's memory.

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 592why, one step back
592 let unerased = e.cast::<ErrorImpl<E>>().boxed();

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 593–595why, one step back
593 drop(unerased);
594}595

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 598–601why, one step back
598 // Drop the fields of ErrorImpl other than E as well as the Box allocation,
599 // without dropping E itself. This is used by downcast after doing a600 // ptr::read to take ownership of the E.601 let _ = target;

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 602why, one step back
602 let unerased = e.cast::<ErrorImpl<ManuallyDrop<E>>>().boxed();

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 603–605why, one step back
603 drop(unerased);
604}605

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 608–610why, one step back
608where
609 E: StdError + Send + Sync + 'static,610{

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

lines 612–621why, one step back
612
613 let unerased = e.cast::<ErrorImpl<E>>();614615 #[cfg(not(anyhow_no_ptr_addr_of))]616 return Ref::from_raw(NonNull::new_unchecked(617 ptr::addr_of!((*unerased.as_ptr())._object) as *mut E,618 ));619620 #[cfg(anyhow_no_ptr_addr_of)]621 return Ref::new(&unerased.deref()._object);

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 622–623why, one step back
622}
623

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

lines 624–625why, one step back
624// Safety: requires layout of *e to match ErrorImpl<E>, and for `e` to be derived
625// from a `&mut`

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 628–630why, one step back
628where
629 E: StdError + Send + Sync + 'static,630{

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 632why, one step back
632 &mut e.cast::<ErrorImpl<E>>().deref_mut()._object

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 633–634why, one step back
633}
634

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 637–639why, one step back
637where
638 E: StdError + Send + Sync + 'static,639{

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 641why, one step back
641 e.cast::<ErrorImpl<E>>().boxed()

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 642–643why, one step back
642}
643

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 646–649why, one step back
646where
647 E: 'static,648{649 if TypeId::of::<E>() == target {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

lines 652–664why, one step back
652
653 let unerased = e.cast::<ErrorImpl<E>>();654655 #[cfg(not(anyhow_no_ptr_addr_of))]656 return Some(657 Ref::from_raw(NonNull::new_unchecked(658 ptr::addr_of!((*unerased.as_ptr())._object) as *mut E,659 ))660 .cast::<()>(),661 );662663 #[cfg(anyhow_no_ptr_addr_of)]664 return Some(Ref::new(&unerased.deref()._object).cast::<()>());

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 665–669why, one step back
665 } else {
666 None667 }668}669

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

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

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

line 671why, one step back
671#[cfg(anyhow_no_ptr_addr_of)]

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 672why, one step back
672unsafe fn object_downcast_mut<E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

lines 673–678why, one step back
673where
674 E: 'static,675{676 if TypeId::of::<E>() == target {677 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a678 // pointer to its E field.

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

lines 679–680why, one step back
679 let unerased = e.cast::<ErrorImpl<E>>().deref_mut();
680 Some(Mut::new(&mut unerased._object).cast::<()>())

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

lines 681–685why, one step back
681 } else {
682 None683 }684}685

Merge pull request #143 from dtolnay/backtraceDavid Tolnaybefore adoptiond65af36

lines 686–691why, one step back
686#[cfg(all(not(backtrace), feature = "backtrace"))]
687fn no_backtrace(e: Ref<ErrorImpl>) -> Option<&Backtrace> {688 let _ = e;689 None690}691

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 694why, one step back
694unsafe fn context_downcast<C, E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 695–699why, one step back
695where
696 C: 'static,697 E: 'static,698{699 if TypeId::of::<C>() == target {

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

lines 700–701why, one step back
700 let unerased = e.cast::<ErrorImpl<ContextError<C, E>>>().deref();
701 Some(Ref::new(&unerased._object.context).cast::<()>())

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

lines 703–704why, one step back
703 let unerased = e.cast::<ErrorImpl<ContextError<C, E>>>().deref();
704 Some(Ref::new(&unerased._object.error).cast::<()>())

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 705–709why, one step back
705 } else {
706 None707 }708}709

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 712why, one step back
712unsafe fn context_downcast_mut<C, E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 713–716why, one step back
713where
714 C: 'static,715 E: 'static,716{

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

lines 718–719why, one step back
718 let unerased = e.cast::<ErrorImpl<ContextError<C, E>>>().deref_mut();
719 Some(Mut::new(&mut unerased._object.context).cast::<()>())

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

lines 721–722why, one step back
721 let unerased = e.cast::<ErrorImpl<ContextError<C, E>>>().deref_mut();
722 Some(Mut::new(&mut unerased._object.error).cast::<()>())

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

lines 723–729why, one step back
723 } else {
724 None725 }726}727728// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.729#[cfg(feature = "std")]

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 730why, one step back
730unsafe fn context_drop_rest<C, E>(e: Own<ErrorImpl>, target: TypeId)

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

lines 731–734why, one step back
731where
732 C: 'static,733 E: 'static,734{

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 735–737why, one step back
735 // Called after downcasting by value to either the C or the E and doing a
736 // ptr::read to take ownership of that value.737 if TypeId::of::<C>() == target {

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

lines 738–740why, one step back
738 let unerased = e
739 .cast::<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>()740 .boxed();

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 741–742why, one step back
741 drop(unerased);
742 } else {

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

lines 743–745why, one step back
743 let unerased = e
744 .cast::<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>()745 .boxed();

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 746–749why, one step back
746 drop(unerased);
747 }748}749

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 751why, one step back
751unsafe fn context_chain_downcast<C>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 752–754why, one step back
752where
753 C: 'static,754{

Resolve branches_sharing_code clippy lintDavid Tolnaybefore adoptionaa6c83d

line 755why, one step back
755 let unerased = e.cast::<ErrorImpl<ContextError<C, Error>>>().deref();

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 757why, one step back
757 Some(Ref::new(&unerased._object.context).cast::<()>())

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

line 758why, one step back
758 } else {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

lines 760–761why, one step back
760 let source = &unerased._object.error;
761 (vtable(source.inner.ptr).object_downcast)(source.inner.by_ref(), target)

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 762–764why, one step back
762 }
763}764

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

line 766why, one step back
766#[cfg(anyhow_no_ptr_addr_of)]

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 767why, one step back
767unsafe fn context_chain_downcast_mut<C>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 768–770why, one step back
768where
769 C: 'static,770{

Resolve branches_sharing_code clippy lintDavid Tolnaybefore adoptionaa6c83d

line 771why, one step back
771 let unerased = e.cast::<ErrorImpl<ContextError<C, Error>>>().deref_mut();

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 773why, one step back
773 Some(Mut::new(&mut unerased._object.context).cast::<()>())

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

lines 774–775why, one step back
774 } else {
775 // Recurse down the context chain per the inner error's vtable.

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

lines 776–777why, one step back
776 let source = &mut unerased._object.error;
777 (vtable(source.inner.ptr).object_downcast_mut)(source.inner.by_mut(), target)

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

lines 778–781why, one step back
778 }
779}780781// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 782why, one step back
782unsafe fn context_chain_drop_rest<C>(e: Own<ErrorImpl>, target: TypeId)

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

lines 783–785why, one step back
783where
784 C: 'static,785{

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 786–788why, one step back
786 // Called after downcasting by value to either the C or one of the causes
787 // and doing a ptr::read to take ownership of that value.788 if TypeId::of::<C>() == target {

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

lines 789–791why, one step back
789 let unerased = e
790 .cast::<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>()791 .boxed();

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 793–794why, one step back
793 drop(unerased);
794 } else {

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

lines 795–798why, one step back
795 let unerased = e
796 .cast::<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>()797 .boxed();798 // Read the Own<ErrorImpl> from the next error.

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

line 799why, one step back
799 let inner = unerased._object.error.inner;

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 801why, one step back
801 let vtable = vtable(inner.ptr);

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

line 803why, one step back
803 (vtable.object_drop_rest)(inner, target);

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 804–806why, one step back
804 }
805}806

Merge pull request #143 from dtolnay/backtraceDavid Tolnaybefore adoptiond65af36

lines 807–818why, one step back
807// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.
808#[cfg(all(not(backtrace), feature = "backtrace"))]809#[allow(clippy::unnecessary_wraps)]810unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>811where812 C: 'static,813{814 let unerased = e.cast::<ErrorImpl<ContextError<C, Error>>>().deref();815 let backtrace = ErrorImpl::backtrace(unerased._object.error.inner.by_ref());816 Some(backtrace)817}818

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

lines 819–820why, one step back
819// NOTE: If working with `ErrorImpl<()>`, references should be avoided in favor
820// of raw pointers and `NonNull`.

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

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

Elide ErrorImpl type parameter if erasedDavid Tolnaybefore adoptionbd5e39b

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

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 824–830why, one step back
824 vtable: &'static ErrorVTable,
825 backtrace: Option<Backtrace>,826 // NOTE: Don't use directly. Use only through vtable. Erased type may have827 // different alignment.828 _object: E,829}830

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

lines 831–832why, one step back
831// Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but
832// avoids converting `p` into a reference.

Only need vtable function for a type erased ErrorImplDavid Tolnaybefore adoptiond1b0c9a

line 833why, one step back
833unsafe fn vtable(p: NonNull<ErrorImpl>) -> &'static ErrorVTable {

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

line 834why, one step back
834 // NOTE: This assumes that `ErrorVTable` is the first field of ErrorImpl.

Restore compatibility with rustc pre-1.38David Tolnaybefore adoptionf3fe8bd

line 835why, one step back
835 *(p.as_ptr() as *const &'static ErrorVTable)

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

lines 836–837why, one step back
836}
837

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 838–846why, one step back
838// repr C to ensure that ContextError<C, E> has the same layout as
839// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.840#[repr(C)]841pub(crate) struct ContextError<C, E> {842 pub context: C,843 pub error: E,844}845846impl<E> ErrorImpl<E> {

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 847why, one step back
847 fn erase(&self) -> Ref<ErrorImpl> {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Fix typo coersion -> coercionDavid Tolnaybefore adoptionfd0268b

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 851why, one step back
851 Ref::new(self).cast::<ErrorImpl>()

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 852–854why, one step back
852 }
853}854

Elide ErrorImpl type parameter if erasedDavid Tolnaybefore adoptionbd5e39b

line 855why, one step back
855impl ErrorImpl {

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 856why, one step back
856 pub(crate) unsafe fn error(this: Ref<Self>) -> &(dyn StdError + Send + Sync + 'static) {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

line 859why, one step back
859 (vtable(this.ptr).object_ref)(this).deref()

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 860–861why, one step back
860 }
861

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 863why, one step back
863 pub(crate) unsafe fn error_mut(this: Mut<Self>) -> &mut (dyn StdError + Send + Sync + 'static) {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

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

Merge pull request #145 from dtolnay/addrofDavid Tolnaybefore adoption64ac0c0

lines 866–873why, one step back
866
867 #[cfg(not(anyhow_no_ptr_addr_of))]868 return (vtable(this.ptr).object_ref)(this.by_ref())869 .by_mut()870 .deref_mut();871872 #[cfg(anyhow_no_ptr_addr_of)]873 return (vtable(this.ptr).object_mut)(this);

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 874–875why, one step back
874 }
875

Merge pull request #143 from dtolnay/backtraceDavid Tolnaybefore adoptiond65af36

line 876why, one step back
876 #[cfg(any(backtrace, feature = "backtrace"))]

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 877why, one step back
877 pub(crate) unsafe fn backtrace(this: Ref<Self>) -> &Backtrace {

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 878–880why, one step back
878 // This unwrap can only panic if the underlying error's backtrace method
879 // is nondeterministic, which would only happen in maliciously880 // constructed code.

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 881why, one step back
881 this.deref()

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

line 882why, one step back
882 .backtrace

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

line 883why, one step back
883 .as_ref()

Merge pull request #143 from dtolnay/backtraceDavid Tolnaybefore adoptiond65af36

lines 884–889why, one step back
884 .or_else(|| {
885 #[cfg(backtrace)]886 return Self::error(this).backtrace();887 #[cfg(all(not(backtrace), feature = "backtrace"))]888 return (vtable(this.ptr).object_backtrace)(this);889 })

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 890–892why, one step back
890 .expect("backtrace capture failed")
891 }892

Merge pull request #166 from stepancheg/coldDavid Tolnaybefore adoption447eff8

line 893why, one step back
893 #[cold]

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 894why, one step back
894 pub(crate) unsafe fn chain(this: Ref<Self>) -> Chain {

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

line 895why, one step back
895 Chain::new(Self::error(this))

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 896–904why, one step back
896 }
897}898899impl<E> StdError for ErrorImpl<E>900where901 E: StdError,902{903 #[cfg(backtrace)]904 fn backtrace(&self) -> Option<&Backtrace> {

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

line 905why, one step back
905 Some(unsafe { ErrorImpl::backtrace(self.erase()) })

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 906–908why, one step back
906 }
907908 fn source(&self) -> Option<&(dyn StdError + 'static)> {

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

line 909why, one step back
909 unsafe { ErrorImpl::error(self.erase()).source() }

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 910–917why, one step back
910 }
911}912913impl<E> Debug for ErrorImpl<E>914where915 E: Debug,916{917 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

line 918why, one step back
918 unsafe { ErrorImpl::debug(self.erase(), formatter) }

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 919–926why, one step back
919 }
920}921922impl<E> Display for ErrorImpl<E>923where924 E: Display,925{926 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {

Merge pull request 134 from thomcc/mirimiriDavid Tolnaybefore adoptionae372df

line 927why, one step back
927 unsafe { Display::fmt(ErrorImpl::error(self.erase()), formatter) }

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 928–931why, one step back
928 }
929}930931impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {

Merge pull request #166 from stepancheg/coldDavid Tolnaybefore adoption447eff8

line 932why, one step back
932 #[cold]

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 933–935why, one step back
933 fn from(error: Error) -> Self {
934 let outer = ManuallyDrop::new(error);935 unsafe {

Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60

lines 936–937why, one step back
936 // Use vtable to attach ErrorImpl<E>'s native StdError vtable for
937 // the right original type E.

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 938why, one step back
938 (vtable(outer.inner.ptr).object_boxed)(outer.inner)

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 939–942why, one step back
939 }
940 }941}942

Merge pull request #104 from dtolnay/fromDavid Tolnaybefore adoption03a1916

lines 943–948why, one step back
943impl From<Error> for Box<dyn StdError + Send + 'static> {
944 fn from(error: Error) -> Self {945 Box::<dyn StdError + Send + Sync>::from(error)946 }947}948

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

lines 949–953why, one step back
949impl From<Error> for Box<dyn StdError + 'static> {
950 fn from(error: Error) -> Self {951 Box::<dyn StdError + Send + Sync>::from(error)952 }953}

Add AsRef impls for ErrorDavid Tolnaybefore adoption2c88164

line 954why, one step back
954

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Add AsRef impls for ErrorDavid Tolnaybefore adoption2c88164

lines 956–961why, one step back
956impl AsRef<dyn StdError + Send + Sync> for Error {
957 fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {958 &**self959 }960}961

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

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

Add AsRef impls for ErrorDavid Tolnaybefore adoption2c88164

lines 963–967why, one step back
963impl AsRef<dyn StdError> for Error {
964 fn as_ref(&self) -> &(dyn StdError + 'static) {965 &**self966 }967}