| 1 | use core::{ |
| 2 | fmt::{self, Debug, Display, Formatter}, |
| 3 | num::ParseIntError as StdParseIntError, |
| 4 | }; |
| 5 | |
| 6 | /// The error type returned when when parsing an integer fails. |
| 7 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 8 | pub struct ParseIntError { |
| 9 | pub(crate) kind: ParseIntErrorKind, |
| 10 | } |
| 11 | |
| 12 | // When https://github.com/rust-lang/rust/issues/22639 is resolved, the error kind can be provided |
| 13 | // publicly as well. For now, distinguishing between overflow / underflow and anything else doesn't |
| 14 | // seem very useful. |
| 15 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 16 | pub(crate) enum ParseIntErrorKind { |
| 17 | Overflow, |
| 18 | Underflow, |
| 19 | Unknown(StdParseIntError), |
| 20 | } |
| 21 | |
| 22 | impl From<StdParseIntError> for ParseIntError { |
| 23 | fn from(e: StdParseIntError) -> Self { |
| 24 | ParseIntError { kind: ParseIntErrorKind::Unknown(e) } |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | impl Display for ParseIntError { |
| 29 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { |
| 30 | match &self.kind { |
| 31 | ParseIntErrorKind::Overflow => f.write_str("number too large to fit in target type"), |
| 32 | ParseIntErrorKind::Underflow => f.write_str("number too small to fit in target type"), |
| 33 | ParseIntErrorKind::Unknown(e) => write!(f, "{}", e), |
| 34 | } |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | #[cfg(feature = "std")] |
| 39 | impl std::error::Error for ParseIntError {} |
| 40 | |
| 41 | /// The error type returned when a checked integral type conversion fails. |
| 42 | #[derive(Clone)] |
| 43 | pub struct TryFromIntError { |
| 44 | _private: (), |
| 45 | } |
| 46 | |
| 47 | impl TryFromIntError { |
| 48 | pub(crate) fn new() -> Self { |
| 49 | Self { _private: () } |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | impl Display for TryFromIntError { |
| 54 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { |
| 55 | f.write_str("out of range integral type conversion attempted") |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | impl Debug for TryFromIntError { |
| 60 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { |
| 61 | f.write_str("TryFromIntError") |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | #[cfg(feature = "std")] |
| 66 | impl std::error::Error for TryFromIntError {} |