Skip to main content

anyerr/
error.rs

1use alloc::boxed::Box;
2#[cfg(feature = "std")]
3use core::ops::{Deref, DerefMut};
4use core::{
5    any::TypeId,
6    fmt::{self, Debug, Display},
7    mem::ManuallyDrop,
8    ptr,
9    ptr::NonNull,
10};
11#[cfg(error_generic_member_access)]
12use std::error::{self, Request};
13
14#[cfg(feature = "std")]
15use crate::ptr::Mut;
16use crate::{
17    Error, StdError,
18    backtrace::Backtrace,
19    chain::Chain,
20    ptr::{Own, Ref},
21};
22
23impl Error {
24    /// Create a new error object from any error type.
25    ///
26    /// The error type must be threadsafe and `'static`, so that the `Error`
27    /// will be as well.
28    ///
29    /// If the error type does not provide a backtrace, a backtrace will be
30    /// created here to ensure that a backtrace exists.
31    #[cfg(feature = "std")]
32    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
33    #[cold]
34    #[must_use]
35    pub fn new<E>(error: E) -> Self
36    where
37        E: StdError + Send + Sync + 'static,
38    {
39        let backtrace = backtrace_if_absent!(&error);
40        Error::from_std(error, backtrace)
41    }
42
43    /// Create a new error object from a printable error message.
44    ///
45    /// If the argument implements std::error::Error, prefer `Error::new`
46    /// instead which preserves the underlying error's cause chain and
47    /// backtrace. If the argument may or may not implement std::error::Error
48    /// now or in the future, use `anyhow!(err)` which handles either way
49    /// correctly.
50    ///
51    /// `Error::msg("...")` is equivalent to `anyhow!("...")` but occasionally
52    /// convenient in places where a function is preferable over a macro, such
53    /// as iterator or stream combinators:
54    ///
55    /// ```ignore
56    /// # mod ffi {
57    /// #     pub struct Input;
58    /// #     pub struct Output;
59    /// #     pub async fn do_some_work(_: Input) -> Result<Output, &'static str> {
60    /// #         unimplemented!()
61    /// #     }
62    /// # }
63    /// #
64    /// # use ffi::{Input, Output};
65    /// #
66    /// use anyerr::{Error, Result};
67    /// use futures::stream::{Stream, StreamExt, TryStreamExt};
68    ///
69    /// async fn demo<S>(stream: S) -> Result<Vec<Output>>
70    /// where
71    ///     S: Stream<Item = Input>,
72    /// {
73    ///     stream
74    ///         .then(ffi::do_some_work) // returns Result<Output, &str>
75    ///         .map_err(Error::msg)
76    ///         .try_collect()
77    ///         .await
78    /// }
79    /// ```
80    #[cold]
81    #[must_use]
82    pub fn msg<M>(message: M) -> Self
83    where
84        M: Display + Debug + Send + Sync + 'static,
85    {
86        Error::from_adhoc(message, backtrace!())
87    }
88
89    #[cfg(feature = "std")]
90    #[cold]
91    pub(crate) fn from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self
92    where
93        E: StdError + Send + Sync + 'static,
94    {
95        let vtable = &ErrorVTable {
96            object_drop: object_drop::<E>,
97            object_ref: object_ref::<E>,
98            object_boxed: object_boxed::<E>,
99            object_downcast: object_downcast::<E>,
100            object_drop_rest: object_drop_front::<E>,
101            #[cfg(all(not(error_generic_member_access), std_backtrace))]
102            object_backtrace: no_backtrace,
103        };
104
105        // Safety: passing vtable that operates on the right type E.
106        unsafe { Error::construct(error, vtable, backtrace) }
107    }
108
109    #[cold]
110    pub(crate) fn from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> Self
111    where
112        M: Display + Debug + Send + Sync + 'static,
113    {
114        use crate::wrapper::MessageError;
115        let error: MessageError<M> = MessageError(message);
116        let vtable = &ErrorVTable {
117            object_drop: object_drop::<MessageError<M>>,
118            object_ref: object_ref::<MessageError<M>>,
119            object_boxed: object_boxed::<MessageError<M>>,
120            object_downcast: object_downcast::<M>,
121            object_drop_rest: object_drop_front::<M>,
122            #[cfg(all(not(error_generic_member_access), std_backtrace))]
123            object_backtrace: no_backtrace,
124        };
125
126        // Safety: MessageError is repr(transparent) so it is okay for the
127        // vtable to allow casting the MessageError<M> to M.
128        unsafe { Error::construct(error, vtable, backtrace) }
129    }
130
131    #[cold]
132    pub(crate) fn from_display<M>(message: M, backtrace: Option<Backtrace>) -> Self
133    where
134        M: Display + Send + Sync + 'static,
135    {
136        use crate::wrapper::DisplayError;
137        let error: DisplayError<M> = DisplayError(message);
138        let vtable = &ErrorVTable {
139            object_drop: object_drop::<DisplayError<M>>,
140            object_ref: object_ref::<DisplayError<M>>,
141            object_boxed: object_boxed::<DisplayError<M>>,
142            object_downcast: object_downcast::<M>,
143            object_drop_rest: object_drop_front::<M>,
144            #[cfg(all(not(error_generic_member_access), std_backtrace))]
145            object_backtrace: no_backtrace,
146        };
147
148        // Safety: DisplayError is repr(transparent) so it is okay for the
149        // vtable to allow casting the DisplayError<M> to M.
150        unsafe { Error::construct(error, vtable, backtrace) }
151    }
152
153    #[cfg(feature = "std")]
154    #[cold]
155    pub(crate) fn from_context<C, E>(context: C, error: E, backtrace: Option<Backtrace>) -> Self
156    where
157        C: Display + Send + Sync + 'static,
158        E: StdError + Send + Sync + 'static,
159    {
160        let error: ContextError<C, E> = ContextError {
161            context,
162            error,
163        };
164
165        let vtable = &ErrorVTable {
166            object_drop: object_drop::<ContextError<C, E>>,
167            object_ref: object_ref::<ContextError<C, E>>,
168            object_boxed: object_boxed::<ContextError<C, E>>,
169            object_downcast: context_downcast::<C, E>,
170            object_drop_rest: context_drop_rest::<C, E>,
171            #[cfg(all(not(error_generic_member_access), std_backtrace))]
172            object_backtrace: no_backtrace,
173        };
174
175        // Safety: passing vtable that operates on the right type.
176        unsafe { Error::construct(error, vtable, backtrace) }
177    }
178
179    #[cfg(feature = "std")]
180    #[cold]
181    pub(crate) fn from_boxed(error: Box<dyn StdError + Send + Sync>, backtrace: Option<Backtrace>) -> Self {
182        use crate::wrapper::BoxedError;
183        let error = BoxedError(error);
184        let vtable = &ErrorVTable {
185            object_drop: object_drop::<BoxedError>,
186            object_ref: object_ref::<BoxedError>,
187            object_boxed: object_boxed::<BoxedError>,
188            object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,
189            object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,
190            #[cfg(all(not(error_generic_member_access), std_backtrace))]
191            object_backtrace: no_backtrace,
192        };
193
194        // Safety: BoxedError is repr(transparent) so it is okay for the vtable
195        // to allow casting to Box<dyn StdError + Send + Sync>.
196        unsafe { Error::construct(error, vtable, backtrace) }
197    }
198
199    // Takes backtrace as argument rather than capturing it here so that the
200    // user sees one fewer layer of wrapping noise in the backtrace.
201    //
202    // Unsafe because the given vtable must have sensible behavior on the error
203    // value of type E.
204    #[cold]
205    unsafe fn construct<E>(error: E, vtable: &'static ErrorVTable, backtrace: Option<Backtrace>) -> Self
206    where
207        E: StdError + Send + Sync + 'static,
208    {
209        let inner: Box<ErrorImpl<E>> = Box::new(ErrorImpl {
210            vtable,
211            backtrace,
212            _object: error,
213        });
214        // Erase the concrete type of E from the compile-time type system. This
215        // is equivalent to the safe unsize coercion from Box<ErrorImpl<E>> to
216        // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the
217        // result is a thin pointer. The necessary behavior for manipulating the
218        // underlying ErrorImpl<E> is preserved in the vtable provided by the
219        // caller rather than a builtin fat pointer vtable.
220        let inner = Own::new(inner).cast::<ErrorImpl>();
221        Error {
222            inner,
223        }
224    }
225
226    /// Wrap the error value with additional context.
227    ///
228    /// For attaching context to a `Result` as it is propagated, the
229    /// [`Context`][crate::Context] extension trait may be more convenient than
230    /// this function.
231    ///
232    /// The primary reason to use `error.context(...)` instead of
233    /// `result.context(...)` via the `Context` trait would be if the context
234    /// needs to depend on some data held by the underlying error:
235    ///
236    /// ```
237    /// # use std::fmt::{self, Debug, Display};
238    /// #
239    /// # type T = ();
240    /// #
241    /// # impl std::error::Error for ParseError {}
242    /// # impl Debug for ParseError {
243    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
244    /// #         unimplemented!()
245    /// #     }
246    /// # }
247    /// # impl Display for ParseError {
248    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
249    /// #         unimplemented!()
250    /// #     }
251    /// # }
252    /// #
253    /// use anyerr::Result;
254    /// use std::fs::File;
255    /// use std::path::Path;
256    ///
257    /// struct ParseError {
258    ///     line: usize,
259    ///     column: usize,
260    /// }
261    ///
262    /// fn parse_impl(file: File) -> Result<T, ParseError> {
263    ///     # const IGNORE: &str = stringify! {
264    ///     ...
265    ///     # };
266    ///     # unimplemented!()
267    /// }
268    ///
269    /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {
270    ///     let file = File::open(&path)?;
271    ///     parse_impl(file).map_err(|error| {
272    ///         let context = format!(
273    ///             "only the first {} lines of {} are valid",
274    ///             error.line, path.as_ref().display(),
275    ///         );
276    ///         anyerr::Error::new(error).context(context)
277    ///     })
278    /// }
279    /// ```
280    #[cold]
281    #[must_use]
282    pub fn context<C>(self, context: C) -> Self
283    where
284        C: Display + Send + Sync + 'static,
285    {
286        let error: ContextError<C, Error> = ContextError {
287            context,
288            error: self,
289        };
290
291        let vtable = &ErrorVTable {
292            object_drop: object_drop::<ContextError<C, Error>>,
293            object_ref: object_ref::<ContextError<C, Error>>,
294            object_boxed: object_boxed::<ContextError<C, Error>>,
295            object_downcast: context_chain_downcast::<C>,
296            object_drop_rest: context_chain_drop_rest::<C>,
297            #[cfg(all(not(error_generic_member_access), std_backtrace))]
298            object_backtrace: context_backtrace::<C>,
299        };
300
301        // As the cause is anyerr::Error, we already have a backtrace for it.
302        let backtrace = None;
303
304        // Safety: passing vtable that operates on the right type.
305        unsafe { Error::construct(error, vtable, backtrace) }
306    }
307
308    /// Get the backtrace for this Error.
309    ///
310    /// In order for the backtrace to be meaningful, one of the two environment
311    /// variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined
312    /// and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhat
313    /// expensive to capture in Rust, so we don't necessarily want to be
314    /// capturing them all over the place all the time.
315    ///
316    /// - If you want panics and errors to both have backtraces, set
317    ///   `RUST_BACKTRACE=1`;
318    /// - If you want only errors to have backtraces, set
319    ///   `RUST_LIB_BACKTRACE=1`;
320    /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and
321    ///   `RUST_LIB_BACKTRACE=0`.
322    ///
323    /// # Stability
324    ///
325    /// Standard library backtraces are only available when using Rust &ge;
326    /// 1.65. On older compilers, this function is only available if the crate's
327    /// "backtrace" feature is enabled, and will use the `backtrace` crate as
328    /// the underlying backtrace implementation. The return type of this
329    /// function on old compilers is `&(impl Debug + Display)`.
330    ///
331    /// ```toml
332    /// [dependencies]
333    /// anyhow = { version = "1.0", features = ["backtrace"] }
334    /// ```
335    #[cfg(std_backtrace)]
336    pub fn backtrace(&self) -> &impl_backtrace!() {
337        unsafe { ErrorImpl::backtrace(self.inner.by_ref()) }
338    }
339
340    /// An iterator of the chain of source errors contained by this Error.
341    ///
342    /// This iterator will visit every error in the cause chain of this error
343    /// object, beginning with the error that this error object was created
344    /// from.
345    ///
346    /// # Example
347    ///
348    /// ```
349    /// use anyerr::Error;
350    /// use std::io;
351    ///
352    /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {
353    ///     for cause in error.chain() {
354    ///         if let Some(io_error) = cause.downcast_ref::<io::Error>() {
355    ///             return Some(io_error.kind());
356    ///         }
357    ///     }
358    ///     None
359    /// }
360    /// ```
361    #[cfg(feature = "std")]
362    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
363    #[cold]
364    pub fn chain(&self) -> Chain<'_> {
365        unsafe { ErrorImpl::chain(self.inner.by_ref()) }
366    }
367
368    /// The lowest level cause of this error &mdash; this error's cause's
369    /// cause's cause etc.
370    ///
371    /// The root cause is the last error in the iterator produced by
372    /// [`chain()`][Error::chain].
373    #[cfg(feature = "std")]
374    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
375    pub fn root_cause(&self) -> &(dyn StdError + 'static) {
376        self.chain().last().unwrap()
377    }
378
379    /// Returns true if `E` is the type held by this error object.
380    ///
381    /// For errors with context, this method returns true if `E` matches the
382    /// type of the context `C` **or** the type of the error on which the
383    /// context has been attached. For details about the interaction between
384    /// context and downcasting, [see here].
385    ///
386    /// [see here]: trait.Context.html#effect-on-downcasting
387    pub fn is<E>(&self) -> bool
388    where
389        E: Display + Debug + Send + Sync + 'static,
390    {
391        self.downcast_ref::<E>().is_some()
392    }
393
394    /// Attempt to downcast the error object to a concrete type.
395    pub fn downcast<E>(mut self) -> Result<E, Self>
396    where
397        E: Display + Debug + Send + Sync + 'static,
398    {
399        let target = TypeId::of::<E>();
400        let inner = self.inner.by_mut();
401        unsafe {
402            // Use vtable to find NonNull<()> which points to a value of type E
403            // somewhere inside the data structure.
404            let addr = match (vtable(inner.ptr).object_downcast)(inner.by_ref(), target) {
405                Some(addr) => addr.by_mut().extend(),
406                None => return Err(self),
407            };
408
409            // Prepare to read E out of the data structure. We'll drop the rest
410            // of the data structure separately so that E is not dropped.
411            let outer = ManuallyDrop::new(self);
412
413            // Read E from where the vtable found it.
414            let error = addr.cast::<E>().read();
415
416            // Drop rest of the data structure outside of E.
417            (vtable(outer.inner.ptr).object_drop_rest)(outer.inner, target);
418
419            Ok(error)
420        }
421    }
422
423    /// Downcast this error object by reference.
424    ///
425    /// # Example
426    ///
427    /// ```
428    /// # use anyerr::anyhow;
429    /// # use std::fmt::{self, Display};
430    /// # use std::task::Poll;
431    /// #
432    /// # #[derive(Debug)]
433    /// # enum DataStoreError {
434    /// #     Censored(()),
435    /// # }
436    /// #
437    /// # impl Display for DataStoreError {
438    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
439    /// #         unimplemented!()
440    /// #     }
441    /// # }
442    /// #
443    /// # impl std::error::Error for DataStoreError {}
444    /// #
445    /// # const REDACTED_CONTENT: () = ();
446    /// #
447    /// # let error = anyhow!("...");
448    /// # let root_cause = &error;
449    /// #
450    /// # let ret =
451    /// // If the error was caused by redaction, then return a tombstone instead
452    /// // of the content.
453    /// match root_cause.downcast_ref::<DataStoreError>() {
454    ///     Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),
455    ///     None => Err(error),
456    /// }
457    /// # ;
458    /// ```
459    pub fn downcast_ref<E>(&self) -> Option<&E>
460    where
461        E: Display + Debug + Send + Sync + 'static,
462    {
463        let target = TypeId::of::<E>();
464        unsafe {
465            // Use vtable to find NonNull<()> which points to a value of type E
466            // somewhere inside the data structure.
467            let addr = (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?;
468            Some(addr.cast::<E>().deref())
469        }
470    }
471
472    /// Downcast this error object by mutable reference.
473    pub fn downcast_mut<E>(&mut self) -> Option<&mut E>
474    where
475        E: Display + Debug + Send + Sync + 'static,
476    {
477        let target = TypeId::of::<E>();
478        unsafe {
479            // Use vtable to find NonNull<()> which points to a value of type E
480            // somewhere inside the data structure.
481
482            let addr = (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?.by_mut();
483
484            Some(addr.cast::<E>().deref_mut())
485        }
486    }
487
488    #[cfg(error_generic_member_access)]
489    pub(crate) fn provide<'a>(&'a self, request: &mut Request<'a>) {
490        unsafe { ErrorImpl::provide(self.inner.by_ref(), request) }
491    }
492
493    // Called by thiserror when you have `#[source] anyerr::Error`. This provide
494    // implementation includes the anyerr::Error's Backtrace if any, unlike
495    // deref'ing to dyn Error where the provide implementation would include
496    // only the original error's Backtrace from before it got wrapped into an
497    // anyerr::Error.
498    #[cfg(error_generic_member_access)]
499    #[doc(hidden)]
500    pub fn thiserror_provide<'a>(&'a self, request: &mut Request<'a>) {
501        Self::provide(self, request);
502    }
503}
504
505#[cfg(feature = "std")]
506#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
507impl<E> From<E> for Error
508where
509    E: StdError + Send + Sync + 'static,
510{
511    #[cold]
512    fn from(error: E) -> Self {
513        let backtrace = backtrace_if_absent!(&error);
514        Error::from_std(error, backtrace)
515    }
516}
517
518#[cfg(feature = "std")]
519#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
520impl Deref for Error {
521    type Target = dyn StdError + Send + Sync + 'static;
522
523    fn deref(&self) -> &Self::Target {
524        unsafe { ErrorImpl::error(self.inner.by_ref()) }
525    }
526}
527
528#[cfg(feature = "std")]
529#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
530impl DerefMut for Error {
531    fn deref_mut(&mut self) -> &mut Self::Target {
532        unsafe { ErrorImpl::error_mut(self.inner.by_mut()) }
533    }
534}
535
536impl Display for Error {
537    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
538        unsafe { ErrorImpl::display(self.inner.by_ref(), formatter) }
539    }
540}
541
542impl Debug for Error {
543    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
544        unsafe { ErrorImpl::debug(self.inner.by_ref(), formatter) }
545    }
546}
547
548impl Drop for Error {
549    fn drop(&mut self) {
550        unsafe {
551            // Invoke the vtable's drop behavior.
552            (vtable(self.inner.ptr).object_drop)(self.inner);
553        }
554    }
555}
556
557struct ErrorVTable {
558    object_drop: unsafe fn(Own<ErrorImpl>),
559    object_ref: unsafe fn(Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>,
560    object_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,
561    object_downcast: unsafe fn(Ref<ErrorImpl>, TypeId) -> Option<Ref<()>>,
562    object_drop_rest: unsafe fn(Own<ErrorImpl>, TypeId),
563    #[cfg(all(not(error_generic_member_access), std_backtrace))]
564    object_backtrace: unsafe fn(Ref<ErrorImpl>) -> Option<&Backtrace>,
565}
566
567// Safety: requires layout of *e to match ErrorImpl<E>.
568unsafe fn object_drop<E>(e: Own<ErrorImpl>) {
569    // Cast back to ErrorImpl<E> so that the allocator receives the correct
570    // Layout to deallocate the Box's memory.
571    let unerased_own = e.cast::<ErrorImpl<E>>();
572    drop(unsafe { unerased_own.boxed() });
573}
574
575// Safety: requires layout of *e to match ErrorImpl<E>.
576unsafe fn object_drop_front<E>(e: Own<ErrorImpl>, target: TypeId) {
577    // Drop the fields of ErrorImpl other than E as well as the Box allocation,
578    // without dropping E itself. This is used by downcast after doing a
579    // ptr::read to take ownership of the E.
580    let _ = target;
581    let unerased_own = e.cast::<ErrorImpl<ManuallyDrop<E>>>();
582    drop(unsafe { unerased_own.boxed() });
583}
584
585// Safety: requires layout of *e to match ErrorImpl<E>.
586unsafe fn object_ref<E>(e: Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>
587where
588    E: StdError + Send + Sync + 'static,
589{
590    // Attach E's native StdError vtable onto a pointer to self._object.
591
592    let unerased_ref = e.cast::<ErrorImpl<E>>();
593
594    return Ref::from_raw(unsafe { NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object) as *mut E) });
595}
596
597// Safety: requires layout of *e to match ErrorImpl<E>.
598unsafe fn object_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>
599where
600    E: StdError + Send + Sync + 'static,
601{
602    // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.
603    let unerased_own = e.cast::<ErrorImpl<E>>();
604    unsafe { unerased_own.boxed() }
605}
606
607// Safety: requires layout of *e to match ErrorImpl<E>.
608unsafe fn object_downcast<E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>
609where
610    E: 'static,
611{
612    if TypeId::of::<E>() == target {
613        // Caller is looking for an E pointer and e is ErrorImpl<E>, take a
614        // pointer to its E field.
615
616        let unerased_ref = e.cast::<ErrorImpl<E>>();
617
618        return Some(
619            Ref::from_raw(unsafe { NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object) as *mut E) })
620                .cast::<()>(),
621        );
622    } else {
623        None
624    }
625}
626
627#[cfg(all(not(error_generic_member_access), std_backtrace))]
628fn no_backtrace(e: Ref<'_, ErrorImpl>) -> Option<&Backtrace> {
629    let _ = e;
630    None
631}
632
633// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.
634#[cfg(feature = "std")]
635unsafe fn context_downcast<C, E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>
636where
637    C: 'static,
638    E: 'static,
639{
640    if TypeId::of::<C>() == target {
641        let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();
642        let unerased = unsafe { unerased_ref.deref() };
643        Some(Ref::new(&unerased._object.context).cast::<()>())
644    } else if TypeId::of::<E>() == target {
645        let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();
646        let unerased = unsafe { unerased_ref.deref() };
647        Some(Ref::new(&unerased._object.error).cast::<()>())
648    } else {
649        None
650    }
651}
652
653// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.
654#[cfg(feature = "std")]
655unsafe fn context_drop_rest<C, E>(e: Own<ErrorImpl>, target: TypeId)
656where
657    C: 'static,
658    E: 'static,
659{
660    // Called after downcasting by value to either the C or the E and doing a
661    // ptr::read to take ownership of that value.
662    if TypeId::of::<C>() == target {
663        let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>();
664        drop(unsafe { unerased_own.boxed() });
665    } else {
666        let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>();
667        drop(unsafe { unerased_own.boxed() });
668    }
669}
670
671// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.
672unsafe fn context_chain_downcast<C>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>
673where
674    C: 'static,
675{
676    let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();
677    let unerased = unsafe { unerased_ref.deref() };
678    if TypeId::of::<C>() == target {
679        Some(Ref::new(&unerased._object.context).cast::<()>())
680    } else {
681        // Recurse down the context chain per the inner error's vtable.
682        let source = &unerased._object.error;
683        unsafe { (vtable(source.inner.ptr).object_downcast)(source.inner.by_ref(), target) }
684    }
685}
686
687// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.
688unsafe fn context_chain_drop_rest<C>(e: Own<ErrorImpl>, target: TypeId)
689where
690    C: 'static,
691{
692    // Called after downcasting by value to either the C or one of the causes
693    // and doing a ptr::read to take ownership of that value.
694    if TypeId::of::<C>() == target {
695        let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>();
696        // Drop the entire rest of the data structure rooted in the next Error.
697        drop(unsafe { unerased_own.boxed() });
698    } else {
699        let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>();
700        let unerased = unsafe { unerased_own.boxed() };
701        // Read the Own<ErrorImpl> from the next error.
702        let inner = unerased._object.error.inner;
703        drop(unerased);
704        let vtable = unsafe { vtable(inner.ptr) };
705        // Recursively drop the next error using the same target typeid.
706        unsafe { (vtable.object_drop_rest)(inner, target) };
707    }
708}
709
710// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.
711#[cfg(all(not(error_generic_member_access), std_backtrace))]
712#[allow(clippy::unnecessary_wraps)]
713unsafe fn context_backtrace<C>(e: Ref<'_, ErrorImpl>) -> Option<&Backtrace>
714where
715    C: 'static,
716{
717    let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();
718    let unerased = unsafe { unerased_ref.deref() };
719    let backtrace = unsafe { ErrorImpl::backtrace(unerased._object.error.inner.by_ref()) };
720    Some(backtrace)
721}
722
723// NOTE: If working with `ErrorImpl<()>`, references should be avoided in favor
724// of raw pointers and `NonNull`.
725// repr C to ensure that E remains in the final position.
726#[repr(C)]
727pub(crate) struct ErrorImpl<E = ()> {
728    vtable: &'static ErrorVTable,
729    backtrace: Option<Backtrace>,
730    // NOTE: Don't use directly. Use only through vtable. Erased type may have
731    // different alignment.
732    _object: E,
733}
734
735// Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but
736// avoids converting `p` into a reference.
737unsafe fn vtable(p: NonNull<ErrorImpl>) -> &'static ErrorVTable {
738    // NOTE: This assumes that `ErrorVTable` is the first field of ErrorImpl.
739    unsafe { *(p.as_ptr() as *const &'static ErrorVTable) }
740}
741
742// repr C to ensure that ContextError<C, E> has the same layout as
743// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.
744#[repr(C)]
745pub(crate) struct ContextError<C, E> {
746    pub context: C,
747    pub error: E,
748}
749
750impl<E> ErrorImpl<E> {
751    fn erase(&self) -> Ref<'_, ErrorImpl> {
752        // Erase the concrete type of E but preserve the vtable in self.vtable
753        // for manipulating the resulting thin pointer. This is analogous to an
754        // unsize coercion.
755        Ref::new(self).cast::<ErrorImpl>()
756    }
757}
758
759impl ErrorImpl {
760    pub(crate) unsafe fn error(this: Ref<'_, Self>) -> &(dyn StdError + Send + Sync + 'static) {
761        // Use vtable to attach E's native StdError vtable for the right
762        // original type E.
763        unsafe { (vtable(this.ptr).object_ref)(this).deref() }
764    }
765
766    #[cfg(feature = "std")]
767    pub(crate) unsafe fn error_mut(this: Mut<'_, Self>) -> &mut (dyn StdError + Send + Sync + 'static) {
768        // Use vtable to attach E's native StdError vtable for the right
769        // original type E.
770        unsafe { (vtable(this.ptr).object_ref)(this.by_ref()).by_mut().deref_mut() }
771    }
772
773    #[cfg(std_backtrace)]
774    pub(crate) unsafe fn backtrace(this: Ref<'_, Self>) -> &Backtrace {
775        // This unwrap can only panic if the underlying error's backtrace method
776        // is nondeterministic, which would only happen in maliciously
777        // constructed code.
778        unsafe { this.deref() }
779            .backtrace
780            .as_ref()
781            .or_else(|| {
782                #[cfg(error_generic_member_access)]
783                return error::request_ref::<Backtrace>(unsafe { Self::error(this) });
784                #[cfg(not(error_generic_member_access))]
785                return unsafe { (vtable(this.ptr).object_backtrace)(this) };
786            })
787            .expect("backtrace capture failed")
788    }
789
790    #[cfg(error_generic_member_access)]
791    unsafe fn provide<'a>(this: Ref<'a, Self>, request: &mut Request<'a>) {
792        if let Some(backtrace) = unsafe { &this.deref().backtrace } {
793            request.provide_ref(backtrace);
794        }
795        unsafe { Self::error(this) }.provide(request);
796    }
797
798    #[cold]
799    pub(crate) unsafe fn chain(this: Ref<Self>) -> Chain {
800        Chain::new(unsafe { Self::error(this) })
801    }
802}
803
804impl<E> StdError for ErrorImpl<E>
805where
806    E: StdError,
807{
808    fn source(&self) -> Option<&(dyn StdError + 'static)> {
809        unsafe { ErrorImpl::error(self.erase()).source() }
810    }
811
812    #[cfg(error_generic_member_access)]
813    fn provide<'a>(&'a self, request: &mut Request<'a>) {
814        unsafe { ErrorImpl::provide(self.erase(), request) }
815    }
816}
817
818impl<E> Debug for ErrorImpl<E>
819where
820    E: Debug,
821{
822    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
823        unsafe { ErrorImpl::debug(self.erase(), formatter) }
824    }
825}
826
827impl<E> Display for ErrorImpl<E>
828where
829    E: Display,
830{
831    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
832        unsafe { Display::fmt(ErrorImpl::error(self.erase()), formatter) }
833    }
834}
835
836impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {
837    #[cold]
838    fn from(error: Error) -> Self {
839        let outer = ManuallyDrop::new(error);
840        unsafe {
841            // Use vtable to attach ErrorImpl<E>'s native StdError vtable for
842            // the right original type E.
843            (vtable(outer.inner.ptr).object_boxed)(outer.inner)
844        }
845    }
846}
847
848impl From<Error> for Box<dyn StdError + Send + 'static> {
849    fn from(error: Error) -> Self {
850        Box::<dyn StdError + Send + Sync>::from(error)
851    }
852}
853
854impl From<Error> for Box<dyn StdError + 'static> {
855    fn from(error: Error) -> Self {
856        Box::<dyn StdError + Send + Sync>::from(error)
857    }
858}
859
860#[cfg(feature = "std")]
861impl AsRef<dyn StdError + Send + Sync> for Error {
862    fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {
863        &**self
864    }
865}
866
867#[cfg(feature = "std")]
868impl AsRef<dyn StdError> for Error {
869    fn as_ref(&self) -> &(dyn StdError + 'static) {
870        &**self
871    }
872}