error.rs
This file
Path
src/error.rs
1,104 lines · 38.9 KiB · Rust
Last changed by
Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
History of this fileTake it
The walk stopped after 200 commits: lines older than ff37db3 point at it.
Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 1–2why, one step back1use crate::backtrace::Backtrace;2use crate::chain::Chain;Merge pull request #414 from dtolnay/nightlyDavid Tolnaybefore adoption213a9c2
lines 3–4why, one step back3#[cfg(error_generic_member_access)]4use crate::nightly::{self, Request};Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 5why, one step back5#[cfg(any(feature = "std", not(anyhow_no_core_error), anyhow_no_ptr_addr_of))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 6–12why, one step back6use crate::ptr::Mut;7use crate::ptr::{Own, Ref};8use crate::{Error, StdError};9use alloc::boxed::Box;10use core::any::TypeId;11use 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};Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
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};Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
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)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 32–37why, one step back32 #[cold]33 #[must_use]34 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);Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
line 39why, one step back39 Error::construct_from_std(error, backtrace)Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 40–84why, 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]80 #[must_use]81 pub fn msg<M>(message: M) -> Self82 where83 M: Display + Debug + Send + Sync + 'static,84 {Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
line 85why, one step back85 Error::construct_from_adhoc(message, backtrace!())Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 86–87why, one step back86 }87Merge pull request #402 from dtolnay/fromboxedDavid Tolnaybefore adoptiona03d6d6
lines 88–148why, one step back88 /// Construct an error object from a type-erased standard library error.89 ///90 /// This is mostly useful for interop with other error libraries.91 ///92 /// # Example93 ///94 /// Here is a skeleton of a library that provides its own error abstraction.95 /// The pair of `From` impls provide bidirectional support for `?`96 /// conversion between `Report` and `anyhow::Error`.97 ///98 /// ```99 /// use std::error::Error as StdError;100 ///101 /// pub struct Report {/* ... */}102 ///103 /// impl<E> From<E> for Report104 /// where105 /// E: Into<anyhow::Error>,106 /// Result<(), E>: anyhow::Context<(), E>,107 /// {108 /// fn from(error: E) -> Self {109 /// let anyhow_error: anyhow::Error = error.into();110 /// let boxed_error: Box<dyn StdError + Send + Sync + 'static> = anyhow_error.into();111 /// Report::from_boxed(boxed_error)112 /// }113 /// }114 ///115 /// impl From<Report> for anyhow::Error {116 /// fn from(report: Report) -> Self {117 /// let boxed_error: Box<dyn StdError + Send + Sync + 'static> = report.into_boxed();118 /// anyhow::Error::from_boxed(boxed_error)119 /// }120 /// }121 ///122 /// impl Report {123 /// fn from_boxed(boxed_error: Box<dyn StdError + Send + Sync + 'static>) -> Self {124 /// todo!()125 /// }126 /// fn into_boxed(self) -> Box<dyn StdError + Send + Sync + 'static> {127 /// todo!()128 /// }129 /// }130 ///131 /// // Example usage: can use `?` in both directions.132 /// fn a() -> anyhow::Result<()> {133 /// b()?;134 /// Ok(())135 /// }136 /// fn b() -> Result<(), Report> {137 /// a()?;138 /// Ok(())139 /// }140 /// ```141 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]142 #[cold]143 #[must_use]144 pub fn from_boxed(boxed_error: Box<dyn StdError + Send + Sync + 'static>) -> Self {145 let backtrace = backtrace_if_absent!(&*boxed_error);146 Error::construct_from_boxed(boxed_error, backtrace)147 }148Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 149why, one step back149 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
line 150why, one step back150 #[cold]Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
line 151why, one step back151 pub(crate) fn construct_from_std<E>(error: E, backtrace: Option<Backtrace>) -> SelfCheck all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 152–159why, one step back152 where153 E: StdError + Send + Sync + 'static,154 {155 let vtable = &ErrorVTable {156 object_drop: object_drop::<E>,157 object_ref: object_ref::<E>,158 #[cfg(anyhow_no_ptr_addr_of)]159 object_mut: object_mut::<E>,Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 160why, one step back160 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 161–165why, one step back161 object_boxed: object_boxed::<E>,162 object_downcast: object_downcast::<E>,163 #[cfg(anyhow_no_ptr_addr_of)]164 object_downcast_mut: object_downcast_mut::<E>,165 object_drop_rest: object_drop_front::<E>,Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 166–167why, one step back166 #[cfg(all(167 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 168why, one step back168 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 169why, one step back169 ))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 170–177why, one step back170 object_backtrace: no_backtrace,171 };172173 // Safety: passing vtable that operates on the right type E.174 unsafe { Error::construct(error, vtable, backtrace) }175 }176177 #[cold]Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
line 178why, one step back178 pub(crate) fn construct_from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> SelfCheck all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 179–186why, one step back179 where180 M: Display + Debug + Send + Sync + 'static,181 {182 use crate::wrapper::MessageError;183 let error: MessageError<M> = MessageError(message);184 let vtable = &ErrorVTable {185 object_drop: object_drop::<MessageError<M>>,186 object_ref: object_ref::<MessageError<M>>,Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 187why, one step back187 #[cfg(all(any(feature = "std", not(anyhow_no_core_error)), anyhow_no_ptr_addr_of))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
line 188why, one step back188 object_mut: object_mut::<MessageError<M>>,Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 189why, one step back189 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 190–194why, one step back190 object_boxed: object_boxed::<MessageError<M>>,191 object_downcast: object_downcast::<M>,192 #[cfg(anyhow_no_ptr_addr_of)]193 object_downcast_mut: object_downcast_mut::<M>,194 object_drop_rest: object_drop_front::<M>,Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 195–196why, one step back195 #[cfg(all(196 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 197why, one step back197 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 198why, one step back198 ))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 199–207why, one step back199 object_backtrace: no_backtrace,200 };201202 // Safety: MessageError is repr(transparent) so it is okay for the203 // vtable to allow casting the MessageError<M> to M.204 unsafe { Error::construct(error, vtable, backtrace) }205 }206207 #[cold]Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
line 208why, one step back208 pub(crate) fn construct_from_display<M>(message: M, backtrace: Option<Backtrace>) -> SelfCheck all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 209–216why, one step back209 where210 M: Display + Send + Sync + 'static,211 {212 use crate::wrapper::DisplayError;213 let error: DisplayError<M> = DisplayError(message);214 let vtable = &ErrorVTable {215 object_drop: object_drop::<DisplayError<M>>,216 object_ref: object_ref::<DisplayError<M>>,Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 217why, one step back217 #[cfg(all(any(feature = "std", not(anyhow_no_core_error)), anyhow_no_ptr_addr_of))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
line 218why, one step back218 object_mut: object_mut::<DisplayError<M>>,Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 219why, one step back219 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 220–224why, one step back220 object_boxed: object_boxed::<DisplayError<M>>,221 object_downcast: object_downcast::<M>,222 #[cfg(anyhow_no_ptr_addr_of)]223 object_downcast_mut: object_downcast_mut::<M>,224 object_drop_rest: object_drop_front::<M>,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 ))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 229–236why, one step back229 object_backtrace: no_backtrace,230 };231232 // Safety: DisplayError is repr(transparent) so it is okay for the233 // vtable to allow casting the DisplayError<M> to M.234 unsafe { Error::construct(error, vtable, backtrace) }235 }236Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 237why, one step back237 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
line 238why, one step back238 #[cold]Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
lines 239–243why, one step back239 pub(crate) fn construct_from_context<C, E>(240 context: C,241 error: E,242 backtrace: Option<Backtrace>,243 ) -> SelfCheck all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 244–254why, one step back244 where245 C: Display + Send + Sync + 'static,246 E: StdError + Send + Sync + 'static,247 {248 let error: ContextError<C, E> = ContextError { context, error };249250 let vtable = &ErrorVTable {251 object_drop: object_drop::<ContextError<C, E>>,252 object_ref: object_ref::<ContextError<C, E>>,253 #[cfg(anyhow_no_ptr_addr_of)]254 object_mut: object_mut::<ContextError<C, E>>,Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 255why, one step back255 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 256–260why, one step back256 object_boxed: object_boxed::<ContextError<C, E>>,257 object_downcast: context_downcast::<C, E>,258 #[cfg(anyhow_no_ptr_addr_of)]259 object_downcast_mut: context_downcast_mut::<C, E>,260 object_drop_rest: context_drop_rest::<C, E>,Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 261–262why, one step back261 #[cfg(all(262 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 263why, one step back263 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 264why, one step back264 ))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 265–271why, one step back265 object_backtrace: no_backtrace,266 };267268 // Safety: passing vtable that operates on the right type.269 unsafe { Error::construct(error, vtable, backtrace) }270 }271Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 272why, one step back272 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
line 273why, one step back273 #[cold]Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
line 274why, one step back274 pub(crate) fn construct_from_boxed(Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 275–284why, one step back275 error: Box<dyn StdError + Send + Sync>,276 backtrace: Option<Backtrace>,277 ) -> Self {278 use crate::wrapper::BoxedError;279 let error = BoxedError(error);280 let vtable = &ErrorVTable {281 object_drop: object_drop::<BoxedError>,282 object_ref: object_ref::<BoxedError>,283 #[cfg(anyhow_no_ptr_addr_of)]284 object_mut: object_mut::<BoxedError>,Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 285why, one step back285 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 286–290why, one step back286 object_boxed: object_boxed::<BoxedError>,287 object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,288 #[cfg(anyhow_no_ptr_addr_of)]289 object_downcast_mut: object_downcast_mut::<Box<dyn StdError + Send + Sync>>,290 object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 291–292why, one step back291 #[cfg(all(292 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 293why, one step back293 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 294why, one step back294 ))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 295–399why, one step back295 object_backtrace: no_backtrace,296 };297298 // Safety: BoxedError is repr(transparent) so it is okay for the vtable299 // to allow casting to Box<dyn StdError + Send + Sync>.300 unsafe { Error::construct(error, vtable, backtrace) }301 }302303 // Takes backtrace as argument rather than capturing it here so that the304 // user sees one fewer layer of wrapping noise in the backtrace.305 //306 // Unsafe because the given vtable must have sensible behavior on the error307 // value of type E.308 #[cold]309 unsafe fn construct<E>(310 error: E,311 vtable: &'static ErrorVTable,312 backtrace: Option<Backtrace>,313 ) -> Self314 where315 E: StdError + Send + Sync + 'static,316 {317 let inner: Box<ErrorImpl<E>> = Box::new(ErrorImpl {318 vtable,319 backtrace,320 _object: error,321 });322 // Erase the concrete type of E from the compile-time type system. This323 // is equivalent to the safe unsize coercion from Box<ErrorImpl<E>> to324 // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the325 // result is a thin pointer. The necessary behavior for manipulating the326 // underlying ErrorImpl<E> is preserved in the vtable provided by the327 // caller rather than a builtin fat pointer vtable.328 let inner = Own::new(inner).cast::<ErrorImpl>();329 Error { inner }330 }331332 /// Wrap the error value with additional context.333 ///334 /// For attaching context to a `Result` as it is propagated, the335 /// [`Context`][crate::Context] extension trait may be more convenient than336 /// this function.337 ///338 /// The primary reason to use `error.context(...)` instead of339 /// `result.context(...)` via the `Context` trait would be if the context340 /// needs to depend on some data held by the underlying error:341 ///342 /// ```343 /// # use std::fmt::{self, Debug, Display};344 /// #345 /// # type T = ();346 /// #347 /// # impl std::error::Error for ParseError {}348 /// # impl Debug for ParseError {349 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {350 /// # unimplemented!()351 /// # }352 /// # }353 /// # impl Display for ParseError {354 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {355 /// # unimplemented!()356 /// # }357 /// # }358 /// #359 /// use anyhow::Result;360 /// use std::fs::File;361 /// use std::path::Path;362 ///363 /// struct ParseError {364 /// line: usize,365 /// column: usize,366 /// }367 ///368 /// fn parse_impl(file: File) -> Result<T, ParseError> {369 /// # const IGNORE: &str = stringify! {370 /// ...371 /// # };372 /// # unimplemented!()373 /// }374 ///375 /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {376 /// let file = File::open(&path)?;377 /// parse_impl(file).map_err(|error| {378 /// let context = format!(379 /// "only the first {} lines of {} are valid",380 /// error.line, path.as_ref().display(),381 /// );382 /// anyhow::Error::new(error).context(context)383 /// })384 /// }385 /// ```386 #[cold]387 #[must_use]388 pub fn context<C>(self, context: C) -> Self389 where390 C: Display + Send + Sync + 'static,391 {392 let error: ContextError<C, Error> = ContextError {393 context,394 error: self,395 };396397 let vtable = &ErrorVTable {398 object_drop: object_drop::<ContextError<C, Error>>,399 object_ref: object_ref::<ContextError<C, Error>>,Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 400why, one step back400 #[cfg(all(any(feature = "std", not(anyhow_no_core_error)), anyhow_no_ptr_addr_of))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
line 401why, one step back401 object_mut: object_mut::<ContextError<C, Error>>,Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 402why, one step back402 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 403–407why, one step back403 object_boxed: object_boxed::<ContextError<C, Error>>,404 object_downcast: context_chain_downcast::<C>,405 #[cfg(anyhow_no_ptr_addr_of)]406 object_downcast_mut: context_chain_downcast_mut::<C>,407 object_drop_rest: context_chain_drop_rest::<C>,Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 408–409why, one step back408 #[cfg(all(409 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 410why, one step back410 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 411why, one step back411 ))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 412–438why, one step back412 object_backtrace: context_backtrace::<C>,413 };414415 // As the cause is anyhow::Error, we already have a backtrace for it.416 let backtrace = None;417418 // Safety: passing vtable that operates on the right type.419 unsafe { Error::construct(error, vtable, backtrace) }420 }421422 /// Get the backtrace for this Error.423 ///424 /// In order for the backtrace to be meaningful, one of the two environment425 /// variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined426 /// and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhat427 /// expensive to capture in Rust, so we don't necessarily want to be428 /// capturing them all over the place all the time.429 ///430 /// - If you want panics and errors to both have backtraces, set431 /// `RUST_BACKTRACE=1`;432 /// - If you want only errors to have backtraces, set433 /// `RUST_LIB_BACKTRACE=1`;434 /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and435 /// `RUST_LIB_BACKTRACE=0`.436 ///437 /// # Stability438 ///Touch up PR 293David Tolnaybefore adoptionb6ac995
lines 439–440why, one step back439 /// Standard library backtraces are only available when using Rust ≥440 /// 1.65. On older compilers, this function is only available if the crate'sCheck all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
line 441why, one step back441 /// "backtrace" feature is enabled, and will use the `backtrace` crate asTouch up PR 293David Tolnaybefore adoptionb6ac995
lines 442–443why, one step back442 /// the underlying backtrace implementation. The return type of this443 /// function on old compilers is `&(impl Debug + Display)`.Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 444–448why, one step back444 ///445 /// ```toml446 /// [dependencies]447 /// anyhow = { version = "1.0", features = ["backtrace"] }448 /// ```Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 449why, one step back449 #[cfg(any(std_backtrace, feature = "backtrace"))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 450–474why, one step back450 pub fn backtrace(&self) -> &impl_backtrace!() {451 unsafe { ErrorImpl::backtrace(self.inner.by_ref()) }452 }453454 /// An iterator of the chain of source errors contained by this Error.455 ///456 /// This iterator will visit every error in the cause chain of this error457 /// object, beginning with the error that this error object was created458 /// from.459 ///460 /// # Example461 ///462 /// ```463 /// use anyhow::Error;464 /// use std::io;465 ///466 /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {467 /// for cause in error.chain() {468 /// if let Some(io_error) = cause.downcast_ref::<io::Error>() {469 /// return Some(io_error.kind());470 /// }471 /// }472 /// None473 /// }474 /// ```Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 475why, one step back475 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 476–485why, one step back476 #[cold]477 pub fn chain(&self) -> Chain {478 unsafe { ErrorImpl::chain(self.inner.by_ref()) }479 }480481 /// The lowest level cause of this error — this error's cause's482 /// cause's cause etc.483 ///484 /// The root cause is the last error in the iterator produced by485 /// [`chain()`][Error::chain].Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 486why, one step back486 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Ignore double_ended_iterator_last clippy lintDavid Tolnaybefore adoption4d71a84
line 487why, one step back487 #[allow(clippy::double_ended_iterator_last)]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 488–498why, one step back488 pub fn root_cause(&self) -> &(dyn StdError + 'static) {489 self.chain().last().unwrap()490 }491492 /// Returns true if `E` is the type held by this error object.493 ///494 /// For errors with context, this method returns true if `E` matches the495 /// type of the context `C` **or** the type of the error on which the496 /// context has been attached. For details about the interaction between497 /// context and downcasting, [see here].498 ///Convert html links to intra-doc linksDavid Tolnaybefore adoptionbc33c24
line 499why, one step back499 /// [see here]: crate::Context#effect-on-downcastingCheck all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 500–610why, one step back500 pub fn is<E>(&self) -> bool501 where502 E: Display + Debug + Send + Sync + 'static,503 {504 self.downcast_ref::<E>().is_some()505 }506507 /// Attempt to downcast the error object to a concrete type.508 pub fn downcast<E>(mut self) -> Result<E, Self>509 where510 E: Display + Debug + Send + Sync + 'static,511 {512 let target = TypeId::of::<E>();513 let inner = self.inner.by_mut();514 unsafe {515 // Use vtable to find NonNull<()> which points to a value of type E516 // somewhere inside the data structure.517 #[cfg(not(anyhow_no_ptr_addr_of))]518 let addr = match (vtable(inner.ptr).object_downcast)(inner.by_ref(), target) {519 Some(addr) => addr.by_mut().extend(),520 None => return Err(self),521 };522 #[cfg(anyhow_no_ptr_addr_of)]523 let addr = match (vtable(inner.ptr).object_downcast_mut)(inner, target) {524 Some(addr) => addr.extend(),525 None => return Err(self),526 };527528 // Prepare to read E out of the data structure. We'll drop the rest529 // of the data structure separately so that E is not dropped.530 let outer = ManuallyDrop::new(self);531532 // Read E from where the vtable found it.533 let error = addr.cast::<E>().read();534535 // Drop rest of the data structure outside of E.536 (vtable(outer.inner.ptr).object_drop_rest)(outer.inner, target);537538 Ok(error)539 }540 }541542 /// Downcast this error object by reference.543 ///544 /// # Example545 ///546 /// ```547 /// # use anyhow::anyhow;548 /// # use std::fmt::{self, Display};549 /// # use std::task::Poll;550 /// #551 /// # #[derive(Debug)]552 /// # enum DataStoreError {553 /// # Censored(()),554 /// # }555 /// #556 /// # impl Display for DataStoreError {557 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {558 /// # unimplemented!()559 /// # }560 /// # }561 /// #562 /// # impl std::error::Error for DataStoreError {}563 /// #564 /// # const REDACTED_CONTENT: () = ();565 /// #566 /// # let error = anyhow!("...");567 /// # let root_cause = &error;568 /// #569 /// # let ret =570 /// // If the error was caused by redaction, then return a tombstone instead571 /// // of the content.572 /// match root_cause.downcast_ref::<DataStoreError>() {573 /// Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),574 /// None => Err(error),575 /// }576 /// # ;577 /// ```578 pub fn downcast_ref<E>(&self) -> Option<&E>579 where580 E: Display + Debug + Send + Sync + 'static,581 {582 let target = TypeId::of::<E>();583 unsafe {584 // Use vtable to find NonNull<()> which points to a value of type E585 // somewhere inside the data structure.586 let addr = (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?;587 Some(addr.cast::<E>().deref())588 }589 }590591 /// Downcast this error object by mutable reference.592 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>593 where594 E: Display + Debug + Send + Sync + 'static,595 {596 let target = TypeId::of::<E>();597 unsafe {598 // Use vtable to find NonNull<()> which points to a value of type E599 // somewhere inside the data structure.600601 #[cfg(not(anyhow_no_ptr_addr_of))]602 let addr =603 (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?.by_mut();604605 #[cfg(anyhow_no_ptr_addr_of)]606 let addr = (vtable(self.inner.ptr).object_downcast_mut)(self.inner.by_mut(), target)?;607608 Some(addr.cast::<E>().deref_mut())609 }610 }Merge pull request #268 from dtolnay/provideDavid Tolnaybefore adoption480e480
line 611why, one step back611Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 612why, one step back612 #[cfg(error_generic_member_access)]Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15
lines 613–616why, one step back613 pub(crate) fn provide<'a>(&'a self, request: &mut Request<'a>) {614 unsafe { ErrorImpl::provide(self.inner.by_ref(), request) }615 }616Merge pull request #268 from dtolnay/provideDavid Tolnaybefore adoption480e480
lines 617–621why, one step back617 // Called by thiserror when you have `#[source] anyhow::Error`. This provide618 // implementation includes the anyhow::Error's Backtrace if any, unlike619 // deref'ing to dyn Error where the provide implementation would include620 // only the original error's Backtrace from before it got wrapped into an621 // anyhow::Error.Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 622why, one step back622 #[cfg(error_generic_member_access)]Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15
lines 623–625why, one step back623 #[doc(hidden)]624 pub fn thiserror_provide<'a>(&'a self, request: &mut Request<'a>) {625 Self::provide(self, request);Merge pull request #268 from dtolnay/provideDavid Tolnaybefore adoption480e480
line 626why, one step back626 }Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 627–628why, one step back627}628Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 629why, one step back629#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 630–635why, one step back630impl<E> From<E> for Error631where632 E: StdError + Send + Sync + 'static,633{634 #[cold]635 fn from(error: E) -> Self {Merge pull request #266 from dtolnay/providerDavid Tolnaybefore adoption546342c
line 636why, one step back636 let backtrace = backtrace_if_absent!(&error);Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
line 637why, one step back637 Error::construct_from_std(error, backtrace)Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 638–640why, one step back638 }639}640Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 641why, one step back641#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 642–649why, one step back642impl Deref for Error {643 type Target = dyn StdError + Send + Sync + 'static;644645 fn deref(&self) -> &Self::Target {646 unsafe { ErrorImpl::error(self.inner.by_ref()) }647 }648}649Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 650why, one step back650#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 651–680why, one step back651impl DerefMut for Error {652 fn deref_mut(&mut self) -> &mut Self::Target {653 unsafe { ErrorImpl::error_mut(self.inner.by_mut()) }654 }655}656657impl Display for Error {658 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {659 unsafe { ErrorImpl::display(self.inner.by_ref(), formatter) }660 }661}662663impl Debug for Error {664 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {665 unsafe { ErrorImpl::debug(self.inner.by_ref(), formatter) }666 }667}668669impl Drop for Error {670 fn drop(&mut self) {671 unsafe {672 // Invoke the vtable's drop behavior.673 (vtable(self.inner.ptr).object_drop)(self.inner);674 }675 }676}677678struct ErrorVTable {679 object_drop: unsafe fn(Own<ErrorImpl>),680 object_ref: unsafe fn(Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>,Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 681why, one step back681 #[cfg(all(any(feature = "std", not(anyhow_no_core_error)), anyhow_no_ptr_addr_of))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
line 682why, one step back682 object_mut: unsafe fn(Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static),Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 683why, one step back683 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 684–688why, one step back684 object_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,685 object_downcast: unsafe fn(Ref<ErrorImpl>, TypeId) -> Option<Ref<()>>,686 #[cfg(anyhow_no_ptr_addr_of)]687 object_downcast_mut: unsafe fn(Mut<ErrorImpl>, TypeId) -> Option<Mut<()>>,688 object_drop_rest: unsafe fn(Own<ErrorImpl>, TypeId),Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 689–690why, one step back689 #[cfg(all(690 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 691why, one step back691 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 692why, one step back692 ))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 693–699why, one step back693 object_backtrace: unsafe fn(Ref<ErrorImpl>) -> Option<&Backtrace>,694}695696// Safety: requires layout of *e to match ErrorImpl<E>.697unsafe fn object_drop<E>(e: Own<ErrorImpl>) {698 // Cast back to ErrorImpl<E> so that the allocator receives the correct699 // Layout to deallocate the Box's memory.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 700–701why, one step back700 let unerased_own = e.cast::<ErrorImpl<E>>();701 drop(unsafe { unerased_own.boxed() });Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 702–709why, one step back702}703704// Safety: requires layout of *e to match ErrorImpl<E>.705unsafe fn object_drop_front<E>(e: Own<ErrorImpl>, target: TypeId) {706 // Drop the fields of ErrorImpl other than E as well as the Box allocation,707 // without dropping E itself. This is used by downcast after doing a708 // ptr::read to take ownership of the E.709 let _ = target;Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 710–711why, one step back710 let unerased_own = e.cast::<ErrorImpl<ManuallyDrop<E>>>();711 drop(unsafe { unerased_own.boxed() });Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 712–720why, one step back712}713714// Safety: requires layout of *e to match ErrorImpl<E>.715unsafe fn object_ref<E>(e: Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>716where717 E: StdError + Send + Sync + 'static,718{719 // Attach E's native StdError vtable onto a pointer to self._object.720Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 721why, one step back721 let unerased_ref = e.cast::<ErrorImpl<E>>();Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 722–723why, one step back722723 #[cfg(not(anyhow_no_ptr_addr_of))]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 724–726why, one step back724 return Ref::from_raw(unsafe {725 NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object) as *mut E)726 });Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 727–728why, one step back727728 #[cfg(anyhow_no_ptr_addr_of)]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 729why, one step back729 return Ref::new(unsafe { &unerased_ref.deref()._object });Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 730–733why, one step back730}731732// Safety: requires layout of *e to match ErrorImpl<E>, and for `e` to be derived733// from a `&mut`Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 734why, one step back734#[cfg(all(any(feature = "std", not(anyhow_no_core_error)), anyhow_no_ptr_addr_of))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 735–739why, one step back735unsafe fn object_mut<E>(e: Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static)736where737 E: StdError + Send + Sync + 'static,738{739 // Attach E's native StdError vtable onto a pointer to self._object.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 740–741why, one step back740 let unerased_mut = e.cast::<ErrorImpl<E>>();741 unsafe { &mut unerased_mut.deref_mut()._object }Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 742–744why, one step back742}743744// Safety: requires layout of *e to match ErrorImpl<E>.Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 745why, one step back745#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 746–750why, one step back746unsafe fn object_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>747where748 E: StdError + Send + Sync + 'static,749{750 // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 751–752why, one step back751 let unerased_own = e.cast::<ErrorImpl<E>>();752 unsafe { unerased_own.boxed() }Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 753–763why, one step back753}754755// Safety: requires layout of *e to match ErrorImpl<E>.756unsafe fn object_downcast<E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>757where758 E: 'static,759{760 if TypeId::of::<E>() == target {761 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a762 // pointer to its E field.763Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 764why, one step back764 let unerased_ref = e.cast::<ErrorImpl<E>>();Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 765–767why, one step back765766 #[cfg(not(anyhow_no_ptr_addr_of))]767 return Some(Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 768–770why, one step back768 Ref::from_raw(unsafe {769 NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object) as *mut E)770 })Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 771–774why, one step back771 .cast::<()>(),772 );773774 #[cfg(anyhow_no_ptr_addr_of)]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 775why, one step back775 return Some(Ref::new(unsafe { &unerased_ref.deref()._object }).cast::<()>());Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 776–789why, one step back776 } else {777 None778 }779}780781// Safety: requires layout of *e to match ErrorImpl<E>.782#[cfg(anyhow_no_ptr_addr_of)]783unsafe fn object_downcast_mut<E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>784where785 E: 'static,786{787 if TypeId::of::<E>() == target {788 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a789 // pointer to its E field.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 790–791why, one step back790 let unerased_mut = e.cast::<ErrorImpl<E>>();791 let unerased = unsafe { unerased_mut.deref_mut() };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 792–797why, one step back792 Some(Mut::new(&mut unerased._object).cast::<()>())793 } else {794 None795 }796}797Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 798–799why, one step back798#[cfg(all(799 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 800why, one step back800 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 801why, one step back801))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 802–807why, one step back802fn no_backtrace(e: Ref<ErrorImpl>) -> Option<&Backtrace> {803 let _ = e;804 None805}806807// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 808why, one step back808#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 809–814why, one step back809unsafe fn context_downcast<C, E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>810where811 C: 'static,812 E: 'static,813{814 if TypeId::of::<C>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 815–816why, one step back815 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();816 let unerased = unsafe { unerased_ref.deref() };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 817–818why, one step back817 Some(Ref::new(&unerased._object.context).cast::<()>())818 } else if TypeId::of::<E>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 819–820why, one step back819 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();820 let unerased = unsafe { unerased_ref.deref() };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 821–834why, one step back821 Some(Ref::new(&unerased._object.error).cast::<()>())822 } else {823 None824 }825}826827// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.828#[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]829unsafe fn context_downcast_mut<C, E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>830where831 C: 'static,832 E: 'static,833{834 if TypeId::of::<C>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 835–836why, one step back835 let unerased_mut = e.cast::<ErrorImpl<ContextError<C, E>>>();836 let unerased = unsafe { unerased_mut.deref_mut() };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 837–838why, one step back837 Some(Mut::new(&mut unerased._object.context).cast::<()>())838 } else if TypeId::of::<E>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 839–840why, one step back839 let unerased_mut = e.cast::<ErrorImpl<ContextError<C, E>>>();840 let unerased = unsafe { unerased_mut.deref_mut() };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 841–847why, one step back841 Some(Mut::new(&mut unerased._object.error).cast::<()>())842 } else {843 None844 }845}846847// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 848why, one step back848#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 849–856why, one step back849unsafe fn context_drop_rest<C, E>(e: Own<ErrorImpl>, target: TypeId)850where851 C: 'static,852 E: 'static,853{854 // Called after downcasting by value to either the C or the E and doing a855 // ptr::read to take ownership of that value.856 if TypeId::of::<C>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 857–858why, one step back857 let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>();858 drop(unsafe { unerased_own.boxed() });Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
line 859why, one step back859 } else {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 860–861why, one step back860 let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>();861 drop(unsafe { unerased_own.boxed() });Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 862–869why, one step back862 }863}864865// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.866unsafe fn context_chain_downcast<C>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>867where868 C: 'static,869{Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 870–871why, one step back870 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();871 let unerased = unsafe { unerased_ref.deref() };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 872–876why, one step back872 if TypeId::of::<C>() == target {873 Some(Ref::new(&unerased._object.context).cast::<()>())874 } else {875 // Recurse down the context chain per the inner error's vtable.876 let source = &unerased._object.error;Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 877why, one step back877 unsafe { (vtable(source.inner.ptr).object_downcast)(source.inner.by_ref(), target) }Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 878–886why, one step back878 }879}880881// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.882#[cfg(anyhow_no_ptr_addr_of)]883unsafe fn context_chain_downcast_mut<C>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>884where885 C: 'static,886{Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 887–888why, one step back887 let unerased_mut = e.cast::<ErrorImpl<ContextError<C, Error>>>();888 let unerased = unsafe { unerased_mut.deref_mut() };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 889–893why, one step back889 if TypeId::of::<C>() == target {890 Some(Mut::new(&mut unerased._object.context).cast::<()>())891 } else {892 // Recurse down the context chain per the inner error's vtable.893 let source = &mut unerased._object.error;Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 894why, one step back894 unsafe { (vtable(source.inner.ptr).object_downcast_mut)(source.inner.by_mut(), target) }Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 895–905why, one step back895 }896}897898// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.899unsafe fn context_chain_drop_rest<C>(e: Own<ErrorImpl>, target: TypeId)900where901 C: 'static,902{903 // Called after downcasting by value to either the C or one of the causes904 // and doing a ptr::read to take ownership of that value.905 if TypeId::of::<C>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 906why, one step back906 let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>();Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
line 907why, one step back907 // Drop the entire rest of the data structure rooted in the next Error.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 908why, one step back908 drop(unsafe { unerased_own.boxed() });Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
line 909why, one step back909 } else {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 910–911why, one step back910 let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>();911 let unerased = unsafe { unerased_own.boxed() };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 912–914why, one step back912 // Read the Own<ErrorImpl> from the next error.913 let inner = unerased._object.error.inner;914 drop(unerased);Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 915why, one step back915 let vtable = unsafe { vtable(inner.ptr) };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
line 916why, one step back916 // Recursively drop the next error using the same target typeid.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 917why, one step back917 unsafe { (vtable.object_drop_rest)(inner, target) };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 918–921why, one step back918 }919}920921// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 922–923why, one step back922#[cfg(all(923 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 924why, one step back924 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 925why, one step back925))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 926–930why, one step back926#[allow(clippy::unnecessary_wraps)]927unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>928where929 C: 'static,930{Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 931–933why, one step back931 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();932 let unerased = unsafe { unerased_ref.deref() };933 let backtrace = unsafe { ErrorImpl::backtrace(unerased._object.error.inner.by_ref()) };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 934–952why, one step back934 Some(backtrace)935}936937// NOTE: If working with `ErrorImpl<()>`, references should be avoided in favor938// of raw pointers and `NonNull`.939// repr C to ensure that E remains in the final position.940#[repr(C)]941pub(crate) struct ErrorImpl<E = ()> {942 vtable: &'static ErrorVTable,943 backtrace: Option<Backtrace>,944 // NOTE: Don't use directly. Use only through vtable. Erased type may have945 // different alignment.946 _object: E,947}948949// Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but950// avoids converting `p` into a reference.951unsafe fn vtable(p: NonNull<ErrorImpl>) -> &'static ErrorVTable {952 // NOTE: This assumes that `ErrorVTable` is the first field of ErrorImpl.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 953why, one step back953 unsafe { *(p.as_ptr() as *const &'static ErrorVTable) }Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 954–976why, one step back954}955956// repr C to ensure that ContextError<C, E> has the same layout as957// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.958#[repr(C)]959pub(crate) struct ContextError<C, E> {960 pub context: C,961 pub error: E,962}963964impl<E> ErrorImpl<E> {965 fn erase(&self) -> Ref<ErrorImpl> {966 // Erase the concrete type of E but preserve the vtable in self.vtable967 // for manipulating the resulting thin pointer. This is analogous to an968 // unsize coercion.969 Ref::new(self).cast::<ErrorImpl>()970 }971}972973impl ErrorImpl {974 pub(crate) unsafe fn error(this: Ref<Self>) -> &(dyn StdError + Send + Sync + 'static) {975 // Use vtable to attach E's native StdError vtable for the right976 // original type E.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 977why, one step back977 unsafe { (vtable(this.ptr).object_ref)(this).deref() }Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 978–979why, one step back978 }979Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 980why, one step back980 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 981–985why, one step back981 pub(crate) unsafe fn error_mut(this: Mut<Self>) -> &mut (dyn StdError + Send + Sync + 'static) {982 // Use vtable to attach E's native StdError vtable for the right983 // original type E.984985 #[cfg(not(anyhow_no_ptr_addr_of))]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 986–990why, one step back986 return unsafe {987 (vtable(this.ptr).object_ref)(this.by_ref())988 .by_mut()989 .deref_mut()990 };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 991–992why, one step back991992 #[cfg(anyhow_no_ptr_addr_of)]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 993why, one step back993 return unsafe { (vtable(this.ptr).object_mut)(this) };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 994–995why, one step back994 }995Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 996why, one step back996 #[cfg(any(std_backtrace, feature = "backtrace"))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 997–1000why, one step back997 pub(crate) unsafe fn backtrace(this: Ref<Self>) -> &Backtrace {998 // This unwrap can only panic if the underlying error's backtrace method999 // is nondeterministic, which would only happen in maliciously1000 // constructed code.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 1001why, one step back1001 unsafe { this.deref() }Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 1002–1004why, one step back1002 .backtrace1003 .as_ref()1004 .or_else(|| {Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 1005why, one step back1005 #[cfg(error_generic_member_access)]Merge pull request #414 from dtolnay/nightlyDavid Tolnaybefore adoption213a9c2
line 1006why, one step back1006 return nightly::request_ref_backtrace(unsafe { Self::error(this) });Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 1007why, one step back1007 #[cfg(not(error_generic_member_access))]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 1008why, one step back1008 return unsafe { (vtable(this.ptr).object_backtrace)(this) };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 1009–1012why, one step back1009 })1010 .expect("backtrace capture failed")1011 }1012Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 1013why, one step back1013 #[cfg(error_generic_member_access)]Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15
line 1014why, one step back1014 unsafe fn provide<'a>(this: Ref<'a, Self>, request: &mut Request<'a>) {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 1015why, one step back1015 if let Some(backtrace) = unsafe { &this.deref().backtrace } {Merge pull request #414 from dtolnay/nightlyDavid Tolnaybefore adoption213a9c2
line 1016why, one step back1016 nightly::provide_ref_backtrace(request, backtrace);Merge pull request #266 from dtolnay/providerDavid Tolnaybefore adoption546342c
line 1017why, one step back1017 }Merge pull request #414 from dtolnay/nightlyDavid Tolnaybefore adoption213a9c2
line 1018why, one step back1018 nightly::provide(unsafe { Self::error(this) }, request);Merge pull request #266 from dtolnay/providerDavid Tolnaybefore adoption546342c
lines 1019–1020why, one step back1019 }1020Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 1021–1022why, one step back1021 #[cold]1022 pub(crate) unsafe fn chain(this: Ref<Self>) -> Chain {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 1023why, one step back1023 Chain::new(unsafe { Self::error(this) })Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 1024–1032why, one step back1024 }1025}10261027impl<E> StdError for ErrorImpl<E>1028where1029 E: StdError,1030{1031 fn source(&self) -> Option<&(dyn StdError + 'static)> {1032 unsafe { ErrorImpl::error(self.erase()).source() }Merge pull request #266 from dtolnay/providerDavid Tolnaybefore adoption546342c
lines 1033–1034why, one step back1033 }1034Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 1035why, one step back1035 #[cfg(error_generic_member_access)]Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15
lines 1036–1037why, one step back1036 fn provide<'a>(&'a self, request: &mut Request<'a>) {1037 unsafe { ErrorImpl::provide(self.erase(), request) }Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 1038–1058why, one step back1038 }1039}10401041impl<E> Debug for ErrorImpl<E>1042where1043 E: Debug,1044{1045 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1046 unsafe { ErrorImpl::debug(self.erase(), formatter) }1047 }1048}10491050impl<E> Display for ErrorImpl<E>1051where1052 E: Display,1053{1054 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1055 unsafe { Display::fmt(ErrorImpl::error(self.erase()), formatter) }1056 }1057}1058Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 1059why, one step back1059#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 1060–1071why, one step back1060impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {1061 #[cold]1062 fn from(error: Error) -> Self {1063 let outer = ManuallyDrop::new(error);1064 unsafe {1065 // Use vtable to attach ErrorImpl<E>'s native StdError vtable for1066 // the right original type E.1067 (vtable(outer.inner.ptr).object_boxed)(outer.inner)1068 }1069 }1070}1071Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 1072why, one step back1072#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 1073–1078why, one step back1073impl From<Error> for Box<dyn StdError + Send + 'static> {1074 fn from(error: Error) -> Self {1075 Box::<dyn StdError + Send + Sync>::from(error)1076 }1077}1078Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 1079why, one step back1079#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 1080–1085why, one step back1080impl From<Error> for Box<dyn StdError + 'static> {1081 fn from(error: Error) -> Self {1082 Box::<dyn StdError + Send + Sync>::from(error)1083 }1084}1085Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 1086why, one step back1086#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 1087–1092why, one step back1087impl AsRef<dyn StdError + Send + Sync> for Error {1088 fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {1089 &**self1090 }1091}1092Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 1093why, one step back1093#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 1094–1098why, one step back1094impl AsRef<dyn StdError> for Error {1095 fn as_ref(&self) -> &(dyn StdError + 'static) {1096 &**self1097 }1098}Merge pull request #386 from dtolnay/unwindsafeDavid Tolnaybefore adoption830c399
lines 1099–1104why, one step back10991100#[cfg(any(feature = "std", not(anyhow_no_core_unwind_safe)))]1101impl UnwindSafe for Error {}11021103#[cfg(any(feature = "std", not(anyhow_no_core_unwind_safe)))]1104impl RefUnwindSafe for Error {}