error.rs
This file
Path
src/error.rs
1,031 lines · 36.2 KiB · Rust
Last changed by
Add construct_ prefix to name of private construct functionsDavid Tolnaybefore adoption671f700
History of this fileTake it
The walk stopped after 200 commits: lines older than 7290028 point at it.
Release 1.0.53David Tolnaybefore adoption7290028
lines 1–2why, one step back1use crate::backtrace::Backtrace;2use crate::chain::Chain;Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 3why, one step back3#[cfg(any(feature = "std", not(anyhow_no_core_error), anyhow_no_ptr_addr_of))]Release 1.0.53David Tolnaybefore adoption7290028
lines 4–8why, one step back4use crate::ptr::Mut;5use crate::ptr::{Own, Ref};6use crate::{Error, StdError};7use alloc::boxed::Box;8use core::any::TypeId;Merge pull request #382 from dtolnay/corerequestDavid Tolnaybefore adoption1eabf69
lines 9–10why, one step back9#[cfg(error_generic_member_access)]10use core::error::{self, Request};Release 1.0.53David Tolnaybefore adoption7290028
lines 11–12why, one step back11use core::fmt::{self, Debug, Display};12use core::mem::ManuallyDrop;Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
lines 13–14why, one step back13#[cfg(any(feature = "std", not(anyhow_no_core_error)))]14use core::ops::{Deref, DerefMut};Merge pull request #386 from dtolnay/unwindsafeDavid Tolnaybefore adoption830c399
lines 15–16why, one step back15#[cfg(not(anyhow_no_core_unwind_safe))]16use core::panic::{RefUnwindSafe, UnwindSafe};Release 1.0.53David Tolnaybefore adoption7290028
lines 17–19why, one step back17#[cfg(not(anyhow_no_ptr_addr_of))]18use core::ptr;19use core::ptr::NonNull;Merge pull request #386 from dtolnay/unwindsafeDavid Tolnaybefore adoption830c399
lines 20–21why, one step back20#[cfg(all(feature = "std", anyhow_no_core_unwind_safe))]21use std::panic::{RefUnwindSafe, UnwindSafe};Release 1.0.53David Tolnaybefore adoption7290028
lines 22–30why, one step back2223impl Error {24 /// Create a new error object from any error type.25 ///26 /// The error type must be threadsafe and `'static`, so that the `Error`27 /// will be as well.28 ///29 /// If the error type does not provide a backtrace, a backtrace will be30 /// created here to ensure that a backtrace exists.Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 31why, one step back31 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Release 1.0.53David Tolnaybefore adoption7290028
line 32why, one step back32 #[cold]Merge pull request #229 from dtolnay/must_useDavid Tolnaybefore adoptionc8a3e42
line 33why, one step back33 #[must_use]Release 1.0.53David Tolnaybefore adoption7290028
lines 34–37why, one step back34 pub fn new<E>(error: E) -> Self35 where36 E: StdError + Send + Sync + 'static,37 {Merge pull request #266 from dtolnay/providerDavid Tolnaybefore adoption546342c
line 38why, one step back38 let backtrace = backtrace_if_absent!(&error);Add construct_ prefix to name of private construct functionsDavid Tolnaybefore adoption671f700
line 39why, one step back39 Error::construct_from_std(error, backtrace)Release 1.0.53David Tolnaybefore adoption7290028
lines 40–79why, one step back40 }4142 /// Create a new error object from a printable error message.43 ///44 /// If the argument implements std::error::Error, prefer `Error::new`45 /// instead which preserves the underlying error's cause chain and46 /// backtrace. If the argument may or may not implement std::error::Error47 /// now or in the future, use `anyhow!(err)` which handles either way48 /// correctly.49 ///50 /// `Error::msg("...")` is equivalent to `anyhow!("...")` but occasionally51 /// convenient in places where a function is preferable over a macro, such52 /// as iterator or stream combinators:53 ///54 /// ```55 /// # mod ffi {56 /// # pub struct Input;57 /// # pub struct Output;58 /// # pub async fn do_some_work(_: Input) -> Result<Output, &'static str> {59 /// # unimplemented!()60 /// # }61 /// # }62 /// #63 /// # use ffi::{Input, Output};64 /// #65 /// use anyhow::{Error, Result};66 /// use futures::stream::{Stream, StreamExt, TryStreamExt};67 ///68 /// async fn demo<S>(stream: S) -> Result<Vec<Output>>69 /// where70 /// S: Stream<Item = Input>,71 /// {72 /// stream73 /// .then(ffi::do_some_work) // returns Result<Output, &str>74 /// .map_err(Error::msg)75 /// .try_collect()76 /// .await77 /// }78 /// ```79 #[cold]Merge pull request #229 from dtolnay/must_useDavid Tolnaybefore adoptionc8a3e42
line 80why, one step back80 #[must_use]Release 1.0.53David Tolnaybefore adoption7290028
lines 81–84why, one step back81 pub fn msg<M>(message: M) -> Self82 where83 M: Display + Debug + Send + Sync + 'static,84 {Add construct_ prefix to name of private construct functionsDavid Tolnaybefore adoption671f700
line 85why, one step back85 Error::construct_from_adhoc(message, backtrace!())Release 1.0.53David Tolnaybefore adoption7290028
lines 86–87why, one step back86 }87Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 88why, one step back88 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Release 1.0.53David Tolnaybefore adoption7290028
line 89why, one step back89 #[cold]Add construct_ prefix to name of private construct functionsDavid Tolnaybefore adoption671f700
line 90why, one step back90 pub(crate) fn construct_from_std<E>(error: E, backtrace: Option<Backtrace>) -> SelfRelease 1.0.53David Tolnaybefore adoption7290028
lines 91–103why, one step back91 where92 E: StdError + Send + Sync + 'static,93 {94 let vtable = &ErrorVTable {95 object_drop: object_drop::<E>,96 object_ref: object_ref::<E>,97 #[cfg(anyhow_no_ptr_addr_of)]98 object_mut: object_mut::<E>,99 object_boxed: object_boxed::<E>,100 object_downcast: object_downcast::<E>,101 #[cfg(anyhow_no_ptr_addr_of)]102 object_downcast_mut: object_downcast_mut::<E>,103 object_drop_rest: object_drop_front::<E>,Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 104–105why, one step back104 #[cfg(all(105 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 106why, one step back106 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 107why, one step back107 ))]Release 1.0.53David Tolnaybefore adoption7290028
lines 108–115why, one step back108 object_backtrace: no_backtrace,109 };110111 // Safety: passing vtable that operates on the right type E.112 unsafe { Error::construct(error, vtable, backtrace) }113 }114115 #[cold]Add construct_ prefix to name of private construct functionsDavid Tolnaybefore adoption671f700
line 116why, one step back116 pub(crate) fn construct_from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> SelfRelease 1.0.53David Tolnaybefore adoption7290028
lines 117–124why, one step back117 where118 M: Display + Debug + Send + Sync + 'static,119 {120 use crate::wrapper::MessageError;121 let error: MessageError<M> = MessageError(message);122 let vtable = &ErrorVTable {123 object_drop: object_drop::<MessageError<M>>,124 object_ref: object_ref::<MessageError<M>>,Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 125why, one step back125 #[cfg(all(any(feature = "std", not(anyhow_no_core_error)), anyhow_no_ptr_addr_of))]Release 1.0.53David Tolnaybefore adoption7290028
lines 126–131why, one step back126 object_mut: object_mut::<MessageError<M>>,127 object_boxed: object_boxed::<MessageError<M>>,128 object_downcast: object_downcast::<M>,129 #[cfg(anyhow_no_ptr_addr_of)]130 object_downcast_mut: object_downcast_mut::<M>,131 object_drop_rest: object_drop_front::<M>,Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 132–133why, one step back132 #[cfg(all(133 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 134why, one step back134 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 135why, one step back135 ))]Release 1.0.53David Tolnaybefore adoption7290028
lines 136–144why, one step back136 object_backtrace: no_backtrace,137 };138139 // Safety: MessageError is repr(transparent) so it is okay for the140 // vtable to allow casting the MessageError<M> to M.141 unsafe { Error::construct(error, vtable, backtrace) }142 }143144 #[cold]Add construct_ prefix to name of private construct functionsDavid Tolnaybefore adoption671f700
line 145why, one step back145 pub(crate) fn construct_from_display<M>(message: M, backtrace: Option<Backtrace>) -> SelfRelease 1.0.53David Tolnaybefore adoption7290028
lines 146–153why, one step back146 where147 M: Display + Send + Sync + 'static,148 {149 use crate::wrapper::DisplayError;150 let error: DisplayError<M> = DisplayError(message);151 let vtable = &ErrorVTable {152 object_drop: object_drop::<DisplayError<M>>,153 object_ref: object_ref::<DisplayError<M>>,Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 154why, one step back154 #[cfg(all(any(feature = "std", not(anyhow_no_core_error)), anyhow_no_ptr_addr_of))]Release 1.0.53David Tolnaybefore adoption7290028
lines 155–160why, one step back155 object_mut: object_mut::<DisplayError<M>>,156 object_boxed: object_boxed::<DisplayError<M>>,157 object_downcast: object_downcast::<M>,158 #[cfg(anyhow_no_ptr_addr_of)]159 object_downcast_mut: object_downcast_mut::<M>,160 object_drop_rest: object_drop_front::<M>,Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 161–162why, one step back161 #[cfg(all(162 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 163why, one step back163 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 164why, one step back164 ))]Release 1.0.53David Tolnaybefore adoption7290028
lines 165–172why, one step back165 object_backtrace: no_backtrace,166 };167168 // Safety: DisplayError is repr(transparent) so it is okay for the169 // vtable to allow casting the DisplayError<M> to M.170 unsafe { Error::construct(error, vtable, backtrace) }171 }172Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 173why, one step back173 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Release 1.0.53David Tolnaybefore adoption7290028
line 174why, one step back174 #[cold]Add construct_ prefix to name of private construct functionsDavid Tolnaybefore adoption671f700
lines 175–179why, one step back175 pub(crate) fn construct_from_context<C, E>(176 context: C,177 error: E,178 backtrace: Option<Backtrace>,179 ) -> SelfRelease 1.0.53David Tolnaybefore adoption7290028
lines 180–195why, one step back180 where181 C: Display + Send + Sync + 'static,182 E: StdError + Send + Sync + 'static,183 {184 let error: ContextError<C, E> = ContextError { context, error };185186 let vtable = &ErrorVTable {187 object_drop: object_drop::<ContextError<C, E>>,188 object_ref: object_ref::<ContextError<C, E>>,189 #[cfg(anyhow_no_ptr_addr_of)]190 object_mut: object_mut::<ContextError<C, E>>,191 object_boxed: object_boxed::<ContextError<C, E>>,192 object_downcast: context_downcast::<C, E>,193 #[cfg(anyhow_no_ptr_addr_of)]194 object_downcast_mut: context_downcast_mut::<C, E>,195 object_drop_rest: context_drop_rest::<C, E>,Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 196–197why, one step back196 #[cfg(all(197 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 198why, one step back198 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 199why, one step back199 ))]Release 1.0.53David Tolnaybefore adoption7290028
lines 200–206why, one step back200 object_backtrace: no_backtrace,201 };202203 // Safety: passing vtable that operates on the right type.204 unsafe { Error::construct(error, vtable, backtrace) }205 }206Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 207why, one step back207 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Release 1.0.53David Tolnaybefore adoption7290028
line 208why, one step back208 #[cold]Add construct_ prefix to name of private construct functionsDavid Tolnaybefore adoption671f700
line 209why, one step back209 pub(crate) fn construct_from_boxed(Release 1.0.53David Tolnaybefore adoption7290028
lines 210–224why, one step back210 error: Box<dyn StdError + Send + Sync>,211 backtrace: Option<Backtrace>,212 ) -> Self {213 use crate::wrapper::BoxedError;214 let error = BoxedError(error);215 let vtable = &ErrorVTable {216 object_drop: object_drop::<BoxedError>,217 object_ref: object_ref::<BoxedError>,218 #[cfg(anyhow_no_ptr_addr_of)]219 object_mut: object_mut::<BoxedError>,220 object_boxed: object_boxed::<BoxedError>,221 object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,222 #[cfg(anyhow_no_ptr_addr_of)]223 object_downcast_mut: object_downcast_mut::<Box<dyn StdError + Send + Sync>>,224 object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 225–226why, one step back225 #[cfg(all(226 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 227why, one step back227 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 228why, one step back228 ))]Release 1.0.53David Tolnaybefore adoption7290028
lines 229–320why, one step back229 object_backtrace: no_backtrace,230 };231232 // Safety: BoxedError is repr(transparent) so it is okay for the vtable233 // to allow casting to Box<dyn StdError + Send + Sync>.234 unsafe { Error::construct(error, vtable, backtrace) }235 }236237 // Takes backtrace as argument rather than capturing it here so that the238 // user sees one fewer layer of wrapping noise in the backtrace.239 //240 // Unsafe because the given vtable must have sensible behavior on the error241 // value of type E.242 #[cold]243 unsafe fn construct<E>(244 error: E,245 vtable: &'static ErrorVTable,246 backtrace: Option<Backtrace>,247 ) -> Self248 where249 E: StdError + Send + Sync + 'static,250 {251 let inner: Box<ErrorImpl<E>> = Box::new(ErrorImpl {252 vtable,253 backtrace,254 _object: error,255 });256 // Erase the concrete type of E from the compile-time type system. This257 // is equivalent to the safe unsize coercion from Box<ErrorImpl<E>> to258 // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the259 // result is a thin pointer. The necessary behavior for manipulating the260 // underlying ErrorImpl<E> is preserved in the vtable provided by the261 // caller rather than a builtin fat pointer vtable.262 let inner = Own::new(inner).cast::<ErrorImpl>();263 Error { inner }264 }265266 /// Wrap the error value with additional context.267 ///268 /// For attaching context to a `Result` as it is propagated, the269 /// [`Context`][crate::Context] extension trait may be more convenient than270 /// this function.271 ///272 /// The primary reason to use `error.context(...)` instead of273 /// `result.context(...)` via the `Context` trait would be if the context274 /// needs to depend on some data held by the underlying error:275 ///276 /// ```277 /// # use std::fmt::{self, Debug, Display};278 /// #279 /// # type T = ();280 /// #281 /// # impl std::error::Error for ParseError {}282 /// # impl Debug for ParseError {283 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {284 /// # unimplemented!()285 /// # }286 /// # }287 /// # impl Display for ParseError {288 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {289 /// # unimplemented!()290 /// # }291 /// # }292 /// #293 /// use anyhow::Result;294 /// use std::fs::File;295 /// use std::path::Path;296 ///297 /// struct ParseError {298 /// line: usize,299 /// column: usize,300 /// }301 ///302 /// fn parse_impl(file: File) -> Result<T, ParseError> {303 /// # const IGNORE: &str = stringify! {304 /// ...305 /// # };306 /// # unimplemented!()307 /// }308 ///309 /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {310 /// let file = File::open(&path)?;311 /// parse_impl(file).map_err(|error| {312 /// let context = format!(313 /// "only the first {} lines of {} are valid",314 /// error.line, path.as_ref().display(),315 /// );316 /// anyhow::Error::new(error).context(context)317 /// })318 /// }319 /// ```320 #[cold]Merge pull request #229 from dtolnay/must_useDavid Tolnaybefore adoptionc8a3e42
line 321why, one step back321 #[must_use]Release 1.0.53David Tolnaybefore adoption7290028
lines 322–333why, one step back322 pub fn context<C>(self, context: C) -> Self323 where324 C: Display + Send + Sync + 'static,325 {326 let error: ContextError<C, Error> = ContextError {327 context,328 error: self,329 };330331 let vtable = &ErrorVTable {332 object_drop: object_drop::<ContextError<C, Error>>,333 object_ref: object_ref::<ContextError<C, Error>>,Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 334why, one step back334 #[cfg(all(any(feature = "std", not(anyhow_no_core_error)), anyhow_no_ptr_addr_of))]Release 1.0.53David Tolnaybefore adoption7290028
lines 335–340why, one step back335 object_mut: object_mut::<ContextError<C, Error>>,336 object_boxed: object_boxed::<ContextError<C, Error>>,337 object_downcast: context_chain_downcast::<C>,338 #[cfg(anyhow_no_ptr_addr_of)]339 object_downcast_mut: context_chain_downcast_mut::<C>,340 object_drop_rest: context_chain_drop_rest::<C>,Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 341–342why, one step back341 #[cfg(all(342 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 343why, one step back343 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 344why, one step back344 ))]Release 1.0.53David Tolnaybefore adoption7290028
lines 345–371why, one step back345 object_backtrace: context_backtrace::<C>,346 };347348 // As the cause is anyhow::Error, we already have a backtrace for it.349 let backtrace = None;350351 // Safety: passing vtable that operates on the right type.352 unsafe { Error::construct(error, vtable, backtrace) }353 }354355 /// Get the backtrace for this Error.356 ///357 /// In order for the backtrace to be meaningful, one of the two environment358 /// variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined359 /// and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhat360 /// expensive to capture in Rust, so we don't necessarily want to be361 /// capturing them all over the place all the time.362 ///363 /// - If you want panics and errors to both have backtraces, set364 /// `RUST_BACKTRACE=1`;365 /// - If you want only errors to have backtraces, set366 /// `RUST_LIB_BACKTRACE=1`;367 /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and368 /// `RUST_LIB_BACKTRACE=0`.369 ///370 /// # Stability371 ///Touch up PR 293David Tolnaybefore adoptionb6ac995
lines 372–373why, one step back372 /// Standard library backtraces are only available when using Rust ≥373 /// 1.65. On older compilers, this function is only available if the crate'sRelease 1.0.53David Tolnaybefore adoption7290028
line 374why, one step back374 /// "backtrace" feature is enabled, and will use the `backtrace` crate asTouch up PR 293David Tolnaybefore adoptionb6ac995
lines 375–376why, one step back375 /// the underlying backtrace implementation. The return type of this376 /// function on old compilers is `&(impl Debug + Display)`.Release 1.0.53David Tolnaybefore adoption7290028
lines 377–381why, one step back377 ///378 /// ```toml379 /// [dependencies]380 /// anyhow = { version = "1.0", features = ["backtrace"] }381 /// ```Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 382why, one step back382 #[cfg(any(std_backtrace, feature = "backtrace"))]Release 1.0.53David Tolnaybefore adoption7290028
lines 383–407why, one step back383 pub fn backtrace(&self) -> &impl_backtrace!() {384 unsafe { ErrorImpl::backtrace(self.inner.by_ref()) }385 }386387 /// An iterator of the chain of source errors contained by this Error.388 ///389 /// This iterator will visit every error in the cause chain of this error390 /// object, beginning with the error that this error object was created391 /// from.392 ///393 /// # Example394 ///395 /// ```396 /// use anyhow::Error;397 /// use std::io;398 ///399 /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {400 /// for cause in error.chain() {401 /// if let Some(io_error) = cause.downcast_ref::<io::Error>() {402 /// return Some(io_error.kind());403 /// }404 /// }405 /// None406 /// }407 /// ```Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 408why, one step back408 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Release 1.0.53David Tolnaybefore adoption7290028
lines 409–418why, one step back409 #[cold]410 pub fn chain(&self) -> Chain {411 unsafe { ErrorImpl::chain(self.inner.by_ref()) }412 }413414 /// The lowest level cause of this error — this error's cause's415 /// cause's cause etc.416 ///417 /// The root cause is the last error in the iterator produced by418 /// [`chain()`][Error::chain].Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 419why, one step back419 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Release 1.0.53David Tolnaybefore adoption7290028
lines 420–542why, one step back420 pub fn root_cause(&self) -> &(dyn StdError + 'static) {421 self.chain().last().unwrap()422 }423424 /// Returns true if `E` is the type held by this error object.425 ///426 /// For errors with context, this method returns true if `E` matches the427 /// type of the context `C` **or** the type of the error on which the428 /// context has been attached. For details about the interaction between429 /// context and downcasting, [see here].430 ///431 /// [see here]: trait.Context.html#effect-on-downcasting432 pub fn is<E>(&self) -> bool433 where434 E: Display + Debug + Send + Sync + 'static,435 {436 self.downcast_ref::<E>().is_some()437 }438439 /// Attempt to downcast the error object to a concrete type.440 pub fn downcast<E>(mut self) -> Result<E, Self>441 where442 E: Display + Debug + Send + Sync + 'static,443 {444 let target = TypeId::of::<E>();445 let inner = self.inner.by_mut();446 unsafe {447 // Use vtable to find NonNull<()> which points to a value of type E448 // somewhere inside the data structure.449 #[cfg(not(anyhow_no_ptr_addr_of))]450 let addr = match (vtable(inner.ptr).object_downcast)(inner.by_ref(), target) {451 Some(addr) => addr.by_mut().extend(),452 None => return Err(self),453 };454 #[cfg(anyhow_no_ptr_addr_of)]455 let addr = match (vtable(inner.ptr).object_downcast_mut)(inner, target) {456 Some(addr) => addr.extend(),457 None => return Err(self),458 };459460 // Prepare to read E out of the data structure. We'll drop the rest461 // of the data structure separately so that E is not dropped.462 let outer = ManuallyDrop::new(self);463464 // Read E from where the vtable found it.465 let error = addr.cast::<E>().read();466467 // Drop rest of the data structure outside of E.468 (vtable(outer.inner.ptr).object_drop_rest)(outer.inner, target);469470 Ok(error)471 }472 }473474 /// Downcast this error object by reference.475 ///476 /// # Example477 ///478 /// ```479 /// # use anyhow::anyhow;480 /// # use std::fmt::{self, Display};481 /// # use std::task::Poll;482 /// #483 /// # #[derive(Debug)]484 /// # enum DataStoreError {485 /// # Censored(()),486 /// # }487 /// #488 /// # impl Display for DataStoreError {489 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {490 /// # unimplemented!()491 /// # }492 /// # }493 /// #494 /// # impl std::error::Error for DataStoreError {}495 /// #496 /// # const REDACTED_CONTENT: () = ();497 /// #498 /// # let error = anyhow!("...");499 /// # let root_cause = &error;500 /// #501 /// # let ret =502 /// // If the error was caused by redaction, then return a tombstone instead503 /// // of the content.504 /// match root_cause.downcast_ref::<DataStoreError>() {505 /// Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),506 /// None => Err(error),507 /// }508 /// # ;509 /// ```510 pub fn downcast_ref<E>(&self) -> Option<&E>511 where512 E: Display + Debug + Send + Sync + 'static,513 {514 let target = TypeId::of::<E>();515 unsafe {516 // Use vtable to find NonNull<()> which points to a value of type E517 // somewhere inside the data structure.518 let addr = (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?;519 Some(addr.cast::<E>().deref())520 }521 }522523 /// Downcast this error object by mutable reference.524 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>525 where526 E: Display + Debug + Send + Sync + 'static,527 {528 let target = TypeId::of::<E>();529 unsafe {530 // Use vtable to find NonNull<()> which points to a value of type E531 // somewhere inside the data structure.532533 #[cfg(not(anyhow_no_ptr_addr_of))]534 let addr =535 (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?.by_mut();536537 #[cfg(anyhow_no_ptr_addr_of)]538 let addr = (vtable(self.inner.ptr).object_downcast_mut)(self.inner.by_mut(), target)?;539540 Some(addr.cast::<E>().deref_mut())541 }542 }Merge pull request #268 from dtolnay/provideDavid Tolnaybefore adoption480e480
line 543why, one step back543Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 544why, one step back544 #[cfg(error_generic_member_access)]Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15
lines 545–548why, one step back545 pub(crate) fn provide<'a>(&'a self, request: &mut Request<'a>) {546 unsafe { ErrorImpl::provide(self.inner.by_ref(), request) }547 }548Merge pull request #268 from dtolnay/provideDavid Tolnaybefore adoption480e480
lines 549–553why, one step back549 // Called by thiserror when you have `#[source] anyhow::Error`. This provide550 // implementation includes the anyhow::Error's Backtrace if any, unlike551 // deref'ing to dyn Error where the provide implementation would include552 // only the original error's Backtrace from before it got wrapped into an553 // anyhow::Error.Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 554why, one step back554 #[cfg(error_generic_member_access)]Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15
lines 555–557why, one step back555 #[doc(hidden)]556 pub fn thiserror_provide<'a>(&'a self, request: &mut Request<'a>) {557 Self::provide(self, request);Merge pull request #268 from dtolnay/provideDavid Tolnaybefore adoption480e480
line 558why, one step back558 }Release 1.0.53David Tolnaybefore adoption7290028
lines 559–560why, one step back559}560Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 561why, one step back561#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Release 1.0.53David Tolnaybefore adoption7290028
lines 562–567why, one step back562impl<E> From<E> for Error563where564 E: StdError + Send + Sync + 'static,565{566 #[cold]567 fn from(error: E) -> Self {Merge pull request #266 from dtolnay/providerDavid Tolnaybefore adoption546342c
line 568why, one step back568 let backtrace = backtrace_if_absent!(&error);Add construct_ prefix to name of private construct functionsDavid Tolnaybefore adoption671f700
line 569why, one step back569 Error::construct_from_std(error, backtrace)Release 1.0.53David Tolnaybefore adoption7290028
lines 570–572why, one step back570 }571}572Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 573why, one step back573#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Release 1.0.53David Tolnaybefore adoption7290028
lines 574–581why, one step back574impl Deref for Error {575 type Target = dyn StdError + Send + Sync + 'static;576577 fn deref(&self) -> &Self::Target {578 unsafe { ErrorImpl::error(self.inner.by_ref()) }579 }580}581Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 582why, one step back582#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Release 1.0.53David Tolnaybefore adoption7290028
lines 583–612why, one step back583impl DerefMut for Error {584 fn deref_mut(&mut self) -> &mut Self::Target {585 unsafe { ErrorImpl::error_mut(self.inner.by_mut()) }586 }587}588589impl Display for Error {590 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {591 unsafe { ErrorImpl::display(self.inner.by_ref(), formatter) }592 }593}594595impl Debug for Error {596 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {597 unsafe { ErrorImpl::debug(self.inner.by_ref(), formatter) }598 }599}600601impl Drop for Error {602 fn drop(&mut self) {603 unsafe {604 // Invoke the vtable's drop behavior.605 (vtable(self.inner.ptr).object_drop)(self.inner);606 }607 }608}609610struct ErrorVTable {611 object_drop: unsafe fn(Own<ErrorImpl>),612 object_ref: unsafe fn(Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>,Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 613why, one step back613 #[cfg(all(any(feature = "std", not(anyhow_no_core_error)), anyhow_no_ptr_addr_of))]Release 1.0.53David Tolnaybefore adoption7290028
lines 614–619why, one step back614 object_mut: unsafe fn(Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static),615 object_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,616 object_downcast: unsafe fn(Ref<ErrorImpl>, TypeId) -> Option<Ref<()>>,617 #[cfg(anyhow_no_ptr_addr_of)]618 object_downcast_mut: unsafe fn(Mut<ErrorImpl>, TypeId) -> Option<Mut<()>>,619 object_drop_rest: unsafe fn(Own<ErrorImpl>, TypeId),Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 620–621why, one step back620 #[cfg(all(621 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 622why, one step back622 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 623why, one step back623 ))]Release 1.0.53David Tolnaybefore adoption7290028
lines 624–630why, one step back624 object_backtrace: unsafe fn(Ref<ErrorImpl>) -> Option<&Backtrace>,625}626627// Safety: requires layout of *e to match ErrorImpl<E>.628unsafe fn object_drop<E>(e: Own<ErrorImpl>) {629 // Cast back to ErrorImpl<E> so that the allocator receives the correct630 // Layout to deallocate the Box's memory.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 631–632why, one step back631 let unerased_own = e.cast::<ErrorImpl<E>>();632 drop(unsafe { unerased_own.boxed() });Release 1.0.53David Tolnaybefore adoption7290028
lines 633–640why, one step back633}634635// Safety: requires layout of *e to match ErrorImpl<E>.636unsafe fn object_drop_front<E>(e: Own<ErrorImpl>, target: TypeId) {637 // Drop the fields of ErrorImpl other than E as well as the Box allocation,638 // without dropping E itself. This is used by downcast after doing a639 // ptr::read to take ownership of the E.640 let _ = target;Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 641–642why, one step back641 let unerased_own = e.cast::<ErrorImpl<ManuallyDrop<E>>>();642 drop(unsafe { unerased_own.boxed() });Release 1.0.53David Tolnaybefore adoption7290028
lines 643–651why, one step back643}644645// Safety: requires layout of *e to match ErrorImpl<E>.646unsafe fn object_ref<E>(e: Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>647where648 E: StdError + Send + Sync + 'static,649{650 // Attach E's native StdError vtable onto a pointer to self._object.651Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 652why, one step back652 let unerased_ref = e.cast::<ErrorImpl<E>>();Release 1.0.53David Tolnaybefore adoption7290028
lines 653–654why, one step back653654 #[cfg(not(anyhow_no_ptr_addr_of))]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 655–657why, one step back655 return Ref::from_raw(unsafe {656 NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object) as *mut E)657 });Release 1.0.53David Tolnaybefore adoption7290028
lines 658–659why, one step back658659 #[cfg(anyhow_no_ptr_addr_of)]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 660why, one step back660 return Ref::new(unsafe { &unerased_ref.deref()._object });Release 1.0.53David Tolnaybefore adoption7290028
lines 661–664why, one step back661}662663// Safety: requires layout of *e to match ErrorImpl<E>, and for `e` to be derived664// from a `&mut`Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 665why, one step back665#[cfg(all(any(feature = "std", not(anyhow_no_core_error)), anyhow_no_ptr_addr_of))]Release 1.0.53David Tolnaybefore adoption7290028
lines 666–670why, one step back666unsafe fn object_mut<E>(e: Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static)667where668 E: StdError + Send + Sync + 'static,669{670 // Attach E's native StdError vtable onto a pointer to self._object.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 671–672why, one step back671 let unerased_mut = e.cast::<ErrorImpl<E>>();672 unsafe { &mut unerased_mut.deref_mut()._object }Release 1.0.53David Tolnaybefore adoption7290028
lines 673–680why, one step back673}674675// Safety: requires layout of *e to match ErrorImpl<E>.676unsafe fn object_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>677where678 E: StdError + Send + Sync + 'static,679{680 // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 681–682why, one step back681 let unerased_own = e.cast::<ErrorImpl<E>>();682 unsafe { unerased_own.boxed() }Release 1.0.53David Tolnaybefore adoption7290028
lines 683–693why, one step back683}684685// Safety: requires layout of *e to match ErrorImpl<E>.686unsafe fn object_downcast<E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>687where688 E: 'static,689{690 if TypeId::of::<E>() == target {691 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a692 // pointer to its E field.693Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 694why, one step back694 let unerased_ref = e.cast::<ErrorImpl<E>>();Release 1.0.53David Tolnaybefore adoption7290028
lines 695–697why, one step back695696 #[cfg(not(anyhow_no_ptr_addr_of))]697 return Some(Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 698–700why, one step back698 Ref::from_raw(unsafe {699 NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object) as *mut E)700 })Release 1.0.53David Tolnaybefore adoption7290028
lines 701–704why, one step back701 .cast::<()>(),702 );703704 #[cfg(anyhow_no_ptr_addr_of)]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 705why, one step back705 return Some(Ref::new(unsafe { &unerased_ref.deref()._object }).cast::<()>());Release 1.0.53David Tolnaybefore adoption7290028
lines 706–719why, one step back706 } else {707 None708 }709}710711// Safety: requires layout of *e to match ErrorImpl<E>.712#[cfg(anyhow_no_ptr_addr_of)]713unsafe fn object_downcast_mut<E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>714where715 E: 'static,716{717 if TypeId::of::<E>() == target {718 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a719 // pointer to its E field.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 720–721why, one step back720 let unerased_mut = e.cast::<ErrorImpl<E>>();721 let unerased = unsafe { unerased_mut.deref_mut() };Release 1.0.53David Tolnaybefore adoption7290028
lines 722–727why, one step back722 Some(Mut::new(&mut unerased._object).cast::<()>())723 } else {724 None725 }726}727Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 728–729why, one step back728#[cfg(all(729 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 730why, one step back730 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 731why, one step back731))]Release 1.0.53David Tolnaybefore adoption7290028
lines 732–737why, one step back732fn no_backtrace(e: Ref<ErrorImpl>) -> Option<&Backtrace> {733 let _ = e;734 None735}736737// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 738why, one step back738#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Release 1.0.53David Tolnaybefore adoption7290028
lines 739–744why, one step back739unsafe fn context_downcast<C, E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>740where741 C: 'static,742 E: 'static,743{744 if TypeId::of::<C>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 745–746why, one step back745 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();746 let unerased = unsafe { unerased_ref.deref() };Release 1.0.53David Tolnaybefore adoption7290028
lines 747–748why, one step back747 Some(Ref::new(&unerased._object.context).cast::<()>())748 } else if TypeId::of::<E>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 749–750why, one step back749 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();750 let unerased = unsafe { unerased_ref.deref() };Release 1.0.53David Tolnaybefore adoption7290028
lines 751–764why, one step back751 Some(Ref::new(&unerased._object.error).cast::<()>())752 } else {753 None754 }755}756757// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.758#[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]759unsafe fn context_downcast_mut<C, E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>760where761 C: 'static,762 E: 'static,763{764 if TypeId::of::<C>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 765–766why, one step back765 let unerased_mut = e.cast::<ErrorImpl<ContextError<C, E>>>();766 let unerased = unsafe { unerased_mut.deref_mut() };Release 1.0.53David Tolnaybefore adoption7290028
lines 767–768why, one step back767 Some(Mut::new(&mut unerased._object.context).cast::<()>())768 } else if TypeId::of::<E>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 769–770why, one step back769 let unerased_mut = e.cast::<ErrorImpl<ContextError<C, E>>>();770 let unerased = unsafe { unerased_mut.deref_mut() };Release 1.0.53David Tolnaybefore adoption7290028
lines 771–777why, one step back771 Some(Mut::new(&mut unerased._object.error).cast::<()>())772 } else {773 None774 }775}776777// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 778why, one step back778#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Release 1.0.53David Tolnaybefore adoption7290028
lines 779–786why, one step back779unsafe fn context_drop_rest<C, E>(e: Own<ErrorImpl>, target: TypeId)780where781 C: 'static,782 E: 'static,783{784 // Called after downcasting by value to either the C or the E and doing a785 // ptr::read to take ownership of that value.786 if TypeId::of::<C>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 787–788why, one step back787 let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>();788 drop(unsafe { unerased_own.boxed() });Release 1.0.53David Tolnaybefore adoption7290028
line 789why, one step back789 } else {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 790–791why, one step back790 let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>();791 drop(unsafe { unerased_own.boxed() });Release 1.0.53David Tolnaybefore adoption7290028
lines 792–799why, one step back792 }793}794795// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.796unsafe fn context_chain_downcast<C>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>797where798 C: 'static,799{Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 800–801why, one step back800 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();801 let unerased = unsafe { unerased_ref.deref() };Release 1.0.53David Tolnaybefore adoption7290028
lines 802–806why, one step back802 if TypeId::of::<C>() == target {803 Some(Ref::new(&unerased._object.context).cast::<()>())804 } else {805 // Recurse down the context chain per the inner error's vtable.806 let source = &unerased._object.error;Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 807why, one step back807 unsafe { (vtable(source.inner.ptr).object_downcast)(source.inner.by_ref(), target) }Release 1.0.53David Tolnaybefore adoption7290028
lines 808–816why, one step back808 }809}810811// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.812#[cfg(anyhow_no_ptr_addr_of)]813unsafe fn context_chain_downcast_mut<C>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>814where815 C: 'static,816{Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 817–818why, one step back817 let unerased_mut = e.cast::<ErrorImpl<ContextError<C, Error>>>();818 let unerased = unsafe { unerased_mut.deref_mut() };Release 1.0.53David Tolnaybefore adoption7290028
lines 819–823why, one step back819 if TypeId::of::<C>() == target {820 Some(Mut::new(&mut unerased._object.context).cast::<()>())821 } else {822 // Recurse down the context chain per the inner error's vtable.823 let source = &mut unerased._object.error;Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 824why, one step back824 unsafe { (vtable(source.inner.ptr).object_downcast_mut)(source.inner.by_mut(), target) }Release 1.0.53David Tolnaybefore adoption7290028
lines 825–835why, one step back825 }826}827828// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.829unsafe fn context_chain_drop_rest<C>(e: Own<ErrorImpl>, target: TypeId)830where831 C: 'static,832{833 // Called after downcasting by value to either the C or one of the causes834 // and doing a ptr::read to take ownership of that value.835 if TypeId::of::<C>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 836why, one step back836 let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>();Release 1.0.53David Tolnaybefore adoption7290028
line 837why, one step back837 // Drop the entire rest of the data structure rooted in the next Error.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 838why, one step back838 drop(unsafe { unerased_own.boxed() });Release 1.0.53David Tolnaybefore adoption7290028
line 839why, one step back839 } else {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 840–841why, one step back840 let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>();841 let unerased = unsafe { unerased_own.boxed() };Release 1.0.53David Tolnaybefore adoption7290028
lines 842–844why, one step back842 // Read the Own<ErrorImpl> from the next error.843 let inner = unerased._object.error.inner;844 drop(unerased);Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 845why, one step back845 let vtable = unsafe { vtable(inner.ptr) };Release 1.0.53David Tolnaybefore adoption7290028
line 846why, one step back846 // Recursively drop the next error using the same target typeid.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 847why, one step back847 unsafe { (vtable.object_drop_rest)(inner, target) };Release 1.0.53David Tolnaybefore adoption7290028
lines 848–851why, one step back848 }849}850851// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 852–853why, one step back852#[cfg(all(853 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 854why, one step back854 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 855why, one step back855))]Release 1.0.53David Tolnaybefore adoption7290028
lines 856–860why, one step back856#[allow(clippy::unnecessary_wraps)]857unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>858where859 C: 'static,860{Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 861–863why, one step back861 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();862 let unerased = unsafe { unerased_ref.deref() };863 let backtrace = unsafe { ErrorImpl::backtrace(unerased._object.error.inner.by_ref()) };Release 1.0.53David Tolnaybefore adoption7290028
lines 864–882why, one step back864 Some(backtrace)865}866867// NOTE: If working with `ErrorImpl<()>`, references should be avoided in favor868// of raw pointers and `NonNull`.869// repr C to ensure that E remains in the final position.870#[repr(C)]871pub(crate) struct ErrorImpl<E = ()> {872 vtable: &'static ErrorVTable,873 backtrace: Option<Backtrace>,874 // NOTE: Don't use directly. Use only through vtable. Erased type may have875 // different alignment.876 _object: E,877}878879// Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but880// avoids converting `p` into a reference.881unsafe fn vtable(p: NonNull<ErrorImpl>) -> &'static ErrorVTable {882 // NOTE: This assumes that `ErrorVTable` is the first field of ErrorImpl.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 883why, one step back883 unsafe { *(p.as_ptr() as *const &'static ErrorVTable) }Release 1.0.53David Tolnaybefore adoption7290028
lines 884–906why, one step back884}885886// repr C to ensure that ContextError<C, E> has the same layout as887// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.888#[repr(C)]889pub(crate) struct ContextError<C, E> {890 pub context: C,891 pub error: E,892}893894impl<E> ErrorImpl<E> {895 fn erase(&self) -> Ref<ErrorImpl> {896 // Erase the concrete type of E but preserve the vtable in self.vtable897 // for manipulating the resulting thin pointer. This is analogous to an898 // unsize coercion.899 Ref::new(self).cast::<ErrorImpl>()900 }901}902903impl ErrorImpl {904 pub(crate) unsafe fn error(this: Ref<Self>) -> &(dyn StdError + Send + Sync + 'static) {905 // Use vtable to attach E's native StdError vtable for the right906 // original type E.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 907why, one step back907 unsafe { (vtable(this.ptr).object_ref)(this).deref() }Release 1.0.53David Tolnaybefore adoption7290028
lines 908–909why, one step back908 }909Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 910why, one step back910 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Release 1.0.53David Tolnaybefore adoption7290028
lines 911–915why, one step back911 pub(crate) unsafe fn error_mut(this: Mut<Self>) -> &mut (dyn StdError + Send + Sync + 'static) {912 // Use vtable to attach E's native StdError vtable for the right913 // original type E.914915 #[cfg(not(anyhow_no_ptr_addr_of))]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 916–920why, one step back916 return unsafe {917 (vtable(this.ptr).object_ref)(this.by_ref())918 .by_mut()919 .deref_mut()920 };Release 1.0.53David Tolnaybefore adoption7290028
lines 921–922why, one step back921922 #[cfg(anyhow_no_ptr_addr_of)]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 923why, one step back923 return unsafe { (vtable(this.ptr).object_mut)(this) };Release 1.0.53David Tolnaybefore adoption7290028
lines 924–925why, one step back924 }925Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 926why, one step back926 #[cfg(any(std_backtrace, feature = "backtrace"))]Release 1.0.53David Tolnaybefore adoption7290028
lines 927–930why, one step back927 pub(crate) unsafe fn backtrace(this: Ref<Self>) -> &Backtrace {928 // This unwrap can only panic if the underlying error's backtrace method929 // is nondeterministic, which would only happen in maliciously930 // constructed code.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 931why, one step back931 unsafe { this.deref() }Release 1.0.53David Tolnaybefore adoption7290028
lines 932–934why, one step back932 .backtrace933 .as_ref()934 .or_else(|| {Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 935why, one step back935 #[cfg(error_generic_member_access)]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 936why, one step back936 return error::request_ref::<Backtrace>(unsafe { Self::error(this) });Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 937why, one step back937 #[cfg(not(error_generic_member_access))]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 938why, one step back938 return unsafe { (vtable(this.ptr).object_backtrace)(this) };Release 1.0.53David Tolnaybefore adoption7290028
lines 939–942why, one step back939 })940 .expect("backtrace capture failed")941 }942Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 943why, one step back943 #[cfg(error_generic_member_access)]Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15
line 944why, one step back944 unsafe fn provide<'a>(this: Ref<'a, Self>, request: &mut Request<'a>) {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 945why, one step back945 if let Some(backtrace) = unsafe { &this.deref().backtrace } {Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15
line 946why, one step back946 request.provide_ref(backtrace);Merge pull request #266 from dtolnay/providerDavid Tolnaybefore adoption546342c
line 947why, one step back947 }Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 948why, one step back948 unsafe { Self::error(this) }.provide(request);Merge pull request #266 from dtolnay/providerDavid Tolnaybefore adoption546342c
lines 949–950why, one step back949 }950Release 1.0.53David Tolnaybefore adoption7290028
lines 951–952why, one step back951 #[cold]952 pub(crate) unsafe fn chain(this: Ref<Self>) -> Chain {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 953why, one step back953 Chain::new(unsafe { Self::error(this) })Release 1.0.53David Tolnaybefore adoption7290028
lines 954–962why, one step back954 }955}956957impl<E> StdError for ErrorImpl<E>958where959 E: StdError,960{961 fn source(&self) -> Option<&(dyn StdError + 'static)> {962 unsafe { ErrorImpl::error(self.erase()).source() }Merge pull request #266 from dtolnay/providerDavid Tolnaybefore adoption546342c
lines 963–964why, one step back963 }964Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 965why, one step back965 #[cfg(error_generic_member_access)]Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15
lines 966–967why, one step back966 fn provide<'a>(&'a self, request: &mut Request<'a>) {967 unsafe { ErrorImpl::provide(self.erase(), request) }Release 1.0.53David Tolnaybefore adoption7290028
lines 968–1012why, one step back968 }969}970971impl<E> Debug for ErrorImpl<E>972where973 E: Debug,974{975 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {976 unsafe { ErrorImpl::debug(self.erase(), formatter) }977 }978}979980impl<E> Display for ErrorImpl<E>981where982 E: Display,983{984 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {985 unsafe { Display::fmt(ErrorImpl::error(self.erase()), formatter) }986 }987}988989impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {990 #[cold]991 fn from(error: Error) -> Self {992 let outer = ManuallyDrop::new(error);993 unsafe {994 // Use vtable to attach ErrorImpl<E>'s native StdError vtable for995 // the right original type E.996 (vtable(outer.inner.ptr).object_boxed)(outer.inner)997 }998 }999}10001001impl From<Error> for Box<dyn StdError + Send + 'static> {1002 fn from(error: Error) -> Self {1003 Box::<dyn StdError + Send + Sync>::from(error)1004 }1005}10061007impl From<Error> for Box<dyn StdError + 'static> {1008 fn from(error: Error) -> Self {1009 Box::<dyn StdError + Send + Sync>::from(error)1010 }1011}1012Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 1013why, one step back1013#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Release 1.0.53David Tolnaybefore adoption7290028
lines 1014–1019why, one step back1014impl AsRef<dyn StdError + Send + Sync> for Error {1015 fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {1016 &**self1017 }1018}1019Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 1020why, one step back1020#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Release 1.0.53David Tolnaybefore adoption7290028
lines 1021–1025why, one step back1021impl AsRef<dyn StdError> for Error {1022 fn as_ref(&self) -> &(dyn StdError + 'static) {1023 &**self1024 }1025}Merge pull request #386 from dtolnay/unwindsafeDavid Tolnaybefore adoption830c399
lines 1026–1031why, one step back10261027#[cfg(any(feature = "std", not(anyhow_no_core_unwind_safe)))]1028impl UnwindSafe for Error {}10291030#[cfg(any(feature = "std", not(anyhow_no_core_unwind_safe)))]1031impl RefUnwindSafe for Error {}