reweb3_num/errors/
parseint.rs

1use core::fmt::{self, Debug, Display, Formatter};
2use core::num::IntErrorKind;
3
4/// The error type that is returned when parsing an integer from an invalid source.
5///
6/// This error can occur when the `from_str_radix` or [`FromStr::from_str`](https://doc.rust-lang.org/core/str/trait.FromStr.html#tymethod.from_str) methods of e.g. [`BUint`](crate::BUint::from_str_radix) are called with an invalid input string.
7#[derive(PartialEq, Eq, Clone)]
8pub struct ParseIntError {
9    pub(crate) kind: IntErrorKind,
10}
11
12impl ParseIntError {
13    /// Returns the enum [`IntErrorKind`](https://doc.rust-lang.org/core/num/enum.IntErrorKind.html), which shows the reason that the parsing input was invalid.
14    pub const fn kind(&self) -> &IntErrorKind {
15        &self.kind
16    }
17
18    pub(crate) const fn description(&self) -> &str {
19        match &self.kind {
20            IntErrorKind::Empty => "attempt to parse integer from empty string",
21            IntErrorKind::InvalidDigit => {
22                "attempt to parse integer from string containing invalid digit"
23            }
24            IntErrorKind::PosOverflow => {
25                "attempt to parse integer too large to be represented by the target type"
26            }
27            IntErrorKind::NegOverflow => {
28                "attempt to parse integer too small to be represented by the target type"
29            }
30            IntErrorKind::Zero => {
31                "attempt to parse the integer `0` which cannot be represented by the target type" // for now this should never occur, unless we implement NonZeroU... types
32            }
33            _ => panic!("unsupported `IntErrorKind` variant"), // necessary as `IntErrorKind` is non-exhaustive
34        }
35    }
36}
37
38impl Display for ParseIntError {
39    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
40        write!(f, "{} {}", super::err_prefix!(), self.description())
41    }
42}
43
44impl Debug for ParseIntError {
45    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
46        Display::fmt(&self, f)
47    }
48}