Skip to main content

corepack/
error.rs

1//! Error types for corepack.
2//
3// This Source Code Form is subject to the terms of the Mozilla Public License,
4// v. 2.0. If a copy of the MPL was not distributed with this file, You can
5// obtain one at https://mozilla.org/MPL/2.0/.
6use std::fmt::Display;
7
8#[cfg(feature = "alloc")]
9use alloc::string::String;
10
11#[cfg(feature = "alloc")]
12use alloc::string::ToString;
13
14use std::str::Utf8Error;
15
16use std::fmt;
17
18/// Reasons that parsing or encoding might fail in corepack.
19#[derive(Debug)]
20pub enum Error {
21    /// Container or sequence was too big to serialize.
22    TooBig,
23
24    /// Reached end of a stream.
25    EndOfStream,
26
27    /// Invalid type encountered.
28    BadType,
29
30    /// Invalid length encountered.
31    BadLength,
32
33    /// Error decoding UTF8 string.
34    Utf8Error(Utf8Error),
35
36    /// Some other error that does not fit into the above.
37    Other(String),
38}
39
40impl Display for Error {
41    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
42        fmt.write_str(self.description())
43    }
44}
45
46impl Error {
47    fn description(&self) -> &str {
48        match self {
49            &Error::TooBig => "Overflowing value",
50            &Error::EndOfStream => "End of stream",
51            &Error::BadType => "Invalid type",
52            &Error::BadLength => "Invalid length",
53            &Error::Utf8Error(_) => "UTF8 Error",
54            &Error::Other(ref message) => &message,
55        }
56    }
57}
58
59impl From<Utf8Error> for Error {
60    fn from(cause: Utf8Error) -> Error {
61        Error::Utf8Error(cause)
62    }
63}
64
65#[cfg(feature = "std")]
66impl ::std::error::Error for Error {
67    fn description(&self) -> &str {
68        Error::description(self)
69    }
70
71    fn cause(&self) -> Option<&::std::error::Error> {
72        match self {
73            &Error::Utf8Error(ref cause) => Some(cause),
74            _ => None,
75        }
76    }
77}
78
79impl ::serde::ser::Error for Error {
80    fn custom<T: Display>(msg: T) -> Error {
81        Error::Other(msg.to_string())
82    }
83}
84
85impl ::serde::de::Error for Error {
86    fn custom<T: Display>(msg: T) -> Error {
87        ::serde::ser::Error::custom(msg)
88    }
89}