Coverage Report

Created: 2024-04-29 06:15

/rust/registry/src/github.com-1ecc6299db9ec823/anyhow-1.0.71/src/context.rs
Line
Count
Source (jump to first uncovered line)
1
use crate::error::ContextError;
2
use crate::{Context, Error, StdError};
3
use core::convert::Infallible;
4
use core::fmt::{self, Debug, Display, Write};
5
6
#[cfg(backtrace)]
7
use std::any::{Demand, Provider};
8
9
mod ext {
10
    use super::*;
11
12
    pub trait StdError {
13
        fn ext_context<C>(self, context: C) -> Error
14
        where
15
            C: Display + Send + Sync + 'static;
16
    }
17
18
    #[cfg(feature = "std")]
19
    impl<E> StdError for E
20
    where
21
        E: std::error::Error + Send + Sync + 'static,
22
    {
23
0
        fn ext_context<C>(self, context: C) -> Error
24
0
        where
25
0
            C: Display + Send + Sync + 'static,
26
0
        {
27
0
            let backtrace = backtrace_if_absent!(&self);
28
0
            Error::from_context(context, self, backtrace)
29
0
        }
30
    }
31
32
    impl StdError for Error {
33
0
        fn ext_context<C>(self, context: C) -> Error
34
0
        where
35
0
            C: Display + Send + Sync + 'static,
36
0
        {
37
0
            self.context(context)
38
0
        }
39
    }
40
}
41
42
impl<T, E> Context<T, E> for Result<T, E>
43
where
44
    E: ext::StdError + Send + Sync + 'static,
45
{
46
0
    fn context<C>(self, context: C) -> Result<T, Error>
47
0
    where
48
0
        C: Display + Send + Sync + 'static,
49
0
    {
50
0
        // Not using map_err to save 2 useless frames off the captured backtrace
51
0
        // in ext_context.
52
0
        match self {
53
0
            Ok(ok) => Ok(ok),
54
0
            Err(error) => Err(error.ext_context(context)),
55
        }
56
0
    }
57
58
0
    fn with_context<C, F>(self, context: F) -> Result<T, Error>
59
0
    where
60
0
        C: Display + Send + Sync + 'static,
61
0
        F: FnOnce() -> C,
62
0
    {
63
0
        match self {
64
0
            Ok(ok) => Ok(ok),
65
0
            Err(error) => Err(error.ext_context(context())),
66
        }
67
0
    }
68
}
69
70
/// ```
71
/// # type T = ();
72
/// #
73
/// use anyhow::{Context, Result};
74
///
75
/// fn maybe_get() -> Option<T> {
76
///     # const IGNORE: &str = stringify! {
77
///     ...
78
///     # };
79
///     # unimplemented!()
80
/// }
81
///
82
/// fn demo() -> Result<()> {
83
///     let t = maybe_get().context("there is no T")?;
84
///     # const IGNORE: &str = stringify! {
85
///     ...
86
///     # };
87
///     # unimplemented!()
88
/// }
89
/// ```
90
impl<T> Context<T, Infallible> for Option<T> {
91
0
    fn context<C>(self, context: C) -> Result<T, Error>
92
0
    where
93
0
        C: Display + Send + Sync + 'static,
94
0
    {
95
0
        // Not using ok_or_else to save 2 useless frames off the captured
96
0
        // backtrace.
97
0
        match self {
98
0
            Some(ok) => Ok(ok),
99
0
            None => Err(Error::from_display(context, backtrace!())),
100
        }
101
0
    }
102
103
0
    fn with_context<C, F>(self, context: F) -> Result<T, Error>
104
0
    where
105
0
        C: Display + Send + Sync + 'static,
106
0
        F: FnOnce() -> C,
107
0
    {
108
0
        match self {
109
0
            Some(ok) => Ok(ok),
110
0
            None => Err(Error::from_display(context(), backtrace!())),
111
        }
112
0
    }
113
}
114
115
impl<C, E> Debug for ContextError<C, E>
116
where
117
    C: Display,
118
    E: Debug,
119
{
120
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
121
0
        f.debug_struct("Error")
122
0
            .field("context", &Quoted(&self.context))
123
0
            .field("source", &self.error)
124
0
            .finish()
125
0
    }
126
}
127
128
impl<C, E> Display for ContextError<C, E>
129
where
130
    C: Display,
131
{
132
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
133
0
        Display::fmt(&self.context, f)
134
0
    }
135
}
136
137
impl<C, E> StdError for ContextError<C, E>
138
where
139
    C: Display,
140
    E: StdError + 'static,
141
{
142
0
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
143
0
        Some(&self.error)
144
0
    }
145
146
    #[cfg(backtrace)]
147
0
    fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
148
0
        StdError::provide(&self.error, demand);
149
0
    }
150
}
151
152
impl<C> StdError for ContextError<C, Error>
153
where
154
    C: Display,
155
{
156
0
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
157
0
        Some(unsafe { crate::ErrorImpl::error(self.error.inner.by_ref()) })
158
0
    }
159
160
    #[cfg(backtrace)]
161
0
    fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
162
0
        Provider::provide(&self.error, demand);
163
0
    }
164
}
165
166
struct Quoted<C>(C);
167
168
impl<C> Debug for Quoted<C>
169
where
170
    C: Display,
171
{
172
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
173
0
        formatter.write_char('"')?;
174
0
        Quoted(&mut *formatter).write_fmt(format_args!("{}", self.0))?;
175
0
        formatter.write_char('"')?;
176
0
        Ok(())
177
0
    }
178
}
179
180
impl Write for Quoted<&mut fmt::Formatter<'_>> {
181
0
    fn write_str(&mut self, s: &str) -> fmt::Result {
182
0
        Display::fmt(&s.escape_debug(), self.0)
183
0
    }
184
}
185
186
pub(crate) mod private {
187
    use super::*;
188
189
    pub trait Sealed {}
190
191
    impl<T, E> Sealed for Result<T, E> where E: ext::StdError {}
192
    impl<T> Sealed for Option<T> {}
193
}