error.rs
This file
Path
src/error.rs
800 lines · 26.9 KiB · Rust
Last changed by
Fix typo coersion -> coercionDavid Tolnaybefore adoptionfd0268b
History of this fileTake it
The walk stopped after 200 commits: lines older than 3adc96a point at it.
Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 1why, one step back1use crate::alloc::Box;Move backtrace capture to backtrace module and macroDavid Tolnaybefore adoptionebd9101
line 2why, one step back2use crate::backtrace::Backtrace;Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
lines 3–8why, one step back3use crate::chain::Chain;4use crate::{Error, StdError};5use core::any::TypeId;6use core::fmt::{self, Debug, Display};7use core::mem::{self, ManuallyDrop};8use core::ptr::{self, NonNull};Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
line 9why, one step back9Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
lines 10–12why, one step back10#[cfg(feature = "std")]11use core::ops::{Deref, DerefMut};12Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 13–20why, one step back13impl Error {14 /// Create a new error object from any error type.15 ///16 /// The error type must be threadsafe and `'static`, so that the `Error`17 /// will be as well.18 ///19 /// If the error type does not provide a backtrace, a backtrace will be20 /// created here to ensure that a backtrace exists.Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 21why, one step back21 #[cfg(feature = "std")]Merge pull request #78 from dtolnay/cfgDavid Tolnaybefore adoptione2eb1f5
line 22why, one step back22 #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 23–26why, one step back23 pub fn new<E>(error: E) -> Self24 where25 E: StdError + Send + Sync + 'static,26 {Move Error::new backtrace capture to backtrace_if_absent macroDavid Tolnaybefore adoptioneaa819d
line 27why, one step back27 let backtrace = backtrace_if_absent!(error);Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9
lines 28–29why, one step back28 Error::from_std(error, backtrace)29 }Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298
line 30why, one step back30Add Error::msg constructor to simplify map_err combinatorsDavid Tolnaybefore adoption04b11c5
lines 31–74why, one step back31 /// Create a new error object from a printable error message.32 ///33 /// If the argument implements std::error::Error, prefer `Error::new`34 /// instead which preserves the underlying error's cause chain and35 /// backtrace. If the argument may or may not implement std::error::Error36 /// now or in the future, use `anyhow!(err)` which handles either way37 /// correctly.38 ///39 /// `Error::msg("...")` is equivalent to `anyhow!("...")` but occasionally40 /// convenient in places where a function is preferable over a macro, such41 /// as iterator or stream combinators:42 ///43 /// ```44 /// # mod ffi {45 /// # pub struct Input;46 /// # pub struct Output;47 /// # pub async fn do_some_work(_: Input) -> Result<Output, &'static str> {48 /// # unimplemented!()49 /// # }50 /// # }51 /// #52 /// # use ffi::{Input, Output};53 /// #54 /// use anyhow::{Error, Result};55 /// use futures::stream::{Stream, StreamExt, TryStreamExt};56 ///57 /// async fn demo<S>(stream: S) -> Result<Vec<Output>>58 /// where59 /// S: Stream<Item = Input>,60 /// {61 /// stream62 /// .then(ffi::do_some_work) // returns Result<Output, &str>63 /// .map_err(Error::msg)64 /// .try_collect()65 /// .await66 /// }67 /// ```68 pub fn msg<M>(message: M) -> Self69 where70 M: Display + Debug + Send + Sync + 'static,71 {72 Error::from_adhoc(message, backtrace!())73 }74Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 75why, one step back75 #[cfg(feature = "std")]Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9
lines 76–79why, one step back76 pub(crate) fn from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self77 where78 E: StdError + Send + Sync + 'static,79 {Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93
lines 80–84why, one step back80 let vtable = &ErrorVTable {81 object_drop: object_drop::<E>,82 object_ref: object_ref::<E>,83 object_mut: object_mut::<E>,84 object_boxed: object_boxed::<E>,Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 85–86why, one step back85 object_downcast: object_downcast::<E>,86 object_drop_rest: object_drop_front::<E>,Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93
line 87why, one step back87 };Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9
line 88why, one step back88Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93
lines 89–90why, one step back89 // Safety: passing vtable that operates on the right type E.90 unsafe { Error::construct(error, vtable, backtrace) }Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 91–92why, one step back91 }92Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9
line 93why, one step back93 pub(crate) fn from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> SelfShrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 94–96why, one step back94 where95 M: Display + Debug + Send + Sync + 'static,96 {Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 97why, one step back97 use crate::wrapper::MessageError;Specify types where the manual vtable relies on themDavid Tolnaybefore adoptionb261a64
line 98why, one step back98 let error: MessageError<M> = MessageError(message);Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93
lines 99–101why, one step back99 let vtable = &ErrorVTable {100 object_drop: object_drop::<MessageError<M>>,101 object_ref: object_ref::<MessageError<M>>,Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 102why, one step back102 #[cfg(feature = "std")]Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93
lines 103–104why, one step back103 object_mut: object_mut::<MessageError<M>>,104 object_boxed: object_boxed::<MessageError<M>>,Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 105–106why, one step back105 object_downcast: object_downcast::<M>,106 object_drop_rest: object_drop_front::<M>,Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93
line 107why, one step back107 };Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298
line 108why, one step back108Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93
lines 109–111why, one step back109 // Safety: MessageError is repr(transparent) so it is okay for the110 // vtable to allow casting the MessageError<M> to M.111 unsafe { Error::construct(error, vtable, backtrace) }Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 112–113why, one step back112 }113Merge pull request #8 from dtolnay/optionDavid Tolnaybefore adoption240cc83
lines 114–117why, one step back114 pub(crate) fn from_display<M>(message: M, backtrace: Option<Backtrace>) -> Self115 where116 M: Display + Send + Sync + 'static,117 {Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 118why, one step back118 use crate::wrapper::DisplayError;Specify types where the manual vtable relies on themDavid Tolnaybefore adoptionb261a64
line 119why, one step back119 let error: DisplayError<M> = DisplayError(message);Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93
lines 120–122why, one step back120 let vtable = &ErrorVTable {121 object_drop: object_drop::<DisplayError<M>>,122 object_ref: object_ref::<DisplayError<M>>,Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 123why, one step back123 #[cfg(feature = "std")]Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93
lines 124–125why, one step back124 object_mut: object_mut::<DisplayError<M>>,125 object_boxed: object_boxed::<DisplayError<M>>,Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 126–127why, one step back126 object_downcast: object_downcast::<M>,127 object_drop_rest: object_drop_front::<M>,Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93
line 128why, one step back128 };Merge pull request #8 from dtolnay/optionDavid Tolnaybefore adoption240cc83
line 129why, one step back129Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93
lines 130–132why, one step back130 // Safety: DisplayError is repr(transparent) so it is okay for the131 // vtable to allow casting the DisplayError<M> to M.132 unsafe { Error::construct(error, vtable, backtrace) }Merge pull request #8 from dtolnay/optionDavid Tolnaybefore adoption240cc83
lines 133–134why, one step back133 }134Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 135why, one step back135 #[cfg(feature = "std")]Expand ContextError vtable to prepare for extending downcast supportDavid Tolnaybefore adoption45e6fc6
line 136why, one step back136 pub(crate) fn from_context<C, E>(context: C, error: E, backtrace: Option<Backtrace>) -> SelfMove ContextError to error.rs in preparation for refactorDavid Tolnaybefore adoption30c2eab
lines 137–140why, one step back137 where138 C: Display + Send + Sync + 'static,139 E: StdError + Send + Sync + 'static,140 {Expand ContextError vtable to prepare for extending downcast supportDavid Tolnaybefore adoption45e6fc6
lines 141–147why, one step back141 let error: ContextError<C, E> = ContextError { context, error };142143 let vtable = &ErrorVTable {144 object_drop: object_drop::<ContextError<C, E>>,145 object_ref: object_ref::<ContextError<C, E>>,146 object_mut: object_mut::<ContextError<C, E>>,147 object_boxed: object_boxed::<ContextError<C, E>>,Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 148–149why, one step back148 object_downcast: context_downcast::<C, E>,149 object_drop_rest: context_drop_rest::<C, E>,Expand ContextError vtable to prepare for extending downcast supportDavid Tolnaybefore adoption45e6fc6
lines 150–152why, one step back150 };151152 // Safety: passing vtable that operates on the right type.Merge pull request #50 from dtolnay/boxedDavid Tolnaybefore adoption74fbea6
lines 153–155why, one step back153 unsafe { Error::construct(error, vtable, backtrace) }154 }155Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 156why, one step back156 #[cfg(feature = "std")]Merge pull request #50 from dtolnay/boxedDavid Tolnaybefore adoption74fbea6
lines 157–160why, one step back157 pub(crate) fn from_boxed(158 error: Box<dyn StdError + Send + Sync>,159 backtrace: Option<Backtrace>,160 ) -> Self {Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 161why, one step back161 use crate::wrapper::BoxedError;Merge pull request #50 from dtolnay/boxedDavid Tolnaybefore adoption74fbea6
lines 162–173why, one step back162 let error = BoxedError(error);163 let vtable = &ErrorVTable {164 object_drop: object_drop::<BoxedError>,165 object_ref: object_ref::<BoxedError>,166 object_mut: object_mut::<BoxedError>,167 object_boxed: object_boxed::<BoxedError>,168 object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,169 object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,170 };171172 // Safety: BoxedError is repr(transparent) so it is okay for the vtable173 // to allow casting to Box<dyn StdError + Send + Sync>.Expand ContextError vtable to prepare for extending downcast supportDavid Tolnaybefore adoption45e6fc6
line 174why, one step back174 unsafe { Error::construct(error, vtable, backtrace) }Move ContextError to error.rs in preparation for refactorDavid Tolnaybefore adoption30c2eab
lines 175–176why, one step back175 }176Move Error::new backtrace capture to backtrace_if_absent macroDavid Tolnaybefore adoptioneaa819d
lines 177–178why, one step back177 // Takes backtrace as argument rather than capturing it here so that the178 // user sees one fewer layer of wrapping noise in the backtrace.Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298
line 179why, one step back179 //Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93
lines 180–186why, one step back180 // Unsafe because the given vtable must have sensible behavior on the error181 // value of type E.182 unsafe fn construct<E>(183 error: E,184 vtable: &'static ErrorVTable,185 backtrace: Option<Backtrace>,186 ) -> SelfShrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 187–189why, one step back187 where188 E: StdError + Send + Sync + 'static,189 {Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298
lines 190–192why, one step back190 let inner = Box::new(ErrorImpl {191 vtable,192 backtrace,Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
line 193why, one step back193 _object: error,Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298
line 194why, one step back194 });Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
line 195why, one step back195 // Erase the concrete type of E from the compile-time type system. ThisFix typo coersion -> coercionDavid Tolnaybefore adoptionfd0268b
line 196why, one step back196 // is equivalent to the safe unsize coercion from Box<ErrorImpl<E>> toFill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
lines 197–200why, one step back197 // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the198 // result is a thin pointer. The necessary behavior for manipulating the199 // underlying ErrorImpl<E> is preserved in the vtable provided by the200 // caller rather than a builtin fat pointer vtable.Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f
lines 201–203why, one step back201 let erased = mem::transmute::<Box<ErrorImpl<E>>, Box<ErrorImpl<()>>>(inner);202 let inner = ManuallyDrop::new(erased);203 Error { inner }Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 204–206why, one step back204 }205206 /// Wrap the error value with additional context.Link to Context trait from Error::context methodDavid Tolnaybefore adoption61e587f
lines 207–210why, one step back207 ///208 /// For attaching context to a `Result` as it is propagated, the209 /// [`Context`][crate::Context] extension trait may be more convenient than210 /// this function.Explain the purpose of Error::contextDavid Tolnaybefore adoption896dd7a
lines 211–232why, one step back211 ///212 /// The primary reason to use `error.context(...)` instead of213 /// `result.context(...)` via the `Context` trait would be if the context214 /// needs to depend on some data held by the underlying error:215 ///216 /// ```217 /// # use std::fmt::{self, Debug, Display};218 /// #219 /// # type T = ();220 /// #221 /// # impl std::error::Error for ParseError {}222 /// # impl Debug for ParseError {223 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {224 /// # unimplemented!()225 /// # }226 /// # }227 /// # impl Display for ParseError {228 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {229 /// # unimplemented!()230 /// # }231 /// # }232 /// #Clean up Error::context example using anyhow ResultDavid Tolnaybefore adoptionf8457fb
line 233why, one step back233 /// use anyhow::Result;Explain the purpose of Error::contextDavid Tolnaybefore adoption896dd7a
lines 234–248why, one step back234 /// use std::fs::File;235 /// use std::path::Path;236 ///237 /// struct ParseError {238 /// line: usize,239 /// column: usize,240 /// }241 ///242 /// fn parse_impl(file: File) -> Result<T, ParseError> {243 /// # const IGNORE: &str = stringify! {244 /// ...245 /// # };246 /// # unimplemented!()247 /// }248 ///Clean up Error::context example using anyhow ResultDavid Tolnaybefore adoptionf8457fb
line 249why, one step back249 /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {Explain the purpose of Error::contextDavid Tolnaybefore adoption896dd7a
lines 250–259why, one step back250 /// let file = File::open(&path)?;251 /// parse_impl(file).map_err(|error| {252 /// let context = format!(253 /// "only the first {} lines of {} are valid",254 /// error.line, path.as_ref().display(),255 /// );256 /// anyhow::Error::new(error).context(context)257 /// })258 /// }259 /// ```Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 260–263why, one step back260 pub fn context<C>(self, context: C) -> Self261 where262 C: Display + Send + Sync + 'static,263 {Specify types where the manual vtable relies on themDavid Tolnaybefore adoptionb261a64
line 264why, one step back264 let error: ContextError<C, Error> = ContextError {Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
line 265why, one step back265 context,Swap ContextError type parameters to match type nameDavid Tolnaybefore adoption9f38495
line 266why, one step back266 error: self,Eliminate backtrace_if_absent in Error::contextDavid Tolnaybefore adoptiona2846fd
lines 267–271why, one step back267 };268269 let vtable = &ErrorVTable {270 object_drop: object_drop::<ContextError<C, Error>>,271 object_ref: object_ref::<ContextError<C, Error>>,Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 272why, one step back272 #[cfg(feature = "std")]Eliminate backtrace_if_absent in Error::contextDavid Tolnaybefore adoptiona2846fd
lines 273–274why, one step back273 object_mut: object_mut::<ContextError<C, Error>>,274 object_boxed: object_boxed::<ContextError<C, Error>>,Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 275–276why, one step back275 object_downcast: context_chain_downcast::<C>,276 object_drop_rest: context_chain_drop_rest::<C>,Eliminate backtrace_if_absent in Error::contextDavid Tolnaybefore adoptiona2846fd
lines 277–283why, one step back277 };278279 // As the cause is anyhow::Error, we already have a backtrace for it.280 let backtrace = None;281282 // Safety: passing vtable that operates on the right type.283 unsafe { Error::construct(error, vtable, backtrace) }Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 284–286why, one step back284 }285286 /// Get the backtrace for this Error.Detect nightly and only expose backtrace if availableDavid Tolnaybefore adoption270ea5e
lines 287–290why, one step back287 ///288 /// Backtraces are only available on the nightly channel. Tracking issue:289 /// [rust-lang/rust#53487][tracking].290 ///Merge pull request #70 from dtolnay/envDavid Tolnaybefore adoption8d2acea
lines 291–293why, one step back291 /// In order for the backtrace to be meaningful, one of the two environment292 /// variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined293 /// and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhatMention env var in Error::backtrace documentationDavid Tolnaybefore adoption4119806
lines 294–295why, one step back294 /// expensive to capture in Rust, so we don't necessarily want to be295 /// capturing them all over the place all the time.Merge pull request #70 from dtolnay/envDavid Tolnaybefore adoption8d2acea
lines 296–302why, one step back296 ///297 /// - If you want panics and errors to both have backtraces, set298 /// `RUST_BACKTRACE=1`;299 /// - If you want only errors to have backtraces, set300 /// `RUST_LIB_BACKTRACE=1`;301 /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and302 /// `RUST_LIB_BACKTRACE=0`.Mention env var in Error::backtrace documentationDavid Tolnaybefore adoption4119806
line 303why, one step back303 ///Detect nightly and only expose backtrace if availableDavid Tolnaybefore adoption270ea5e
lines 304–305why, one step back304 /// [tracking]: https://github.com/rust-lang/rust/issues/53487305 #[cfg(backtrace)]Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
line 306why, one step back306 pub fn backtrace(&self) -> &Backtrace {Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
line 307why, one step back307 self.inner.backtrace()Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 308–314why, one step back308 }309310 /// An iterator of the chain of source errors contained by this Error.311 ///312 /// This iterator will visit every error in the cause chain of this error313 /// object, beginning with the error that this error object was created314 /// from.Add example of Error::chainDavid Tolnaybefore adoptiond159b79
lines 315–330why, one step back315 ///316 /// # Example317 ///318 /// ```319 /// use anyhow::Error;320 /// use std::io;321 ///322 /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {323 /// for cause in error.chain() {324 /// if let Some(io_error) = cause.downcast_ref::<io::Error>() {325 /// return Some(io_error.kind());326 /// }327 /// }328 /// None329 /// }330 /// ```Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 331why, one step back331 #[cfg(feature = "std")]Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
line 332why, one step back332 pub fn chain(&self) -> Chain {Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
line 333why, one step back333 self.inner.chain()Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 334–335why, one step back334 }335Add Error::root_cause accessorDavid Tolnaybefore adoption1ea72bb
lines 336–340why, one step back336 /// The lowest level cause of this error — this error's cause's337 /// cause's cause etc.338 ///339 /// The root cause is the last error in the iterator produced by340 /// [`chain()`][Error::chain].Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 341why, one step back341 #[cfg(feature = "std")]Add Error::root_cause accessorDavid Tolnaybefore adoption1ea72bb
line 342why, one step back342 pub fn root_cause(&self) -> &(dyn StdError + 'static) {Merge pull request #108 from hbina/patch-1David Tolnaybefore adoption7954754
line 343why, one step back343 self.chain().last().unwrap()Add Error::root_cause accessorDavid Tolnaybefore adoption1ea72bb
lines 344–345why, one step back344 }345Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 346–353why, one step back346 /// Returns true if `E` is the type held by this error object.347 ///348 /// For errors with context, this method returns true if `E` matches the349 /// type of the context `C` **or** the type of the error on which the350 /// context has been attached. For details about the interaction between351 /// context and downcasting, [see here].352 ///353 /// [see here]: trait.Context.html#effect-on-downcastingShrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 354–357why, one step back354 pub fn is<E>(&self) -> bool355 where356 E: Display + Debug + Send + Sync + 'static,357 {Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
line 358why, one step back358 self.downcast_ref::<E>().is_some()Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 359–365why, one step back359 }360361 /// Attempt to downcast the error object to a concrete type.362 pub fn downcast<E>(self) -> Result<E, Self>363 where364 E: Display + Debug + Send + Sync + 'static,365 {Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 366–367why, one step back366 let target = TypeId::of::<E>();367 unsafe {Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
lines 368–369why, one step back368 // Use vtable to find NonNull<()> which points to a value of type E369 // somewhere inside the data structure.Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 370–373why, one step back370 let addr = match (self.inner.vtable.object_downcast)(&self.inner, target) {371 Some(addr) => addr,372 None => return Err(self),373 };Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
lines 374–376why, one step back374375 // Prepare to read E out of the data structure. We'll drop the rest376 // of the data structure separately so that E is not dropped.Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608
line 377why, one step back377 let outer = ManuallyDrop::new(self);Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
lines 378–379why, one step back378379 // Read E from where the vtable found it.Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
line 380why, one step back380 let error = ptr::read(addr.cast::<E>().as_ptr());Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
lines 381–383why, one step back381382 // Read Box<ErrorImpl<()>> from self. Can't move it out because383 // Error has a Drop impl which we want to not run.Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 384–385why, one step back384 let inner = ptr::read(&outer.inner);385 let erased = ManuallyDrop::into_inner(inner);Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
lines 386–387why, one step back386387 // Drop rest of the data structure outside of E.Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
line 388why, one step back388 (erased.vtable.object_drop_rest)(erased, target);Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
line 389why, one step back389Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
line 390why, one step back390 Ok(error)Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 391–394why, one step back391 }392 }393394 /// Downcast this error object by reference.Add example to Error::downcast_refDavid Tolnaybefore adoption0c21b7a
lines 395–429why, one step back395 ///396 /// # Example397 ///398 /// ```399 /// # use anyhow::anyhow;400 /// # use std::fmt::{self, Display};401 /// # use std::task::Poll;402 /// #403 /// # #[derive(Debug)]404 /// # enum DataStoreError {405 /// # Censored(()),406 /// # }407 /// #408 /// # impl Display for DataStoreError {409 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {410 /// # unimplemented!()411 /// # }412 /// # }413 /// #414 /// # impl std::error::Error for DataStoreError {}415 /// #416 /// # const REDACTED_CONTENT: () = ();417 /// #418 /// # let error = anyhow!("...");419 /// # let root_cause = &error;420 /// #421 /// # let ret =422 /// // If the error was caused by redaction, then return a tombstone instead423 /// // of the content.424 /// match root_cause.downcast_ref::<DataStoreError>() {425 /// Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),426 /// None => Err(error),427 /// }428 /// # ;429 /// ```Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 430–433why, one step back430 pub fn downcast_ref<E>(&self) -> Option<&E>431 where432 E: Display + Debug + Send + Sync + 'static,433 {Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 434–435why, one step back434 let target = TypeId::of::<E>();435 unsafe {Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
lines 436–437why, one step back436 // Use vtable to find NonNull<()> which points to a value of type E437 // somewhere inside the data structure.Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 438–439why, one step back438 let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;439 Some(&*addr.cast::<E>().as_ptr())Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 440–447why, one step back440 }441 }442443 /// Downcast this error object by mutable reference.444 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>445 where446 E: Display + Debug + Send + Sync + 'static,447 {Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 448–449why, one step back448 let target = TypeId::of::<E>();449 unsafe {Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
lines 450–451why, one step back450 // Use vtable to find NonNull<()> which points to a value of type E451 // somewhere inside the data structure.Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 452–453why, one step back452 let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;453 Some(&mut *addr.cast::<E>().as_ptr())Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 454–456why, one step back454 }455 }456}Remove use of attributes on function parametersDavid Tolnaybefore adoptiona2d7e2f
line 457why, one step back457Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 458why, one step back458#[cfg(feature = "std")]Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 459–463why, one step back459impl<E> From<E> for Error460where461 E: StdError + Send + Sync + 'static,462{463 fn from(error: E) -> Self {Capture backtraces earlierDavid Tolnaybefore adoptionc06155e
lines 464–465why, one step back464 let backtrace = backtrace_if_absent!(error);465 Error::from_std(error, backtrace)Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 466–468why, one step back466 }467}468Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 469why, one step back469#[cfg(feature = "std")]Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 470–471why, one step back470impl Deref for Error {471 type Target = dyn StdError + Send + Sync + 'static;Remove as_dyn_error methods from ErrorDavid Tolnaybefore adoption73c7283
line 472why, one step back472Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 473–477why, one step back473 fn deref(&self) -> &Self::Target {474 self.inner.error()475 }476}477Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 478why, one step back478#[cfg(feature = "std")]Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 479–484why, one step back479impl DerefMut for Error {480 fn deref_mut(&mut self) -> &mut Self::Target {481 self.inner.error_mut()482 }483}484Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd
line 485why, one step back485impl Display for Error {Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
line 486why, one step back486 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd
line 487why, one step back487 self.inner.display(formatter)Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 488–490why, one step back488 }489}490Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd
lines 491–493why, one step back491impl Debug for Error {492 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {493 self.inner.debug(formatter)Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 494–498why, one step back494 }495}496497impl Drop for Error {498 fn drop(&mut self) {Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f
line 499why, one step back499 unsafe {Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
line 500why, one step back500 // Read Box<ErrorImpl<()>> from self.Ptr read only needs a const ptrDavid Tolnaybefore adoption83f63a6
line 501why, one step back501 let inner = ptr::read(&self.inner);Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f
line 502why, one step back502 let erased = ManuallyDrop::into_inner(inner);Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
lines 503–504why, one step back503504 // Invoke the vtable's drop behavior.Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f
lines 505–506why, one step back505 (erased.vtable.object_drop)(erased);506 }Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 507–509why, one step back507 }508}509Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a
line 510why, one step back510struct ErrorVTable {Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f
line 511why, one step back511 object_drop: unsafe fn(Box<ErrorImpl<()>>),Rename vtable object ref and mut methods that are no longer raw ptrDavid Tolnaybefore adoptiond57f80c
line 512why, one step back512 object_ref: unsafe fn(&ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static),Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 513why, one step back513 #[cfg(feature = "std")]Rename vtable object ref and mut methods that are no longer raw ptrDavid Tolnaybefore adoptiond57f80c
line 514why, one step back514 object_mut: unsafe fn(&mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static),Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
line 515why, one step back515 object_boxed: unsafe fn(Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>,Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 516–517why, one step back516 object_downcast: unsafe fn(&ErrorImpl<()>, TypeId) -> Option<NonNull<()>>,517 object_drop_rest: unsafe fn(Box<ErrorImpl<()>>, TypeId),Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f
lines 518–519why, one step back518}519Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
line 520why, one step back520// Safety: requires layout of *e to match ErrorImpl<E>.Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f
lines 521–524why, one step back521unsafe fn object_drop<E>(e: Box<ErrorImpl<()>>) {522 // Cast back to ErrorImpl<E> so that the allocator receives the correct523 // Layout to deallocate the Box's memory.524 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e);Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608
lines 525–527why, one step back525 drop(unerased);526}527Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
line 528why, one step back528// Safety: requires layout of *e to match ErrorImpl<E>.Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
line 529why, one step back529unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>, target: TypeId) {Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608
lines 530–532why, one step back530 // Drop the fields of ErrorImpl other than E as well as the Box allocation,531 // without dropping E itself. This is used by downcast after doing a532 // ptr::read to take ownership of the E.Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
line 533why, one step back533 let _ = target;Deallocate with the right Layout during downcastDavid Tolnaybefore adoption22c2608
line 534why, one step back534 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<ManuallyDrop<E>>>>(e);Deallocate ErrorImpl with the right LayoutDavid Tolnaybefore adoption6b25b2f
line 535why, one step back535 drop(unerased);Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a
lines 536–537why, one step back536}537Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
line 538why, one step back538// Safety: requires layout of *e to match ErrorImpl<E>.Rename vtable object ref and mut methods that are no longer raw ptrDavid Tolnaybefore adoptiond57f80c
line 539why, one step back539unsafe fn object_ref<E>(e: &ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static)Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a
lines 540–542why, one step back540where541 E: StdError + Send + Sync + 'static,542{Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
line 543why, one step back543 // Attach E's native StdError vtable onto a pointer to self._object.Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
line 544why, one step back544 &(*(e as *const ErrorImpl<()> as *const ErrorImpl<E>))._objectMerge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a
lines 545–546why, one step back545}546Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
line 547why, one step back547// Safety: requires layout of *e to match ErrorImpl<E>.Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 548why, one step back548#[cfg(feature = "std")]Rename vtable object ref and mut methods that are no longer raw ptrDavid Tolnaybefore adoptiond57f80c
line 549why, one step back549unsafe fn object_mut<E>(e: &mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static)Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a
lines 550–552why, one step back550where551 E: StdError + Send + Sync + 'static,552{Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
line 553why, one step back553 // Attach E's native StdError vtable onto a pointer to self._object.Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
line 554why, one step back554 &mut (*(e as *mut ErrorImpl<()> as *mut ErrorImpl<E>))._objectMerge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a
lines 555–556why, one step back555}556Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
line 557why, one step back557// Safety: requires layout of *e to match ErrorImpl<E>.Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
lines 558–561why, one step back558unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>559where560 E: StdError + Send + Sync + 'static,561{Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
line 562why, one step back562 // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
lines 563–565why, one step back563 mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e)564}565Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
line 566why, one step back566// Safety: requires layout of *e to match ErrorImpl<E>.Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
line 567why, one step back567unsafe fn object_downcast<E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93
line 568why, one step back568whereMerge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
line 569why, one step back569 E: 'static,Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93
line 570why, one step back570{Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
line 571why, one step back571 if TypeId::of::<E>() == target {Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
lines 572–573why, one step back572 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a573 // pointer to its E field.Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 574–579why, one step back574 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<E>;575 let addr = &(*unerased)._object as *const E as *mut ();576 Some(NonNull::new_unchecked(addr))577 } else {578 None579 }Merge pull request #33 from dtolnay/typeidDavid Tolnaybefore adoption8885e93
lines 580–581why, one step back580}581Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
line 582why, one step back582// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 583why, one step back583#[cfg(feature = "std")]Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 584–601why, one step back584unsafe fn context_downcast<C, E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>585where586 C: 'static,587 E: 'static,588{589 if TypeId::of::<C>() == target {590 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;591 let addr = &(*unerased)._object.context as *const C as *mut ();592 Some(NonNull::new_unchecked(addr))593 } else if TypeId::of::<E>() == target {594 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;595 let addr = &(*unerased)._object.error as *const E as *mut ();596 Some(NonNull::new_unchecked(addr))597 } else {598 None599 }600}601Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
line 602why, one step back602// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 603why, one step back603#[cfg(feature = "std")]Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 604–625why, one step back604unsafe fn context_drop_rest<C, E>(e: Box<ErrorImpl<()>>, target: TypeId)605where606 C: 'static,607 E: 'static,608{609 // Called after downcasting by value to either the C or the E and doing a610 // ptr::read to take ownership of that value.611 if TypeId::of::<C>() == target {612 let unerased = mem::transmute::<613 Box<ErrorImpl<()>>,614 Box<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>,615 >(e);616 drop(unerased);617 } else {618 let unerased = mem::transmute::<619 Box<ErrorImpl<()>>,620 Box<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>,621 >(e);622 drop(unerased);623 }624}625Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
line 626why, one step back626// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 627–635why, one step back627unsafe fn context_chain_downcast<C>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>628where629 C: 'static,630{631 if TypeId::of::<C>() == target {632 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;633 let addr = &(*unerased)._object.context as *const C as *mut ();634 Some(NonNull::new_unchecked(addr))635 } else {Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
line 636why, one step back636 // Recurse down the context chain per the inner error's vtable.Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 637–642why, one step back637 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;638 let source = &(*unerased)._object.error;639 (source.inner.vtable.object_downcast)(&source.inner, target)640 }641}642Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
line 643why, one step back643// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 644–654why, one step back644unsafe fn context_chain_drop_rest<C>(e: Box<ErrorImpl<()>>, target: TypeId)645where646 C: 'static,647{648 // Called after downcasting by value to either the C or one of the causes649 // and doing a ptr::read to take ownership of that value.650 if TypeId::of::<C>() == target {651 let unerased = mem::transmute::<652 Box<ErrorImpl<()>>,653 Box<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>,654 >(e);Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
line 655why, one step back655 // Drop the entire rest of the data structure rooted in the next Error.Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 656–661why, one step back656 drop(unerased);657 } else {658 let unerased = mem::transmute::<659 Box<ErrorImpl<()>>,660 Box<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>,661 >(e);Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
line 662why, one step back662 // Read out a ManuallyDrop<Box<ErrorImpl<()>>> from the next error.Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 663–665why, one step back663 let inner = ptr::read(&unerased._object.error.inner);664 drop(unerased);665 let erased = ManuallyDrop::into_inner(inner);Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
line 666why, one step back666 // Recursively drop the next error using the same target typeid.Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 667–671why, one step back667 (erased.vtable.object_drop_rest)(erased, target);668 }669}670671// repr C to ensure that E remains in the final position.Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
line 672why, one step back672#[repr(C)]Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4
line 673why, one step back673pub(crate) struct ErrorImpl<E> {Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a
line 674why, one step back674 vtable: &'static ErrorVTable,Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
line 675why, one step back675 backtrace: Option<Backtrace>,Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 676–678why, one step back676 // NOTE: Don't use directly. Use only through vtable. Erased type may have677 // different alignment.678 _object: E,Move ContextError to error.rs in preparation for refactorDavid Tolnaybefore adoption30c2eab
lines 679–680why, one step back679}680Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0
lines 681–683why, one step back681// repr C to ensure that ContextError<C, E> has the same layout as682// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.683#[repr(C)]Move ContextError to error.rs in preparation for refactorDavid Tolnaybefore adoption30c2eab
lines 684–686why, one step back684pub(crate) struct ContextError<C, E> {685 pub context: C,686 pub error: E,Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 687–688why, one step back687}688Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452
lines 689–690why, one step back689impl<E> ErrorImpl<E> {690 fn erase(&self) -> &ErrorImpl<()> {Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
lines 691–692why, one step back691 // Erase the concrete type of E but preserve the vtable in self.vtable692 // for manipulating the resulting thin pointer. This is analogous to anFix typo coersion -> coercionDavid Tolnaybefore adoptionfd0268b
line 693why, one step back693 // unsize coercion.Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452
lines 694–697why, one step back694 unsafe { &*(self as *const ErrorImpl<E> as *const ErrorImpl<()>) }695 }696}697Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
line 698why, one step back698impl ErrorImpl<()> {Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd
line 699why, one step back699 pub(crate) fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
lines 700–701why, one step back700 // Use vtable to attach E's native StdError vtable for the right701 // original type E.Rename vtable object ref and mut methods that are no longer raw ptrDavid Tolnaybefore adoptiond57f80c
line 702why, one step back702 unsafe { &*(self.vtable.object_ref)(self) }Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 703–704why, one step back703 }704Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 705why, one step back705 #[cfg(feature = "std")]Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd
line 706why, one step back706 pub(crate) fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
lines 707–708why, one step back707 // Use vtable to attach E's native StdError vtable for the right708 // original type E.Rename vtable object ref and mut methods that are no longer raw ptrDavid Tolnaybefore adoptiond57f80c
line 709why, one step back709 unsafe { &mut *(self.vtable.object_mut)(self) }Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
lines 710–712why, one step back710 }711712 #[cfg(backtrace)]Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd
line 713why, one step back713 pub(crate) fn backtrace(&self) -> &Backtrace {Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
lines 714–722why, one step back714 // This unwrap can only panic if the underlying error's backtrace method715 // is nondeterministic, which would only happen in maliciously716 // constructed code.717 self.backtrace718 .as_ref()719 .or_else(|| self.error().backtrace())720 .expect("backtrace capture failed")721 }722Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd
line 723why, one step back723 pub(crate) fn chain(&self) -> Chain {Add a Chain::new constructorDavid Tolnaybefore adoptionca2b8b9
line 724why, one step back724 Chain::new(self.error())Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
lines 725–727why, one step back725 }726}727Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452
lines 728–735why, one step back728impl<E> StdError for ErrorImpl<E>729where730 E: StdError,731{732 #[cfg(backtrace)]733 fn backtrace(&self) -> Option<&Backtrace> {734 Some(self.erase().backtrace())735 }Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
line 736why, one step back736Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452
line 737why, one step back737 fn source(&self) -> Option<&(dyn StdError + 'static)> {Merge pull request #16 from johnschug/masterDavid Tolnaybefore adoptioneeaf2ef
line 738why, one step back738 self.erase().error().source()Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452
lines 739–741why, one step back739 }740}741Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
lines 742–746why, one step back742impl<E> Debug for ErrorImpl<E>743where744 E: Debug,745{746 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452
line 747why, one step back747 self.erase().debug(formatter)Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
lines 748–755why, one step back748 }749}750751impl<E> Display for ErrorImpl<E>752where753 E: Display,754{755 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {Merge pull request #16 from johnschug/masterDavid Tolnaybefore adoptioneeaf2ef
line 756why, one step back756 Display::fmt(&self.erase().error(), formatter)Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
lines 757–763why, one step back757 }758}759760impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {761 fn from(error: Error) -> Self {762 let outer = ManuallyDrop::new(error);763 unsafe {Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
lines 764–765why, one step back764 // Read Box<ErrorImpl<()>> from error. Can't move it out because765 // Error has a Drop impl which we want to not run.Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
lines 766–767why, one step back766 let inner = ptr::read(&outer.inner);767 let erased = ManuallyDrop::into_inner(inner);Fill in some explanations of unsafe codeDavid Tolnaybefore adoption6088b60
lines 768–770why, one step back768769 // Use vtable to attach ErrorImpl<E>'s native StdError vtable for770 // the right original type E.Merge pull request #12 from dtolnay/boxedDavid Tolnaybefore adoptionbc446d8
lines 771–772why, one step back771 (erased.vtable.object_boxed)(erased)772 }Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 773–775why, one step back773 }774}775Merge pull request #104 from dtolnay/fromDavid Tolnaybefore adoption03a1916
lines 776–781why, one step back776impl From<Error> for Box<dyn StdError + Send + 'static> {777 fn from(error: Error) -> Self {778 Box::<dyn StdError + Send + Sync>::from(error)779 }780}781Merge pull request #28 from dtolnay/fromDavid Tolnaybefore adoption68225d2
lines 782–784why, one step back782impl From<Error> for Box<dyn StdError + 'static> {783 fn from(error: Error) -> Self {784 Box::<dyn StdError + Send + Sync>::from(error)Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 785–786why, one step back785 }786}Add AsRef impls for ErrorDavid Tolnaybefore adoption2c88164
line 787why, one step back787Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 788why, one step back788#[cfg(feature = "std")]Add AsRef impls for ErrorDavid Tolnaybefore adoption2c88164
lines 789–794why, one step back789impl AsRef<dyn StdError + Send + Sync> for Error {790 fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {791 &**self792 }793}794Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 795why, one step back795#[cfg(feature = "std")]Add AsRef impls for ErrorDavid Tolnaybefore adoption2c88164
lines 796–800why, one step back796impl AsRef<dyn StdError> for Error {797 fn as_ref(&self) -> &(dyn StdError + 'static) {798 &**self799 }800}