1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
use crate::std::fmt;

#[cfg(feature = "alloc")]
use crate::std::string::String;

#[cfg(feature = "std")]
use crate::std::{
    boxed::Box,
    error,
};

/**
An error encountered while visiting a value.

# Converting an `Error` into a standard error

The `Error` type doesn't implement the `std::error::Error` trait directly.
When `std` is available, the `into_error` method will convert an
`Error` into a value that implements `std::error::Error`.
*/
pub struct Error(ErrorInner);

impl Error {
    /** Capture a static message as an error. */
    #[inline]
    pub fn msg(msg: &'static str) -> Self {
        Error(ErrorInner::Static(msg))
    }

    /** Declare some structure as unsupported. */
    #[inline]
    pub fn unsupported(operation: &'static str) -> Self {
        Error(ErrorInner::Unsupported {
            msg: operation,
            default: false,
        })
    }

    /** Whether or not an error is because some operation was unsupported. */
    pub fn is_unsupported(&self) -> bool {
        if let ErrorInner::Unsupported { .. } = self.0 {
            true
        } else {
            false
        }
    }

    #[allow(dead_code)]
    pub(crate) fn default_unsupported(operation: &'static str) -> Self {
        Error(ErrorInner::Unsupported {
            msg: operation,
            default: true,
        })
    }

    #[allow(dead_code)]
    pub(crate) fn is_default_unsupported(&self) -> bool {
        if let ErrorInner::Unsupported { default: true, .. } = self.0 {
            true
        } else {
            false
        }
    }

    /** Convert into a `fmt::Error` */
    #[inline]
    pub fn into_fmt_error(self) -> fmt::Error {
        fmt::Error
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

enum ErrorInner {
    Unsupported {
        msg: &'static str,
        default: bool,
    },
    Static(&'static str),
    #[cfg(not(feature = "alloc"))]
    Custom(&'static dyn fmt::Display),
    #[cfg(feature = "alloc")]
    Owned(String),
    #[cfg(feature = "std")]
    Source {
        msg: String,
        source: Box<dyn error::Error + Send + Sync + 'static>,
    },
}

impl fmt::Debug for ErrorInner {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ErrorInner::Unsupported { msg: op, .. } => {
                write!(f, "unsupported stream operation: {}", op)
            }
            ErrorInner::Static(msg) => msg.fmt(f),
            #[cfg(not(feature = "alloc"))]
            ErrorInner::Custom(ref err) => err.fmt(f),
            #[cfg(feature = "alloc")]
            ErrorInner::Owned(ref msg) => msg.fmt(f),
            #[cfg(feature = "std")]
            ErrorInner::Source {
                ref msg,
                ref source,
            } => f
                .debug_struct("Error")
                .field("msg", &msg)
                .field("source", &source)
                .finish(),
        }
    }
}

impl fmt::Display for ErrorInner {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ErrorInner::Unsupported { msg: op, .. } => {
                write!(f, "unsupported stream operation: {}", op)
            }
            ErrorInner::Static(msg) => msg.fmt(f),
            #[cfg(not(feature = "alloc"))]
            ErrorInner::Custom(ref err) => err.fmt(f),
            #[cfg(feature = "alloc")]
            ErrorInner::Owned(ref msg) => msg.fmt(f),
            #[cfg(feature = "std")]
            ErrorInner::Source {
                ref msg,
                ref source,
            } => f.write_fmt(format_args!("{} ({})", msg, source)),
        }
    }
}

impl From<fmt::Error> for Error {
    fn from(_: fmt::Error) -> Self {
        Error::msg("formatting failed")
    }
}

#[cfg(not(feature = "alloc"))]
mod no_alloc_support {
    use super::*;

    use crate::std::fmt;

    impl Error {
        // NOTE: This method is not public because we already
        // have a method called `custom` when `alloc` is available.
        // It's strictly more general than this one, but could
        // be confusing to users to have bounds change depending
        // on cargo features
        pub(crate) fn custom(err: &'static dyn fmt::Display) -> Self {
            Error(ErrorInner::Custom(err))
        }
    }
}

#[cfg(feature = "alloc")]
mod alloc_support {
    use super::*;

    use crate::std::string::ToString;

    impl Error {
        /** Get an error from a format. */
        pub fn custom(err: impl fmt::Display) -> Self {
            Error(ErrorInner::Owned(err.to_string()))
        }
    }
}

#[cfg(feature = "std")]
mod std_support {
    use super::*;

    use crate::std::{
        boxed::Box,
        error,
        io,
    };

    impl Error {
        /** Convert into an io error. */
        #[inline]
        pub fn into_io_error(self) -> io::Error {
            io::Error::new(io::ErrorKind::Other, self)
        }
    }

    impl error::Error for Error {
        fn source(&self) -> Option<&(dyn error::Error + 'static)> {
            if let ErrorInner::Source { ref source, .. } = self.0 {
                Some(&**source)
            } else {
                None
            }
        }
    }

    impl From<io::Error> for Error {
        fn from(err: io::Error) -> Self {
            Error(ErrorInner::Source {
                msg: "failed during an IO operation".into(),
                source: Box::new(err),
            })
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        use crate::std::error::Error as StdError;

        #[test]
        fn io_error() {
            let err = Error::from(io::Error::from(io::ErrorKind::Other));

            assert!(err.source().is_some());
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::std::fmt;

    use super::*;

    #[test]
    fn fmt_error() {
        let _ = Error::from(fmt::Error);
    }
}