error.rs
This file
Path
src/error.rs
1,060 lines · 38.3 KiB · Rust
Last changed by
Merge pull request #452 from dtolnay/downcastDavid Tolnaybefore adoptione621bd3
History of this fileTake it
The walk stopped after 200 commits: lines older than 553ed38 point at it.
Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
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 #435 from dtolnay/upDavid Tolnaybefore adoptionb86c3c8
line 5why, one step back5#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
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
line 15why, one step back15use core::panic::{RefUnwindSafe, UnwindSafe};Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 16–26why, one step back16use core::ptr;17use core::ptr::NonNull;1819impl Error {20 /// Create a new error object from any error type.21 ///22 /// The error type must be threadsafe and `'static`, so that the `Error`23 /// will be as well.24 ///25 /// If the error type does not provide a backtrace, a backtrace will be26 /// created here to ensure that a backtrace exists.Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 27why, one step back27 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 28–34why, one step back28 #[cold]29 #[must_use]30 pub fn new<E>(error: E) -> Self31 where32 E: StdError + Send + Sync + 'static,33 {34 let backtrace = backtrace_if_absent!(&error);Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
line 35why, one step back35 Error::construct_from_std(error, backtrace)Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 36–80why, one step back36 }3738 /// Create a new error object from a printable error message.39 ///40 /// If the argument implements std::error::Error, prefer `Error::new`41 /// instead which preserves the underlying error's cause chain and42 /// backtrace. If the argument may or may not implement std::error::Error43 /// now or in the future, use `anyhow!(err)` which handles either way44 /// correctly.45 ///46 /// `Error::msg("...")` is equivalent to `anyhow!("...")` but occasionally47 /// convenient in places where a function is preferable over a macro, such48 /// as iterator or stream combinators:49 ///50 /// ```51 /// # mod ffi {52 /// # pub struct Input;53 /// # pub struct Output;54 /// # pub async fn do_some_work(_: Input) -> Result<Output, &'static str> {55 /// # unimplemented!()56 /// # }57 /// # }58 /// #59 /// # use ffi::{Input, Output};60 /// #61 /// use anyhow::{Error, Result};62 /// use futures::stream::{Stream, StreamExt, TryStreamExt};63 ///64 /// async fn demo<S>(stream: S) -> Result<Vec<Output>>65 /// where66 /// S: Stream<Item = Input>,67 /// {68 /// stream69 /// .then(ffi::do_some_work) // returns Result<Output, &str>70 /// .map_err(Error::msg)71 /// .try_collect()72 /// .await73 /// }74 /// ```75 #[cold]76 #[must_use]77 pub fn msg<M>(message: M) -> Self78 where79 M: Display + Debug + Send + Sync + 'static,80 {Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
line 81why, one step back81 Error::construct_from_adhoc(message, backtrace!())Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 82–83why, one step back82 }83Merge pull request #402 from dtolnay/fromboxedDavid Tolnaybefore adoptiona03d6d6
lines 84–144why, one step back84 /// Construct an error object from a type-erased standard library error.85 ///86 /// This is mostly useful for interop with other error libraries.87 ///88 /// # Example89 ///90 /// Here is a skeleton of a library that provides its own error abstraction.91 /// The pair of `From` impls provide bidirectional support for `?`92 /// conversion between `Report` and `anyhow::Error`.93 ///94 /// ```95 /// use std::error::Error as StdError;96 ///97 /// pub struct Report {/* ... */}98 ///99 /// impl<E> From<E> for Report100 /// where101 /// E: Into<anyhow::Error>,102 /// Result<(), E>: anyhow::Context<(), E>,103 /// {104 /// fn from(error: E) -> Self {105 /// let anyhow_error: anyhow::Error = error.into();106 /// let boxed_error: Box<dyn StdError + Send + Sync + 'static> = anyhow_error.into();107 /// Report::from_boxed(boxed_error)108 /// }109 /// }110 ///111 /// impl From<Report> for anyhow::Error {112 /// fn from(report: Report) -> Self {113 /// let boxed_error: Box<dyn StdError + Send + Sync + 'static> = report.into_boxed();114 /// anyhow::Error::from_boxed(boxed_error)115 /// }116 /// }117 ///118 /// impl Report {119 /// fn from_boxed(boxed_error: Box<dyn StdError + Send + Sync + 'static>) -> Self {120 /// todo!()121 /// }122 /// fn into_boxed(self) -> Box<dyn StdError + Send + Sync + 'static> {123 /// todo!()124 /// }125 /// }126 ///127 /// // Example usage: can use `?` in both directions.128 /// fn a() -> anyhow::Result<()> {129 /// b()?;130 /// Ok(())131 /// }132 /// fn b() -> Result<(), Report> {133 /// a()?;134 /// Ok(())135 /// }136 /// ```137 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]138 #[cold]139 #[must_use]140 pub fn from_boxed(boxed_error: Box<dyn StdError + Send + Sync + 'static>) -> Self {141 let backtrace = backtrace_if_absent!(&*boxed_error);142 Error::construct_from_boxed(boxed_error, backtrace)143 }144Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 145why, one step back145 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 146why, one step back146 #[cold]Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
line 147why, one step back147 pub(crate) fn construct_from_std<E>(error: E, backtrace: Option<Backtrace>) -> SelfUpdate clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 148–154why, one step back148 where149 E: StdError + Send + Sync + 'static,150 {151 let vtable = &ErrorVTable {152 object_drop: object_drop::<E>,153 object_ref: object_ref::<E>,154 object_boxed: object_boxed::<E>,Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2
line 155why, one step back155 object_reallocate_boxed: object_reallocate_boxed::<E>,Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 156–157why, one step back156 object_downcast: object_downcast::<E>,157 object_drop_rest: object_drop_front::<E>,Merge pull request #440 from dtolnay/backtraceDavid Tolnaybefore adoption9b67e5d
line 158why, one step back158 #[cfg(all(not(error_generic_member_access), feature = "std"))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 159–166why, one step back159 object_backtrace: no_backtrace,160 };161162 // Safety: passing vtable that operates on the right type E.163 unsafe { Error::construct(error, vtable, backtrace) }164 }165166 #[cold]Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
line 167why, one step back167 pub(crate) fn construct_from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> SelfUpdate clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 168–175why, one step back168 where169 M: Display + Debug + Send + Sync + 'static,170 {171 use crate::wrapper::MessageError;172 let error: MessageError<M> = MessageError(message);173 let vtable = &ErrorVTable {174 object_drop: object_drop::<MessageError<M>>,175 object_ref: object_ref::<MessageError<M>>,Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 176why, one step back176 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 177why, one step back177 object_boxed: object_boxed::<MessageError<M>>,Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2
lines 178–179why, one step back178 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]179 object_reallocate_boxed: object_reallocate_boxed::<MessageError<M>>,Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 180–181why, one step back180 object_downcast: object_downcast::<M>,181 object_drop_rest: object_drop_front::<M>,Merge pull request #440 from dtolnay/backtraceDavid Tolnaybefore adoption9b67e5d
line 182why, one step back182 #[cfg(all(not(error_generic_member_access), feature = "std"))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 183–191why, one step back183 object_backtrace: no_backtrace,184 };185186 // Safety: MessageError is repr(transparent) so it is okay for the187 // vtable to allow casting the MessageError<M> to M.188 unsafe { Error::construct(error, vtable, backtrace) }189 }190191 #[cold]Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
line 192why, one step back192 pub(crate) fn construct_from_display<M>(message: M, backtrace: Option<Backtrace>) -> SelfUpdate clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 193–200why, one step back193 where194 M: Display + Send + Sync + 'static,195 {196 use crate::wrapper::DisplayError;197 let error: DisplayError<M> = DisplayError(message);198 let vtable = &ErrorVTable {199 object_drop: object_drop::<DisplayError<M>>,200 object_ref: object_ref::<DisplayError<M>>,Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 201why, one step back201 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 202why, one step back202 object_boxed: object_boxed::<DisplayError<M>>,Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2
lines 203–204why, one step back203 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]204 object_reallocate_boxed: object_reallocate_boxed::<DisplayError<M>>,Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 205–206why, one step back205 object_downcast: object_downcast::<M>,206 object_drop_rest: object_drop_front::<M>,Merge pull request #440 from dtolnay/backtraceDavid Tolnaybefore adoption9b67e5d
line 207why, one step back207 #[cfg(all(not(error_generic_member_access), feature = "std"))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 208–215why, one step back208 object_backtrace: no_backtrace,209 };210211 // Safety: DisplayError is repr(transparent) so it is okay for the212 // vtable to allow casting the DisplayError<M> to M.213 unsafe { Error::construct(error, vtable, backtrace) }214 }215Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 216why, one step back216 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 217why, one step back217 #[cold]Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
lines 218–222why, one step back218 pub(crate) fn construct_from_context<C, E>(219 context: C,220 error: E,221 backtrace: Option<Backtrace>,222 ) -> SelfUpdate clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 223–231why, one step back223 where224 C: Display + Send + Sync + 'static,225 E: StdError + Send + Sync + 'static,226 {227 let error: ContextError<C, E> = ContextError { context, error };228229 let vtable = &ErrorVTable {230 object_drop: object_drop::<ContextError<C, E>>,231 object_ref: object_ref::<ContextError<C, E>>,Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 232why, one step back232 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 233why, one step back233 object_boxed: object_boxed::<ContextError<C, E>>,Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2
lines 234–235why, one step back234 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]235 object_reallocate_boxed: object_reallocate_boxed::<ContextError<C, E>>,Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 236–237why, one step back236 object_downcast: context_downcast::<C, E>,237 object_drop_rest: context_drop_rest::<C, E>,Merge pull request #440 from dtolnay/backtraceDavid Tolnaybefore adoption9b67e5d
line 238why, one step back238 #[cfg(all(not(error_generic_member_access), feature = "std"))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 239–245why, one step back239 object_backtrace: no_backtrace,240 };241242 // Safety: passing vtable that operates on the right type.243 unsafe { Error::construct(error, vtable, backtrace) }244 }245Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 246why, one step back246 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 247why, one step back247 #[cold]Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
line 248why, one step back248 pub(crate) fn construct_from_boxed(Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 249–256why, one step back249 error: Box<dyn StdError + Send + Sync>,250 backtrace: Option<Backtrace>,251 ) -> Self {252 use crate::wrapper::BoxedError;253 let error = BoxedError(error);254 let vtable = &ErrorVTable {255 object_drop: object_drop::<BoxedError>,256 object_ref: object_ref::<BoxedError>,Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 257why, one step back257 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 258why, one step back258 object_boxed: object_boxed::<BoxedError>,Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2
lines 259–260why, one step back259 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]260 object_reallocate_boxed: object_reallocate_boxed::<BoxedError>,Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 261–262why, one step back261 object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,262 object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,Merge pull request #440 from dtolnay/backtraceDavid Tolnaybefore adoption9b67e5d
line 263why, one step back263 #[cfg(all(not(error_generic_member_access), feature = "std"))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 264–368why, one step back264 object_backtrace: no_backtrace,265 };266267 // Safety: BoxedError is repr(transparent) so it is okay for the vtable268 // to allow casting to Box<dyn StdError + Send + Sync>.269 unsafe { Error::construct(error, vtable, backtrace) }270 }271272 // Takes backtrace as argument rather than capturing it here so that the273 // user sees one fewer layer of wrapping noise in the backtrace.274 //275 // Unsafe because the given vtable must have sensible behavior on the error276 // value of type E.277 #[cold]278 unsafe fn construct<E>(279 error: E,280 vtable: &'static ErrorVTable,281 backtrace: Option<Backtrace>,282 ) -> Self283 where284 E: StdError + Send + Sync + 'static,285 {286 let inner: Box<ErrorImpl<E>> = Box::new(ErrorImpl {287 vtable,288 backtrace,289 _object: error,290 });291 // Erase the concrete type of E from the compile-time type system. This292 // is equivalent to the safe unsize coercion from Box<ErrorImpl<E>> to293 // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the294 // result is a thin pointer. The necessary behavior for manipulating the295 // underlying ErrorImpl<E> is preserved in the vtable provided by the296 // caller rather than a builtin fat pointer vtable.297 let inner = Own::new(inner).cast::<ErrorImpl>();298 Error { inner }299 }300301 /// Wrap the error value with additional context.302 ///303 /// For attaching context to a `Result` as it is propagated, the304 /// [`Context`][crate::Context] extension trait may be more convenient than305 /// this function.306 ///307 /// The primary reason to use `error.context(...)` instead of308 /// `result.context(...)` via the `Context` trait would be if the context309 /// needs to depend on some data held by the underlying error:310 ///311 /// ```312 /// # use std::fmt::{self, Debug, Display};313 /// #314 /// # type T = ();315 /// #316 /// # impl std::error::Error for ParseError {}317 /// # impl Debug for ParseError {318 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {319 /// # unimplemented!()320 /// # }321 /// # }322 /// # impl Display for ParseError {323 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {324 /// # unimplemented!()325 /// # }326 /// # }327 /// #328 /// use anyhow::Result;329 /// use std::fs::File;330 /// use std::path::Path;331 ///332 /// struct ParseError {333 /// line: usize,334 /// column: usize,335 /// }336 ///337 /// fn parse_impl(file: File) -> Result<T, ParseError> {338 /// # const IGNORE: &str = stringify! {339 /// ...340 /// # };341 /// # unimplemented!()342 /// }343 ///344 /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {345 /// let file = File::open(&path)?;346 /// parse_impl(file).map_err(|error| {347 /// let context = format!(348 /// "only the first {} lines of {} are valid",349 /// error.line, path.as_ref().display(),350 /// );351 /// anyhow::Error::new(error).context(context)352 /// })353 /// }354 /// ```355 #[cold]356 #[must_use]357 pub fn context<C>(self, context: C) -> Self358 where359 C: Display + Send + Sync + 'static,360 {361 let error: ContextError<C, Error> = ContextError {362 context,363 error: self,364 };365366 let vtable = &ErrorVTable {367 object_drop: object_drop::<ContextError<C, Error>>,368 object_ref: object_ref::<ContextError<C, Error>>,Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 369why, one step back369 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 370why, one step back370 object_boxed: object_boxed::<ContextError<C, Error>>,Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2
lines 371–372why, one step back371 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]372 object_reallocate_boxed: object_reallocate_boxed::<ContextError<C, Error>>,Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 373–374why, one step back373 object_downcast: context_chain_downcast::<C>,374 object_drop_rest: context_chain_drop_rest::<C>,Merge pull request #440 from dtolnay/backtraceDavid Tolnaybefore adoption9b67e5d
line 375why, one step back375 #[cfg(all(not(error_generic_member_access), feature = "std"))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 376–402why, one step back376 object_backtrace: context_backtrace::<C>,377 };378379 // As the cause is anyhow::Error, we already have a backtrace for it.380 let backtrace = None;381382 // Safety: passing vtable that operates on the right type.383 unsafe { Error::construct(error, vtable, backtrace) }384 }385386 /// Get the backtrace for this Error.387 ///388 /// In order for the backtrace to be meaningful, one of the two environment389 /// variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined390 /// and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhat391 /// expensive to capture in Rust, so we don't necessarily want to be392 /// capturing them all over the place all the time.393 ///394 /// - If you want panics and errors to both have backtraces, set395 /// `RUST_BACKTRACE=1`;396 /// - If you want only errors to have backtraces, set397 /// `RUST_LIB_BACKTRACE=1`;398 /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and399 /// `RUST_LIB_BACKTRACE=0`.400 ///401 /// # Stability402 ///Touch up PR 293David Tolnaybefore adoptionb6ac995
lines 403–404why, one step back403 /// Standard library backtraces are only available when using Rust ≥404 /// 1.65. On older compilers, this function is only available if the crate'sUpdate clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 405why, one step back405 /// "backtrace" feature is enabled, and will use the `backtrace` crate asTouch up PR 293David Tolnaybefore adoptionb6ac995
lines 406–407why, one step back406 /// the underlying backtrace implementation. The return type of this407 /// function on old compilers is `&(impl Debug + Display)`.Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 408–412why, one step back408 ///409 /// ```toml410 /// [dependencies]411 /// anyhow = { version = "1.0", features = ["backtrace"] }412 /// ```Merge pull request #440 from dtolnay/backtraceDavid Tolnaybefore adoption9b67e5d
line 413why, one step back413 #[cfg(feature = "std")]Merge pull request #442 from dtolnay/backtraceDavid Tolnaybefore adoptione737fb6
line 414why, one step back414 pub fn backtrace(&self) -> &Backtrace {Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 415–438why, one step back415 unsafe { ErrorImpl::backtrace(self.inner.by_ref()) }416 }417418 /// An iterator of the chain of source errors contained by this Error.419 ///420 /// This iterator will visit every error in the cause chain of this error421 /// object, beginning with the error that this error object was created422 /// from.423 ///424 /// # Example425 ///426 /// ```427 /// use anyhow::Error;428 /// use std::io;429 ///430 /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {431 /// for cause in error.chain() {432 /// if let Some(io_error) = cause.downcast_ref::<io::Error>() {433 /// return Some(io_error.kind());434 /// }435 /// }436 /// None437 /// }438 /// ```Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 439why, one step back439 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 440–449why, one step back440 #[cold]441 pub fn chain(&self) -> Chain {442 unsafe { ErrorImpl::chain(self.inner.by_ref()) }443 }444445 /// The lowest level cause of this error — this error's cause's446 /// cause's cause etc.447 ///448 /// The root cause is the last error in the iterator produced by449 /// [`chain()`][Error::chain].Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 450why, one step back450 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Ignore double_ended_iterator_last clippy lintDavid Tolnaybefore adoption4d71a84
line 451why, one step back451 #[allow(clippy::double_ended_iterator_last)]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 452–462why, one step back452 pub fn root_cause(&self) -> &(dyn StdError + 'static) {453 self.chain().last().unwrap()454 }455456 /// Returns true if `E` is the type held by this error object.457 ///458 /// For errors with context, this method returns true if `E` matches the459 /// type of the context `C` **or** the type of the error on which the460 /// context has been attached. For details about the interaction between461 /// context and downcasting, [see here].462 ///Convert html links to intra-doc linksDavid Tolnaybefore adoptionbc33c24
line 463why, one step back463 /// [see here]: crate::Context#effect-on-downcastingUpdate clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 464–563why, one step back464 pub fn is<E>(&self) -> bool465 where466 E: Display + Debug + Send + Sync + 'static,467 {468 self.downcast_ref::<E>().is_some()469 }470471 /// Attempt to downcast the error object to a concrete type.472 pub fn downcast<E>(mut self) -> Result<E, Self>473 where474 E: Display + Debug + Send + Sync + 'static,475 {476 let target = TypeId::of::<E>();477 let inner = self.inner.by_mut();478 unsafe {479 // Use vtable to find NonNull<()> which points to a value of type E480 // somewhere inside the data structure.481 let addr = match (vtable(inner.ptr).object_downcast)(inner.by_ref(), target) {482 Some(addr) => addr.by_mut().extend(),483 None => return Err(self),484 };485486 // Prepare to read E out of the data structure. We'll drop the rest487 // of the data structure separately so that E is not dropped.488 let outer = ManuallyDrop::new(self);489490 // Read E from where the vtable found it.491 let error = addr.cast::<E>().read();492493 // Drop rest of the data structure outside of E.494 (vtable(outer.inner.ptr).object_drop_rest)(outer.inner, target);495496 Ok(error)497 }498 }499500 /// Downcast this error object by reference.501 ///502 /// # Example503 ///504 /// ```505 /// # use anyhow::anyhow;506 /// # use std::fmt::{self, Display};507 /// # use std::task::Poll;508 /// #509 /// # #[derive(Debug)]510 /// # enum DataStoreError {511 /// # Censored(()),512 /// # }513 /// #514 /// # impl Display for DataStoreError {515 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {516 /// # unimplemented!()517 /// # }518 /// # }519 /// #520 /// # impl std::error::Error for DataStoreError {}521 /// #522 /// # const REDACTED_CONTENT: () = ();523 /// #524 /// # let error = anyhow!("...");525 /// # let root_cause = &error;526 /// #527 /// # let ret =528 /// // If the error was caused by redaction, then return a tombstone instead529 /// // of the content.530 /// match root_cause.downcast_ref::<DataStoreError>() {531 /// Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),532 /// None => Err(error),533 /// }534 /// # ;535 /// ```536 pub fn downcast_ref<E>(&self) -> Option<&E>537 where538 E: Display + Debug + Send + Sync + 'static,539 {540 let target = TypeId::of::<E>();541 unsafe {542 // Use vtable to find NonNull<()> which points to a value of type E543 // somewhere inside the data structure.544 let addr = (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?;545 Some(addr.cast::<E>().deref())546 }547 }548549 /// Downcast this error object by mutable reference.550 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>551 where552 E: Display + Debug + Send + Sync + 'static,553 {554 let target = TypeId::of::<E>();555 unsafe {556 // Use vtable to find NonNull<()> which points to a value of type E557 // somewhere inside the data structure.558 let addr =559 (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?.by_mut();560 Some(addr.cast::<E>().deref_mut())561 }562 }563Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2
lines 564–655why, one step back564 /// Convert to a standard library error trait object.565 ///566 /// This is implemented as a cheap pointer cast that does not allocate or567 /// deallocate memory. Like [`anyhow::Error::from_boxed`], it's useful for568 /// interop with other error libraries.569 ///570 /// The same conversion is also available as571 /// <code style="display:inline;white-space:normal;">impl From<anyhow::Error>572 /// for Box<dyn Error + Send + Sync + 'static></code>.573 ///574 /// If a backtrace was collected during construction of the `anyhow::Error`,575 /// that backtrace remains accessible using the standard library `Error`576 /// trait's provider API, but as a consequence, the resulting boxed error577 /// can no longer be downcast to its original underlying type.578 ///579 /// ```580 #[cfg_attr(not(error_generic_member_access), doc = "# _ = stringify! {")]581 /// #![feature(error_generic_member_access)]582 ///583 /// use anyhow::anyhow;584 /// use std::backtrace::Backtrace;585 /// use thiserror::Error;586 ///587 /// #[derive(Error, Debug)]588 /// #[error("...")]589 /// struct MyError;590 ///591 /// let anyhow_error = anyhow!(MyError);592 /// println!("{}", anyhow_error.backtrace()); // has Backtrace593 /// assert!(anyhow_error.downcast_ref::<MyError>().is_some()); // can downcast594 ///595 /// let boxed_dyn_error = anyhow_error.into_boxed_dyn_error();596 /// assert!(std::error::request_ref::<Backtrace>(&*boxed_dyn_error).is_some()); // has Backtrace597 /// assert!(boxed_dyn_error.downcast_ref::<MyError>().is_none()); // can no longer downcast598 #[cfg_attr(not(error_generic_member_access), doc = "# };")]599 /// ```600 ///601 /// [`anyhow::Error::from_boxed`]: Self::from_boxed602 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]603 #[must_use]604 pub fn into_boxed_dyn_error(self) -> Box<dyn StdError + Send + Sync + 'static> {605 let outer = ManuallyDrop::new(self);606 unsafe {607 // Use vtable to attach ErrorImpl<E>'s native StdError vtable for608 // the right original type E.609 (vtable(outer.inner.ptr).object_boxed)(outer.inner)610 }611 }612613 /// Convert to a standard library error trait object.614 ///615 /// Unlike `self.into_boxed_dyn_error()`, this method relocates the616 /// underlying error into a new allocation in order to make it downcastable617 /// to `&E` or `Box<E>` for its original underlying error type. Any618 /// backtrace collected during construction of the `anyhow::Error` is619 /// discarded.620 ///621 /// ```622 #[cfg_attr(not(error_generic_member_access), doc = "# _ = stringify!{")]623 /// #![feature(error_generic_member_access)]624 ///625 /// use anyhow::anyhow;626 /// use std::backtrace::Backtrace;627 /// use thiserror::Error;628 ///629 /// #[derive(Error, Debug)]630 /// #[error("...")]631 /// struct MyError;632 ///633 /// let anyhow_error = anyhow!(MyError);634 /// println!("{}", anyhow_error.backtrace()); // has Backtrace635 /// assert!(anyhow_error.downcast_ref::<MyError>().is_some()); // can downcast636 ///637 /// let boxed_dyn_error = anyhow_error.reallocate_into_boxed_dyn_error_without_backtrace();638 /// assert!(std::error::request_ref::<Backtrace>(&*boxed_dyn_error).is_none()); // Backtrace lost639 /// assert!(boxed_dyn_error.downcast_ref::<MyError>().is_some()); // can downcast to &MyError640 /// assert!(boxed_dyn_error.downcast::<MyError>().is_ok()); // can downcast to Box<MyError>641 #[cfg_attr(not(error_generic_member_access), doc = "# };")]642 /// ```643 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]644 #[must_use]645 pub fn reallocate_into_boxed_dyn_error_without_backtrace(646 self,647 ) -> Box<dyn StdError + Send + Sync + 'static> {648 let outer = ManuallyDrop::new(self);649 unsafe {650 // Use vtable to attach E's native StdError vtable for the right651 // original type E.652 (vtable(outer.inner.ptr).object_reallocate_boxed)(outer.inner)653 }654 }655Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 656why, one step back656 #[cfg(error_generic_member_access)]Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15
lines 657–660why, one step back657 pub(crate) fn provide<'a>(&'a self, request: &mut Request<'a>) {658 unsafe { ErrorImpl::provide(self.inner.by_ref(), request) }659 }660Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 661–665why, one step back661 // Called by thiserror when you have `#[source] anyhow::Error`. This provide662 // implementation includes the anyhow::Error's Backtrace if any, unlike663 // deref'ing to dyn Error where the provide implementation would include664 // only the original error's Backtrace from before it got wrapped into an665 // anyhow::Error.Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 666why, one step back666 #[cfg(error_generic_member_access)]Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15
lines 667–669why, one step back667 #[doc(hidden)]668 pub fn thiserror_provide<'a>(&'a self, request: &mut Request<'a>) {669 Self::provide(self, request);Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 670–672why, one step back670 }671}672Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 673why, one step back673#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 674–680why, one step back674impl<E> From<E> for Error675where676 E: StdError + Send + Sync + 'static,677{678 #[cold]679 fn from(error: E) -> Self {680 let backtrace = backtrace_if_absent!(&error);Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc
line 681why, one step back681 Error::construct_from_std(error, backtrace)Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 682–684why, one step back682 }683}684Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 685why, one step back685#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 686–693why, one step back686impl Deref for Error {687 type Target = dyn StdError + Send + Sync + 'static;688689 fn deref(&self) -> &Self::Target {690 unsafe { ErrorImpl::error(self.inner.by_ref()) }691 }692}693Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 694why, one step back694#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 695–724why, one step back695impl DerefMut for Error {696 fn deref_mut(&mut self) -> &mut Self::Target {697 unsafe { ErrorImpl::error_mut(self.inner.by_mut()) }698 }699}700701impl Display for Error {702 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {703 unsafe { ErrorImpl::display(self.inner.by_ref(), formatter) }704 }705}706707impl Debug for Error {708 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {709 unsafe { ErrorImpl::debug(self.inner.by_ref(), formatter) }710 }711}712713impl Drop for Error {714 fn drop(&mut self) {715 unsafe {716 // Invoke the vtable's drop behavior.717 (vtable(self.inner.ptr).object_drop)(self.inner);718 }719 }720}721722struct ErrorVTable {723 object_drop: unsafe fn(Own<ErrorImpl>),724 object_ref: unsafe fn(Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>,Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 725why, one step back725 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 726why, one step back726 object_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2
lines 727–728why, one step back727 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]728 object_reallocate_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 729–730why, one step back729 object_downcast: unsafe fn(Ref<ErrorImpl>, TypeId) -> Option<Ref<()>>,730 object_drop_rest: unsafe fn(Own<ErrorImpl>, TypeId),Merge pull request #440 from dtolnay/backtraceDavid Tolnaybefore adoption9b67e5d
line 731why, one step back731 #[cfg(all(not(error_generic_member_access), feature = "std"))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 732–738why, one step back732 object_backtrace: unsafe fn(Ref<ErrorImpl>) -> Option<&Backtrace>,733}734735// Safety: requires layout of *e to match ErrorImpl<E>.736unsafe fn object_drop<E>(e: Own<ErrorImpl>) {737 // Cast back to ErrorImpl<E> so that the allocator receives the correct738 // Layout to deallocate the Box's memory.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 739–740why, one step back739 let unerased_own = e.cast::<ErrorImpl<E>>();740 drop(unsafe { unerased_own.boxed() });Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 741–748why, one step back741}742743// Safety: requires layout of *e to match ErrorImpl<E>.744unsafe fn object_drop_front<E>(e: Own<ErrorImpl>, target: TypeId) {745 // Drop the fields of ErrorImpl other than E as well as the Box allocation,746 // without dropping E itself. This is used by downcast after doing a747 // ptr::read to take ownership of the E.748 let _ = target;Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 749–750why, one step back749 let unerased_own = e.cast::<ErrorImpl<ManuallyDrop<E>>>();750 drop(unsafe { unerased_own.boxed() });Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 751–758why, one step back751}752753// Safety: requires layout of *e to match ErrorImpl<E>.754unsafe fn object_ref<E>(e: Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>755where756 E: StdError + Send + Sync + 'static,757{758 // Attach E's native StdError vtable onto a pointer to self._object.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 759why, one step back759 let unerased_ref = e.cast::<ErrorImpl<E>>();Merge pull request #435 from dtolnay/upDavid Tolnaybefore adoptionb86c3c8
line 760why, one step back760 Ref::from_raw(unsafe {Merge pull request #436 from dtolnay/upDavid Tolnaybefore adoption67df012
line 761why, one step back761 NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object).cast_mut())Merge pull request #435 from dtolnay/upDavid Tolnaybefore adoptionb86c3c8
line 762why, one step back762 })Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 763–765why, one step back763}764765// Safety: requires layout of *e to match ErrorImpl<E>.Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 766why, one step back766#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 767–771why, one step back767unsafe fn object_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>768where769 E: StdError + Send + Sync + 'static,770{771 // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 772–773why, one step back772 let unerased_own = e.cast::<ErrorImpl<E>>();773 unsafe { unerased_own.boxed() }Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 774–776why, one step back774}775776// Safety: requires layout of *e to match ErrorImpl<E>.Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2
lines 777–787why, one step back777#[cfg(any(feature = "std", not(anyhow_no_core_error)))]778unsafe fn object_reallocate_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>779where780 E: StdError + Send + Sync + 'static,781{782 // Attach E's native StdError vtable.783 let unerased_own = e.cast::<ErrorImpl<E>>();784 Box::new(unsafe { unerased_own.boxed() }._object)785}786787// Safety: requires layout of *e to match ErrorImpl<E>.Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 788–794why, one step back788unsafe fn object_downcast<E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>789where790 E: 'static,791{792 if TypeId::of::<E>() == target {793 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a794 // pointer to its E field.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 795why, one step back795 let unerased_ref = e.cast::<ErrorImpl<E>>();Merge pull request #435 from dtolnay/upDavid Tolnaybefore adoptionb86c3c8
line 796why, one step back796 Some(Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 797why, one step back797 Ref::from_raw(unsafe {Merge pull request #436 from dtolnay/upDavid Tolnaybefore adoption67df012
line 798why, one step back798 NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object).cast_mut())Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 799why, one step back799 })Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 800why, one step back800 .cast::<()>(),Merge pull request #435 from dtolnay/upDavid Tolnaybefore adoptionb86c3c8
line 801why, one step back801 )Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 802–806why, one step back802 } else {803 None804 }805}806Merge pull request #440 from dtolnay/backtraceDavid Tolnaybefore adoption9b67e5d
line 807why, one step back807#[cfg(all(not(error_generic_member_access), feature = "std"))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 808–813why, one step back808fn no_backtrace(e: Ref<ErrorImpl>) -> Option<&Backtrace> {809 let _ = e;810 None811}812813// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 814why, one step back814#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 815–820why, one step back815unsafe fn context_downcast<C, E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>816where817 C: 'static,818 E: 'static,819{820 if TypeId::of::<C>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 821why, one step back821 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();Merge pull request #452 from dtolnay/downcastDavid Tolnaybefore adoptione621bd3
lines 822–823why, one step back822 let inner = unsafe { ptr::addr_of!((*unerased_ref.as_ptr())._object.context) };823 Some(Ref::from_raw(unsafe { NonNull::new_unchecked(inner.cast_mut()) }).cast::<()>())Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 824why, one step back824 } else if TypeId::of::<E>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 825why, one step back825 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();Merge pull request #452 from dtolnay/downcastDavid Tolnaybefore adoptione621bd3
lines 826–827why, one step back826 let inner = unsafe { ptr::addr_of!((*unerased_ref.as_ptr())._object.error) };827 Some(Ref::from_raw(unsafe { NonNull::new_unchecked(inner.cast_mut()) }).cast::<()>())Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 828–833why, one step back828 } else {829 None830 }831}832833// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 834why, one step back834#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 835–842why, one step back835unsafe fn context_drop_rest<C, E>(e: Own<ErrorImpl>, target: TypeId)836where837 C: 'static,838 E: 'static,839{840 // Called after downcasting by value to either the C or the E and doing a841 // ptr::read to take ownership of that value.842 if TypeId::of::<C>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 843–844why, one step back843 let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>();844 drop(unsafe { unerased_own.boxed() });Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 845why, one step back845 } else {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 846–847why, one step back846 let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>();847 drop(unsafe { unerased_own.boxed() });Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 848–855why, one step back848 }849}850851// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.852unsafe fn context_chain_downcast<C>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>853where854 C: 'static,855{Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 856why, one step back856 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 857why, one step back857 if TypeId::of::<C>() == target {Merge pull request #452 from dtolnay/downcastDavid Tolnaybefore adoptione621bd3
lines 858–859why, one step back858 let inner = unsafe { ptr::addr_of!((*unerased_ref.as_ptr())._object.context) };859 Some(Ref::from_raw(unsafe { NonNull::new_unchecked(inner.cast_mut()) }).cast::<()>())Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 860–861why, one step back860 } else {861 // Recurse down the context chain per the inner error's vtable.Merge pull request #452 from dtolnay/downcastDavid Tolnaybefore adoptione621bd3
line 862why, one step back862 let unerased = unsafe { unerased_ref.deref() };Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 863why, one step back863 let source = &unerased._object.error;Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 864why, one step back864 unsafe { (vtable(source.inner.ptr).object_downcast)(source.inner.by_ref(), target) }Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 865–875why, one step back865 }866}867868// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.869unsafe fn context_chain_drop_rest<C>(e: Own<ErrorImpl>, target: TypeId)870where871 C: 'static,872{873 // Called after downcasting by value to either the C or one of the causes874 // and doing a ptr::read to take ownership of that value.875 if TypeId::of::<C>() == target {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 876why, one step back876 let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>();Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 877why, one step back877 // Drop the entire rest of the data structure rooted in the next Error.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 878why, one step back878 drop(unsafe { unerased_own.boxed() });Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 879why, one step back879 } else {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 880–881why, one step back880 let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>();881 let unerased = unsafe { unerased_own.boxed() };Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 882–884why, one step back882 // Read the Own<ErrorImpl> from the next error.883 let inner = unerased._object.error.inner;884 drop(unerased);Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 885why, one step back885 let vtable = unsafe { vtable(inner.ptr) };Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 886why, one step back886 // Recursively drop the next error using the same target typeid.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 887why, one step back887 unsafe { (vtable.object_drop_rest)(inner, target) };Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 888–891why, one step back888 }889}890891// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.Merge pull request #440 from dtolnay/backtraceDavid Tolnaybefore adoption9b67e5d
line 892why, one step back892#[cfg(all(not(error_generic_member_access), feature = "std"))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 893–897why, one step back893#[allow(clippy::unnecessary_wraps)]894unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>895where896 C: 'static,897{Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 898–900why, one step back898 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();899 let unerased = unsafe { unerased_ref.deref() };900 let backtrace = unsafe { ErrorImpl::backtrace(unerased._object.error.inner.by_ref()) };Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 901–919why, one step back901 Some(backtrace)902}903904// NOTE: If working with `ErrorImpl<()>`, references should be avoided in favor905// of raw pointers and `NonNull`.906// repr C to ensure that E remains in the final position.907#[repr(C)]908pub(crate) struct ErrorImpl<E = ()> {909 vtable: &'static ErrorVTable,910 backtrace: Option<Backtrace>,911 // NOTE: Don't use directly. Use only through vtable. Erased type may have912 // different alignment.913 _object: E,914}915916// Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but917// avoids converting `p` into a reference.918unsafe fn vtable(p: NonNull<ErrorImpl>) -> &'static ErrorVTable {919 // NOTE: This assumes that `ErrorVTable` is the first field of ErrorImpl.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 920why, one step back920 unsafe { *(p.as_ptr() as *const &'static ErrorVTable) }Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 921–943why, one step back921}922923// repr C to ensure that ContextError<C, E> has the same layout as924// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.925#[repr(C)]926pub(crate) struct ContextError<C, E> {927 pub context: C,928 pub error: E,929}930931impl<E> ErrorImpl<E> {932 fn erase(&self) -> Ref<ErrorImpl> {933 // Erase the concrete type of E but preserve the vtable in self.vtable934 // for manipulating the resulting thin pointer. This is analogous to an935 // unsize coercion.936 Ref::new(self).cast::<ErrorImpl>()937 }938}939940impl ErrorImpl {941 pub(crate) unsafe fn error(this: Ref<Self>) -> &(dyn StdError + Send + Sync + 'static) {942 // Use vtable to attach E's native StdError vtable for the right943 // original type E.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 944why, one step back944 unsafe { (vtable(this.ptr).object_ref)(this).deref() }Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 945–946why, one step back945 }946Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 947why, one step back947 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 948–950why, one step back948 pub(crate) unsafe fn error_mut(this: Mut<Self>) -> &mut (dyn StdError + Send + Sync + 'static) {949 // Use vtable to attach E's native StdError vtable for the right950 // original type E.Merge pull request #435 from dtolnay/upDavid Tolnaybefore adoptionb86c3c8
line 951why, one step back951 unsafe {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
lines 952–954why, one step back952 (vtable(this.ptr).object_ref)(this.by_ref())953 .by_mut()954 .deref_mut()Merge pull request #435 from dtolnay/upDavid Tolnaybefore adoptionb86c3c8
line 955why, one step back955 }Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 956–957why, one step back956 }957Merge pull request #440 from dtolnay/backtraceDavid Tolnaybefore adoption9b67e5d
line 958why, one step back958 #[cfg(feature = "std")]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 959–962why, one step back959 pub(crate) unsafe fn backtrace(this: Ref<Self>) -> &Backtrace {960 // This unwrap can only panic if the underlying error's backtrace method961 // is nondeterministic, which would only happen in maliciously962 // constructed code.Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 963why, one step back963 unsafe { this.deref() }Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 964–966why, one step back964 .backtrace965 .as_ref()966 .or_else(|| {Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 967why, one step back967 #[cfg(error_generic_member_access)]Merge pull request #414 from dtolnay/nightlyDavid Tolnaybefore adoption213a9c2
line 968why, one step back968 return nightly::request_ref_backtrace(unsafe { Self::error(this) });Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 969why, one step back969 #[cfg(not(error_generic_member_access))]Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 970why, one step back970 return unsafe { (vtable(this.ptr).object_backtrace)(this) };Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 971–974why, one step back971 })972 .expect("backtrace capture failed")973 }974Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 975why, one step back975 #[cfg(error_generic_member_access)]Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15
line 976why, one step back976 unsafe fn provide<'a>(this: Ref<'a, Self>, request: &mut Request<'a>) {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 977why, one step back977 if let Some(backtrace) = unsafe { &this.deref().backtrace } {Merge pull request #414 from dtolnay/nightlyDavid Tolnaybefore adoption213a9c2
line 978why, one step back978 nightly::provide_ref_backtrace(request, backtrace);Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 979why, one step back979 }Merge pull request #414 from dtolnay/nightlyDavid Tolnaybefore adoption213a9c2
line 980why, one step back980 nightly::provide(unsafe { Self::error(this) }, request);Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 981–984why, one step back981 }982983 #[cold]984 pub(crate) unsafe fn chain(this: Ref<Self>) -> Chain {Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49
line 985why, one step back985 Chain::new(unsafe { Self::error(this) })Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 986–996why, one step back986 }987}988989impl<E> StdError for ErrorImpl<E>990where991 E: StdError,992{993 fn source(&self) -> Option<&(dyn StdError + 'static)> {994 unsafe { ErrorImpl::error(self.erase()).source() }995 }996Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194
line 997why, one step back997 #[cfg(error_generic_member_access)]Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15
lines 998–999why, one step back998 fn provide<'a>(&'a self, request: &mut Request<'a>) {999 unsafe { ErrorImpl::provide(self.erase(), request) }Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 1000–1020why, one step back1000 }1001}10021003impl<E> Debug for ErrorImpl<E>1004where1005 E: Debug,1006{1007 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1008 unsafe { ErrorImpl::debug(self.erase(), formatter) }1009 }1010}10111012impl<E> Display for ErrorImpl<E>1013where1014 E: Display,1015{1016 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1017 unsafe { Display::fmt(ErrorImpl::error(self.erase()), formatter) }1018 }1019}1020Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 1021why, one step back1021#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 1022–1024why, one step back1022impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {1023 #[cold]1024 fn from(error: Error) -> Self {Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2
line 1025why, one step back1025 error.into_boxed_dyn_error()Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 1026–1028why, one step back1026 }1027}1028Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 1029why, one step back1029#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 1030why, one step back1030impl From<Error> for Box<dyn StdError + Send + 'static> {Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2
line 1031why, one step back1031 #[cold]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 1032why, one step back1032 fn from(error: Error) -> Self {Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2
line 1033why, one step back1033 error.into_boxed_dyn_error()Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 1034–1036why, one step back1034 }1035}1036Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd
line 1037why, one step back1037#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 1038why, one step back1038impl From<Error> for Box<dyn StdError + 'static> {Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2
line 1039why, one step back1039 #[cold]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
line 1040why, one step back1040 fn from(error: Error) -> Self {Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2
line 1041why, one step back1041 error.into_boxed_dyn_error()Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 1042–1044why, one step back1042 }1043}1044Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 1045why, one step back1045#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 1046–1051why, one step back1046impl AsRef<dyn StdError + Send + Sync> for Error {1047 fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {1048 &**self1049 }1050}1051Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf
line 1052why, one step back1052#[cfg(any(feature = "std", not(anyhow_no_core_error)))]Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 1053–1057why, one step back1053impl AsRef<dyn StdError> for Error {1054 fn as_ref(&self) -> &(dyn StdError + 'static) {1055 &**self1056 }1057}Merge pull request #386 from dtolnay/unwindsafeDavid Tolnaybefore adoption830c399
lines 1058–1060why, one step back10581059impl UnwindSafe for Error {}1060impl RefUnwindSafe for Error {}