error.rs
This file
Path
src/error.rs
1,093 lines · 38.2 KiB · Rust
Last changed by
Convert html links to intra-doc linksDavid Tolnaybefore adoptionbc33c24
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 #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))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
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};Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
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};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–164why, 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>,160 object_boxed: object_boxed::<E>,161 object_downcast: object_downcast::<E>,162 #[cfg(anyhow_no_ptr_addr_of)]163 object_downcast_mut: object_downcast_mut::<E>,164 object_drop_rest: object_drop_front::<E>,Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 165–166why, one step back165 #[cfg(all(166 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 167why, one step back167 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 168why, one step back168 ))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 169–176why, one step back169 object_backtrace: no_backtrace,170 };171172 // Safety: passing vtable that operates on the right type E.173 unsafe { Error::construct(error, vtable, backtrace) }174 }175176 #[cold]Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
line 177why, one step back177 pub(crate) fn construct_from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> SelfCheck all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 178–185why, one step back178 where179 M: Display + Debug + Send + Sync + 'static,180 {181 use crate::wrapper::MessageError;182 let error: MessageError<M> = MessageError(message);183 let vtable = &ErrorVTable {184 object_drop: object_drop::<MessageError<M>>,185 object_ref: object_ref::<MessageError<M>>,Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 186why, one step back186 #[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 187–192why, one step back187 object_mut: object_mut::<MessageError<M>>,188 object_boxed: object_boxed::<MessageError<M>>,189 object_downcast: object_downcast::<M>,190 #[cfg(anyhow_no_ptr_addr_of)]191 object_downcast_mut: object_downcast_mut::<M>,192 object_drop_rest: object_drop_front::<M>,Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 193–194why, one step back193 #[cfg(all(194 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 195why, one step back195 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 196why, one step back196 ))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 197–205why, one step back197 object_backtrace: no_backtrace,198 };199200 // Safety: MessageError is repr(transparent) so it is okay for the201 // vtable to allow casting the MessageError<M> to M.202 unsafe { Error::construct(error, vtable, backtrace) }203 }204205 #[cold]Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
line 206why, one step back206 pub(crate) fn construct_from_display<M>(message: M, backtrace: Option<Backtrace>) -> SelfCheck all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 207–214why, one step back207 where208 M: Display + Send + Sync + 'static,209 {210 use crate::wrapper::DisplayError;211 let error: DisplayError<M> = DisplayError(message);212 let vtable = &ErrorVTable {213 object_drop: object_drop::<DisplayError<M>>,214 object_ref: object_ref::<DisplayError<M>>,Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 215why, one step back215 #[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 216–221why, one step back216 object_mut: object_mut::<DisplayError<M>>,217 object_boxed: object_boxed::<DisplayError<M>>,218 object_downcast: object_downcast::<M>,219 #[cfg(anyhow_no_ptr_addr_of)]220 object_downcast_mut: object_downcast_mut::<M>,221 object_drop_rest: object_drop_front::<M>,Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 222–223why, one step back222 #[cfg(all(223 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 224why, one step back224 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 225why, one step back225 ))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 226–233why, one step back226 object_backtrace: no_backtrace,227 };228229 // Safety: DisplayError is repr(transparent) so it is okay for the230 // vtable to allow casting the DisplayError<M> to M.231 unsafe { Error::construct(error, vtable, backtrace) }232 }233Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 234why, one step back234 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
line 235why, one step back235 #[cold]Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
lines 236–240why, one step back236 pub(crate) fn construct_from_context<C, E>(237 context: C,238 error: E,239 backtrace: Option<Backtrace>,240 ) -> SelfCheck all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 241–256why, one step back241 where242 C: Display + Send + Sync + 'static,243 E: StdError + Send + Sync + 'static,244 {245 let error: ContextError<C, E> = ContextError { context, error };246247 let vtable = &ErrorVTable {248 object_drop: object_drop::<ContextError<C, E>>,249 object_ref: object_ref::<ContextError<C, E>>,250 #[cfg(anyhow_no_ptr_addr_of)]251 object_mut: object_mut::<ContextError<C, E>>,252 object_boxed: object_boxed::<ContextError<C, E>>,253 object_downcast: context_downcast::<C, E>,254 #[cfg(anyhow_no_ptr_addr_of)]255 object_downcast_mut: context_downcast_mut::<C, E>,256 object_drop_rest: context_drop_rest::<C, E>,Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 257–258why, one step back257 #[cfg(all(258 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 259why, one step back259 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 260why, one step back260 ))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 261–267why, one step back261 object_backtrace: no_backtrace,262 };263264 // Safety: passing vtable that operates on the right type.265 unsafe { Error::construct(error, vtable, backtrace) }266 }267Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 268why, one step back268 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
line 269why, one step back269 #[cold]Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
line 270why, one step back270 pub(crate) fn construct_from_boxed(Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 271–285why, one step back271 error: Box<dyn StdError + Send + Sync>,272 backtrace: Option<Backtrace>,273 ) -> Self {274 use crate::wrapper::BoxedError;275 let error = BoxedError(error);276 let vtable = &ErrorVTable {277 object_drop: object_drop::<BoxedError>,278 object_ref: object_ref::<BoxedError>,279 #[cfg(anyhow_no_ptr_addr_of)]280 object_mut: object_mut::<BoxedError>,281 object_boxed: object_boxed::<BoxedError>,282 object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,283 #[cfg(anyhow_no_ptr_addr_of)]284 object_downcast_mut: object_downcast_mut::<Box<dyn StdError + Send + Sync>>,285 object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 286–287why, one step back286 #[cfg(all(287 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 288why, one step back288 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 289why, one step back289 ))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 290–394why, one step back290 object_backtrace: no_backtrace,291 };292293 // Safety: BoxedError is repr(transparent) so it is okay for the vtable294 // to allow casting to Box<dyn StdError + Send + Sync>.295 unsafe { Error::construct(error, vtable, backtrace) }296 }297298 // Takes backtrace as argument rather than capturing it here so that the299 // user sees one fewer layer of wrapping noise in the backtrace.300 //301 // Unsafe because the given vtable must have sensible behavior on the error302 // value of type E.303 #[cold]304 unsafe fn construct<E>(305 error: E,306 vtable: &'static ErrorVTable,307 backtrace: Option<Backtrace>,308 ) -> Self309 where310 E: StdError + Send + Sync + 'static,311 {312 let inner: Box<ErrorImpl<E>> = Box::new(ErrorImpl {313 vtable,314 backtrace,315 _object: error,316 });317 // Erase the concrete type of E from the compile-time type system. This318 // is equivalent to the safe unsize coercion from Box<ErrorImpl<E>> to319 // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the320 // result is a thin pointer. The necessary behavior for manipulating the321 // underlying ErrorImpl<E> is preserved in the vtable provided by the322 // caller rather than a builtin fat pointer vtable.323 let inner = Own::new(inner).cast::<ErrorImpl>();324 Error { inner }325 }326327 /// Wrap the error value with additional context.328 ///329 /// For attaching context to a `Result` as it is propagated, the330 /// [`Context`][crate::Context] extension trait may be more convenient than331 /// this function.332 ///333 /// The primary reason to use `error.context(...)` instead of334 /// `result.context(...)` via the `Context` trait would be if the context335 /// needs to depend on some data held by the underlying error:336 ///337 /// ```338 /// # use std::fmt::{self, Debug, Display};339 /// #340 /// # type T = ();341 /// #342 /// # impl std::error::Error for ParseError {}343 /// # impl Debug for ParseError {344 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {345 /// # unimplemented!()346 /// # }347 /// # }348 /// # impl Display for ParseError {349 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {350 /// # unimplemented!()351 /// # }352 /// # }353 /// #354 /// use anyhow::Result;355 /// use std::fs::File;356 /// use std::path::Path;357 ///358 /// struct ParseError {359 /// line: usize,360 /// column: usize,361 /// }362 ///363 /// fn parse_impl(file: File) -> Result<T, ParseError> {364 /// # const IGNORE: &str = stringify! {365 /// ...366 /// # };367 /// # unimplemented!()368 /// }369 ///370 /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {371 /// let file = File::open(&path)?;372 /// parse_impl(file).map_err(|error| {373 /// let context = format!(374 /// "only the first {} lines of {} are valid",375 /// error.line, path.as_ref().display(),376 /// );377 /// anyhow::Error::new(error).context(context)378 /// })379 /// }380 /// ```381 #[cold]382 #[must_use]383 pub fn context<C>(self, context: C) -> Self384 where385 C: Display + Send + Sync + 'static,386 {387 let error: ContextError<C, Error> = ContextError {388 context,389 error: self,390 };391392 let vtable = &ErrorVTable {393 object_drop: object_drop::<ContextError<C, Error>>,394 object_ref: object_ref::<ContextError<C, Error>>,Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 395why, one step back395 #[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 396–401why, one step back396 object_mut: object_mut::<ContextError<C, Error>>,397 object_boxed: object_boxed::<ContextError<C, Error>>,398 object_downcast: context_chain_downcast::<C>,399 #[cfg(anyhow_no_ptr_addr_of)]400 object_downcast_mut: context_chain_downcast_mut::<C>,401 object_drop_rest: context_chain_drop_rest::<C>,Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 402–403why, one step back402 #[cfg(all(403 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 404why, one step back404 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 405why, one step back405 ))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 406–432why, one step back406 object_backtrace: context_backtrace::<C>,407 };408409 // As the cause is anyhow::Error, we already have a backtrace for it.410 let backtrace = None;411412 // Safety: passing vtable that operates on the right type.413 unsafe { Error::construct(error, vtable, backtrace) }414 }415416 /// Get the backtrace for this Error.417 ///418 /// In order for the backtrace to be meaningful, one of the two environment419 /// variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined420 /// and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhat421 /// expensive to capture in Rust, so we don't necessarily want to be422 /// capturing them all over the place all the time.423 ///424 /// - If you want panics and errors to both have backtraces, set425 /// `RUST_BACKTRACE=1`;426 /// - If you want only errors to have backtraces, set427 /// `RUST_LIB_BACKTRACE=1`;428 /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and429 /// `RUST_LIB_BACKTRACE=0`.430 ///431 /// # Stability432 ///Touch up PR 293David Tolnaybefore adoptionb6ac995
lines 433–434why, one step back433 /// Standard library backtraces are only available when using Rust ≥434 /// 1.65. On older compilers, this function is only available if the crate'sCheck all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
line 435why, one step back435 /// "backtrace" feature is enabled, and will use the `backtrace` crate asTouch up PR 293David Tolnaybefore adoptionb6ac995
lines 436–437why, one step back436 /// the underlying backtrace implementation. The return type of this437 /// function on old compilers is `&(impl Debug + Display)`.Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 438–442why, one step back438 ///439 /// ```toml440 /// [dependencies]441 /// anyhow = { version = "1.0", features = ["backtrace"] }442 /// ```Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 443why, one step back443 #[cfg(any(std_backtrace, feature = "backtrace"))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 444–468why, one step back444 pub fn backtrace(&self) -> &impl_backtrace!() {445 unsafe { ErrorImpl::backtrace(self.inner.by_ref()) }446 }447448 /// An iterator of the chain of source errors contained by this Error.449 ///450 /// This iterator will visit every error in the cause chain of this error451 /// object, beginning with the error that this error object was created452 /// from.453 ///454 /// # Example455 ///456 /// ```457 /// use anyhow::Error;458 /// use std::io;459 ///460 /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {461 /// for cause in error.chain() {462 /// if let Some(io_error) = cause.downcast_ref::<io::Error>() {463 /// return Some(io_error.kind());464 /// }465 /// }466 /// None467 /// }468 /// ```Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 469why, one step back469 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 470–479why, one step back470 #[cold]471 pub fn chain(&self) -> Chain {472 unsafe { ErrorImpl::chain(self.inner.by_ref()) }473 }474475 /// The lowest level cause of this error — this error's cause's476 /// cause's cause etc.477 ///478 /// The root cause is the last error in the iterator produced by479 /// [`chain()`][Error::chain].Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 480why, one step back480 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Ignore double_ended_iterator_last clippy lintDavid Tolnaybefore adoption4d71a84
line 481why, one step back481 #[allow(clippy::double_ended_iterator_last)]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 482–492why, one step back482 pub fn root_cause(&self) -> &(dyn StdError + 'static) {483 self.chain().last().unwrap()484 }485486 /// Returns true if `E` is the type held by this error object.487 ///488 /// For errors with context, this method returns true if `E` matches the489 /// type of the context `C` **or** the type of the error on which the490 /// context has been attached. For details about the interaction between491 /// context and downcasting, [see here].492 ///Convert html links to intra-doc linksDavid Tolnaybefore adoptionbc33c24
line 493why, one step back493 /// [see here]: crate::Context#effect-on-downcastingCheck all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 494–604why, one step back494 pub fn is<E>(&self) -> bool495 where496 E: Display + Debug + Send + Sync + 'static,497 {498 self.downcast_ref::<E>().is_some()499 }500501 /// Attempt to downcast the error object to a concrete type.502 pub fn downcast<E>(mut self) -> Result<E, Self>503 where504 E: Display + Debug + Send + Sync + 'static,505 {506 let target = TypeId::of::<E>();507 let inner = self.inner.by_mut();508 unsafe {509 // Use vtable to find NonNull<()> which points to a value of type E510 // somewhere inside the data structure.511 #[cfg(not(anyhow_no_ptr_addr_of))]512 let addr = match (vtable(inner.ptr).object_downcast)(inner.by_ref(), target) {513 Some(addr) => addr.by_mut().extend(),514 None => return Err(self),515 };516 #[cfg(anyhow_no_ptr_addr_of)]517 let addr = match (vtable(inner.ptr).object_downcast_mut)(inner, target) {518 Some(addr) => addr.extend(),519 None => return Err(self),520 };521522 // Prepare to read E out of the data structure. We'll drop the rest523 // of the data structure separately so that E is not dropped.524 let outer = ManuallyDrop::new(self);525526 // Read E from where the vtable found it.527 let error = addr.cast::<E>().read();528529 // Drop rest of the data structure outside of E.530 (vtable(outer.inner.ptr).object_drop_rest)(outer.inner, target);531532 Ok(error)533 }534 }535536 /// Downcast this error object by reference.537 ///538 /// # Example539 ///540 /// ```541 /// # use anyhow::anyhow;542 /// # use std::fmt::{self, Display};543 /// # use std::task::Poll;544 /// #545 /// # #[derive(Debug)]546 /// # enum DataStoreError {547 /// # Censored(()),548 /// # }549 /// #550 /// # impl Display for DataStoreError {551 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {552 /// # unimplemented!()553 /// # }554 /// # }555 /// #556 /// # impl std::error::Error for DataStoreError {}557 /// #558 /// # const REDACTED_CONTENT: () = ();559 /// #560 /// # let error = anyhow!("...");561 /// # let root_cause = &error;562 /// #563 /// # let ret =564 /// // If the error was caused by redaction, then return a tombstone instead565 /// // of the content.566 /// match root_cause.downcast_ref::<DataStoreError>() {567 /// Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),568 /// None => Err(error),569 /// }570 /// # ;571 /// ```572 pub fn downcast_ref<E>(&self) -> Option<&E>573 where574 E: Display + Debug + Send + Sync + 'static,575 {576 let target = TypeId::of::<E>();577 unsafe {578 // Use vtable to find NonNull<()> which points to a value of type E579 // somewhere inside the data structure.580 let addr = (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?;581 Some(addr.cast::<E>().deref())582 }583 }584585 /// Downcast this error object by mutable reference.586 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>587 where588 E: Display + Debug + Send + Sync + 'static,589 {590 let target = TypeId::of::<E>();591 unsafe {592 // Use vtable to find NonNull<()> which points to a value of type E593 // somewhere inside the data structure.594595 #[cfg(not(anyhow_no_ptr_addr_of))]596 let addr =597 (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?.by_mut();598599 #[cfg(anyhow_no_ptr_addr_of)]600 let addr = (vtable(self.inner.ptr).object_downcast_mut)(self.inner.by_mut(), target)?;601602 Some(addr.cast::<E>().deref_mut())603 }604 }Merge pull request #268 from dtolnay/provideDavid Tolnaybefore adoption480e480
line 605why, one step back605Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 606why, one step back606 #[cfg(error_generic_member_access)]Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15
lines 607–610why, one step back607 pub(crate) fn provide<'a>(&'a self, request: &mut Request<'a>) {608 unsafe { ErrorImpl::provide(self.inner.by_ref(), request) }609 }610Merge pull request #268 from dtolnay/provideDavid Tolnaybefore adoption480e480
lines 611–615why, one step back611 // Called by thiserror when you have `#[source] anyhow::Error`. This provide612 // implementation includes the anyhow::Error's Backtrace if any, unlike613 // deref'ing to dyn Error where the provide implementation would include614 // only the original error's Backtrace from before it got wrapped into an615 // anyhow::Error.Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 616why, one step back616 #[cfg(error_generic_member_access)]Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15
lines 617–619why, one step back617 #[doc(hidden)]618 pub fn thiserror_provide<'a>(&'a self, request: &mut Request<'a>) {619 Self::provide(self, request);Merge pull request #268 from dtolnay/provideDavid Tolnaybefore adoption480e480
line 620why, one step back620 }Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 621–622why, one step back621}622Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 623why, one step back623#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 624–629why, one step back624impl<E> From<E> for Error625where626 E: StdError + Send + Sync + 'static,627{628 #[cold]629 fn from(error: E) -> Self {Merge pull request #266 from dtolnay/providerDavid Tolnaybefore adoption546342c
line 630why, one step back630 let backtrace = backtrace_if_absent!(&error);Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
line 631why, one step back631 Error::construct_from_std(error, backtrace)Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 632–634why, one step back632 }633}634Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 635why, one step back635#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 636–643why, one step back636impl Deref for Error {637 type Target = dyn StdError + Send + Sync + 'static;638639 fn deref(&self) -> &Self::Target {640 unsafe { ErrorImpl::error(self.inner.by_ref()) }641 }642}643Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 644why, one step back644#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 645–674why, one step back645impl DerefMut for Error {646 fn deref_mut(&mut self) -> &mut Self::Target {647 unsafe { ErrorImpl::error_mut(self.inner.by_mut()) }648 }649}650651impl Display for Error {652 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {653 unsafe { ErrorImpl::display(self.inner.by_ref(), formatter) }654 }655}656657impl Debug for Error {658 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {659 unsafe { ErrorImpl::debug(self.inner.by_ref(), formatter) }660 }661}662663impl Drop for Error {664 fn drop(&mut self) {665 unsafe {666 // Invoke the vtable's drop behavior.667 (vtable(self.inner.ptr).object_drop)(self.inner);668 }669 }670}671672struct ErrorVTable {673 object_drop: unsafe fn(Own<ErrorImpl>),674 object_ref: unsafe fn(Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>,Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 675why, one step back675 #[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 676–681why, one step back676 object_mut: unsafe fn(Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static),677 object_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,678 object_downcast: unsafe fn(Ref<ErrorImpl>, TypeId) -> Option<Ref<()>>,679 #[cfg(anyhow_no_ptr_addr_of)]680 object_downcast_mut: unsafe fn(Mut<ErrorImpl>, TypeId) -> Option<Mut<()>>,681 object_drop_rest: unsafe fn(Own<ErrorImpl>, TypeId),Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 682–683why, one step back682 #[cfg(all(683 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 684why, one step back684 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 685why, one step back685 ))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 686–692why, one step back686 object_backtrace: unsafe fn(Ref<ErrorImpl>) -> Option<&Backtrace>,687}688689// Safety: requires layout of *e to match ErrorImpl<E>.690unsafe fn object_drop<E>(e: Own<ErrorImpl>) {691 // Cast back to ErrorImpl<E> so that the allocator receives the correct692 // Layout to deallocate the Box's memory.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 693–694why, one step back693 let unerased_own = e.cast::<ErrorImpl<E>>();694 drop(unsafe { unerased_own.boxed() });Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 695–702why, one step back695}696697// Safety: requires layout of *e to match ErrorImpl<E>.698unsafe fn object_drop_front<E>(e: Own<ErrorImpl>, target: TypeId) {699 // Drop the fields of ErrorImpl other than E as well as the Box allocation,700 // without dropping E itself. This is used by downcast after doing a701 // ptr::read to take ownership of the E.702 let _ = target;Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 703–704why, one step back703 let unerased_own = e.cast::<ErrorImpl<ManuallyDrop<E>>>();704 drop(unsafe { unerased_own.boxed() });Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 705–713why, one step back705}706707// Safety: requires layout of *e to match ErrorImpl<E>.708unsafe fn object_ref<E>(e: Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>709where710 E: StdError + Send + Sync + 'static,711{712 // Attach E's native StdError vtable onto a pointer to self._object.713Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 714why, one step back714 let unerased_ref = e.cast::<ErrorImpl<E>>();Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 715–716why, one step back715716 #[cfg(not(anyhow_no_ptr_addr_of))]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 717–719why, one step back717 return Ref::from_raw(unsafe {718 NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object) as *mut E)719 });Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 720–721why, one step back720721 #[cfg(anyhow_no_ptr_addr_of)]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 722why, one step back722 return Ref::new(unsafe { &unerased_ref.deref()._object });Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 723–726why, one step back723}724725// Safety: requires layout of *e to match ErrorImpl<E>, and for `e` to be derived726// from a `&mut`Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 727why, one step back727#[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 728–732why, one step back728unsafe fn object_mut<E>(e: Mut<ErrorImpl>) -> &mut (dyn StdError + Send + Sync + 'static)729where730 E: StdError + Send + Sync + 'static,731{732 // Attach E's native StdError vtable onto a pointer to self._object.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 733–734why, one step back733 let unerased_mut = e.cast::<ErrorImpl<E>>();734 unsafe { &mut unerased_mut.deref_mut()._object }Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 735–742why, one step back735}736737// Safety: requires layout of *e to match ErrorImpl<E>.738unsafe fn object_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>739where740 E: StdError + Send + Sync + 'static,741{742 // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 743–744why, one step back743 let unerased_own = e.cast::<ErrorImpl<E>>();744 unsafe { unerased_own.boxed() }Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 745–755why, one step back745}746747// Safety: requires layout of *e to match ErrorImpl<E>.748unsafe fn object_downcast<E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>749where750 E: 'static,751{752 if TypeId::of::<E>() == target {753 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a754 // pointer to its E field.755Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 756why, one step back756 let unerased_ref = e.cast::<ErrorImpl<E>>();Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 757–759why, one step back757758 #[cfg(not(anyhow_no_ptr_addr_of))]759 return Some(Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 760–762why, one step back760 Ref::from_raw(unsafe {761 NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object) as *mut E)762 })Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 763–766why, one step back763 .cast::<()>(),764 );765766 #[cfg(anyhow_no_ptr_addr_of)]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 767why, one step back767 return Some(Ref::new(unsafe { &unerased_ref.deref()._object }).cast::<()>());Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 768–781why, one step back768 } else {769 None770 }771}772773// Safety: requires layout of *e to match ErrorImpl<E>.774#[cfg(anyhow_no_ptr_addr_of)]775unsafe fn object_downcast_mut<E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>776where777 E: 'static,778{779 if TypeId::of::<E>() == target {780 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a781 // pointer to its E field.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 782–783why, one step back782 let unerased_mut = e.cast::<ErrorImpl<E>>();783 let unerased = unsafe { unerased_mut.deref_mut() };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 784–789why, one step back784 Some(Mut::new(&mut unerased._object).cast::<()>())785 } else {786 None787 }788}789Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 790–791why, one step back790#[cfg(all(791 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 792why, one step back792 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 793why, one step back793))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 794–799why, one step back794fn no_backtrace(e: Ref<ErrorImpl>) -> Option<&Backtrace> {795 let _ = e;796 None797}798799// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 800why, one step back800#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 801–806why, one step back801unsafe fn context_downcast<C, E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>802where803 C: 'static,804 E: 'static,805{806 if TypeId::of::<C>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 807–808why, one step back807 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();808 let unerased = unsafe { unerased_ref.deref() };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 809–810why, one step back809 Some(Ref::new(&unerased._object.context).cast::<()>())810 } else if TypeId::of::<E>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 811–812why, one step back811 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();812 let unerased = unsafe { unerased_ref.deref() };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 813–826why, one step back813 Some(Ref::new(&unerased._object.error).cast::<()>())814 } else {815 None816 }817}818819// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.820#[cfg(all(feature = "std", anyhow_no_ptr_addr_of))]821unsafe fn context_downcast_mut<C, E>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>822where823 C: 'static,824 E: 'static,825{826 if TypeId::of::<C>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 827–828why, one step back827 let unerased_mut = e.cast::<ErrorImpl<ContextError<C, E>>>();828 let unerased = unsafe { unerased_mut.deref_mut() };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 829–830why, one step back829 Some(Mut::new(&mut unerased._object.context).cast::<()>())830 } else if TypeId::of::<E>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 831–832why, one step back831 let unerased_mut = e.cast::<ErrorImpl<ContextError<C, E>>>();832 let unerased = unsafe { unerased_mut.deref_mut() };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 833–839why, one step back833 Some(Mut::new(&mut unerased._object.error).cast::<()>())834 } else {835 None836 }837}838839// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 840why, one step back840#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 841–848why, one step back841unsafe fn context_drop_rest<C, E>(e: Own<ErrorImpl>, target: TypeId)842where843 C: 'static,844 E: 'static,845{846 // Called after downcasting by value to either the C or the E and doing a847 // ptr::read to take ownership of that value.848 if TypeId::of::<C>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 849–850why, one step back849 let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>();850 drop(unsafe { unerased_own.boxed() });Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
line 851why, one step back851 } else {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 852–853why, one step back852 let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>();853 drop(unsafe { unerased_own.boxed() });Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 854–861why, one step back854 }855}856857// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.858unsafe fn context_chain_downcast<C>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>859where860 C: 'static,861{Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 862–863why, one step back862 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();863 let unerased = unsafe { unerased_ref.deref() };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 864–868why, one step back864 if TypeId::of::<C>() == target {865 Some(Ref::new(&unerased._object.context).cast::<()>())866 } else {867 // Recurse down the context chain per the inner error's vtable.868 let source = &unerased._object.error;Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 869why, one step back869 unsafe { (vtable(source.inner.ptr).object_downcast)(source.inner.by_ref(), target) }Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 870–878why, one step back870 }871}872873// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.874#[cfg(anyhow_no_ptr_addr_of)]875unsafe fn context_chain_downcast_mut<C>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>876where877 C: 'static,878{Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 879–880why, one step back879 let unerased_mut = e.cast::<ErrorImpl<ContextError<C, Error>>>();880 let unerased = unsafe { unerased_mut.deref_mut() };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 881–885why, one step back881 if TypeId::of::<C>() == target {882 Some(Mut::new(&mut unerased._object.context).cast::<()>())883 } else {884 // Recurse down the context chain per the inner error's vtable.885 let source = &mut unerased._object.error;Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 886why, one step back886 unsafe { (vtable(source.inner.ptr).object_downcast_mut)(source.inner.by_mut(), target) }Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 887–897why, one step back887 }888}889890// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.891unsafe fn context_chain_drop_rest<C>(e: Own<ErrorImpl>, target: TypeId)892where893 C: 'static,894{895 // Called after downcasting by value to either the C or one of the causes896 // and doing a ptr::read to take ownership of that value.897 if TypeId::of::<C>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 898why, one step back898 let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>();Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
line 899why, one step back899 // Drop the entire rest of the data structure rooted in the next Error.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 900why, one step back900 drop(unsafe { unerased_own.boxed() });Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
line 901why, one step back901 } else {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 902–903why, one step back902 let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>();903 let unerased = unsafe { unerased_own.boxed() };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 904–906why, one step back904 // Read the Own<ErrorImpl> from the next error.905 let inner = unerased._object.error.inner;906 drop(unerased);Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 907why, one step back907 let vtable = unsafe { vtable(inner.ptr) };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
line 908why, one step back908 // Recursively drop the next error using the same target typeid.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 909why, one step back909 unsafe { (vtable.object_drop_rest)(inner, target) };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 910–913why, one step back910 }911}912913// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
lines 914–915why, one step back914#[cfg(all(915 not(error_generic_member_access),Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 916why, one step back916 any(std_backtrace, feature = "backtrace")Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 917why, one step back917))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 918–922why, one step back918#[allow(clippy::unnecessary_wraps)]919unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>920where921 C: 'static,922{Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 923–925why, one step back923 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();924 let unerased = unsafe { unerased_ref.deref() };925 let backtrace = unsafe { ErrorImpl::backtrace(unerased._object.error.inner.by_ref()) };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 926–944why, one step back926 Some(backtrace)927}928929// NOTE: If working with `ErrorImpl<()>`, references should be avoided in favor930// of raw pointers and `NonNull`.931// repr C to ensure that E remains in the final position.932#[repr(C)]933pub(crate) struct ErrorImpl<E = ()> {934 vtable: &'static ErrorVTable,935 backtrace: Option<Backtrace>,936 // NOTE: Don't use directly. Use only through vtable. Erased type may have937 // different alignment.938 _object: E,939}940941// Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but942// avoids converting `p` into a reference.943unsafe fn vtable(p: NonNull<ErrorImpl>) -> &'static ErrorVTable {944 // NOTE: This assumes that `ErrorVTable` is the first field of ErrorImpl.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 945why, one step back945 unsafe { *(p.as_ptr() as *const &'static ErrorVTable) }Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 946–968why, one step back946}947948// repr C to ensure that ContextError<C, E> has the same layout as949// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.950#[repr(C)]951pub(crate) struct ContextError<C, E> {952 pub context: C,953 pub error: E,954}955956impl<E> ErrorImpl<E> {957 fn erase(&self) -> Ref<ErrorImpl> {958 // Erase the concrete type of E but preserve the vtable in self.vtable959 // for manipulating the resulting thin pointer. This is analogous to an960 // unsize coercion.961 Ref::new(self).cast::<ErrorImpl>()962 }963}964965impl ErrorImpl {966 pub(crate) unsafe fn error(this: Ref<Self>) -> &(dyn StdError + Send + Sync + 'static) {967 // Use vtable to attach E's native StdError vtable for the right968 // original type E.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 969why, one step back969 unsafe { (vtable(this.ptr).object_ref)(this).deref() }Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 970–971why, one step back970 }971Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 972why, one step back972 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 973–977why, one step back973 pub(crate) unsafe fn error_mut(this: Mut<Self>) -> &mut (dyn StdError + Send + Sync + 'static) {974 // Use vtable to attach E's native StdError vtable for the right975 // original type E.976977 #[cfg(not(anyhow_no_ptr_addr_of))]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 978–982why, one step back978 return unsafe {979 (vtable(this.ptr).object_ref)(this.by_ref())980 .by_mut()981 .deref_mut()982 };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 983–984why, one step back983984 #[cfg(anyhow_no_ptr_addr_of)]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 985why, one step back985 return unsafe { (vtable(this.ptr).object_mut)(this) };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 986–987why, one step back986 }987Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6
line 988why, one step back988 #[cfg(any(std_backtrace, feature = "backtrace"))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 989–992why, one step back989 pub(crate) unsafe fn backtrace(this: Ref<Self>) -> &Backtrace {990 // This unwrap can only panic if the underlying error's backtrace method991 // is nondeterministic, which would only happen in maliciously992 // constructed code.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 993why, one step back993 unsafe { this.deref() }Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 994–996why, one step back994 .backtrace995 .as_ref()996 .or_else(|| {Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 997why, one step back997 #[cfg(error_generic_member_access)]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 998why, one step back998 return error::request_ref::<Backtrace>(unsafe { Self::error(this) });Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 999why, one step back999 #[cfg(not(error_generic_member_access))]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 1000why, one step back1000 return unsafe { (vtable(this.ptr).object_backtrace)(this) };Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 1001–1004why, one step back1001 })1002 .expect("backtrace capture failed")1003 }1004Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 1005why, one step back1005 #[cfg(error_generic_member_access)]Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15
line 1006why, one step back1006 unsafe fn provide<'a>(this: Ref<'a, Self>, request: &mut Request<'a>) {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 1007why, one step back1007 if let Some(backtrace) = unsafe { &this.deref().backtrace } {Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15
line 1008why, one step back1008 request.provide_ref(backtrace);Merge pull request #266 from dtolnay/providerDavid Tolnaybefore adoption546342c
line 1009why, one step back1009 }Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 1010why, one step back1010 unsafe { Self::error(this) }.provide(request);Merge pull request #266 from dtolnay/providerDavid Tolnaybefore adoption546342c
lines 1011–1012why, one step back1011 }1012Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 1013–1014why, one step back1013 #[cold]1014 pub(crate) unsafe fn chain(this: Ref<Self>) -> Chain {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 1015why, one step back1015 Chain::new(unsafe { Self::error(this) })Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 1016–1024why, one step back1016 }1017}10181019impl<E> StdError for ErrorImpl<E>1020where1021 E: StdError,1022{1023 fn source(&self) -> Option<&(dyn StdError + 'static)> {1024 unsafe { ErrorImpl::error(self.erase()).source() }Merge pull request #266 from dtolnay/providerDavid Tolnaybefore adoption546342c
lines 1025–1026why, one step back1025 }1026Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 1027why, one step back1027 #[cfg(error_generic_member_access)]Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15
lines 1028–1029why, one step back1028 fn provide<'a>(&'a self, request: &mut Request<'a>) {1029 unsafe { ErrorImpl::provide(self.erase(), request) }Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 1030–1074why, one step back1030 }1031}10321033impl<E> Debug for ErrorImpl<E>1034where1035 E: Debug,1036{1037 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1038 unsafe { ErrorImpl::debug(self.erase(), formatter) }1039 }1040}10411042impl<E> Display for ErrorImpl<E>1043where1044 E: Display,1045{1046 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1047 unsafe { Display::fmt(ErrorImpl::error(self.erase()), formatter) }1048 }1049}10501051impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {1052 #[cold]1053 fn from(error: Error) -> Self {1054 let outer = ManuallyDrop::new(error);1055 unsafe {1056 // Use vtable to attach ErrorImpl<E>'s native StdError vtable for1057 // the right original type E.1058 (vtable(outer.inner.ptr).object_boxed)(outer.inner)1059 }1060 }1061}10621063impl From<Error> for Box<dyn StdError + Send + 'static> {1064 fn from(error: Error) -> Self {1065 Box::<dyn StdError + Send + Sync>::from(error)1066 }1067}10681069impl From<Error> for Box<dyn StdError + 'static> {1070 fn from(error: Error) -> Self {1071 Box::<dyn StdError + Send + Sync>::from(error)1072 }1073}1074Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 1075why, one step back1075#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 1076–1081why, one step back1076impl AsRef<dyn StdError + Send + Sync> for Error {1077 fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {1078 &**self1079 }1080}1081Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 1082why, one step back1082#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Check all crates in workspace for outdated depsDavid Tolnaybefore adoptionff37db3
lines 1083–1087why, one step back1083impl AsRef<dyn StdError> for Error {1084 fn as_ref(&self) -> &(dyn StdError + 'static) {1085 &**self1086 }1087}Merge pull request #386 from dtolnay/unwindsafeDavid Tolnaybefore adoption830c399
lines 1088–1093why, one step back10881089#[cfg(any(feature = "std", not(anyhow_no_core_unwind_safe)))]1090impl UnwindSafe for Error {}10911092#[cfg(any(feature = "std", not(anyhow_no_core_unwind_safe)))]1093impl RefUnwindSafe for Error {}