1use core::{
2 fmt,
3 fmt::{Debug, Display, Formatter},
4 num::{IntErrorKind, ParseIntError},
5};
6
7use crate::utils::err_prefix;
8
9#[derive(Copy, Clone, PartialEq)]
22pub enum ParseError {
23 Empty,
27
28 InvalidDigit,
36
37 PosOverflow,
39
40 NegOverflow,
42
43 Zero,
48
49 Signed,
54
55 InvalidRadix,
57
58 Unknown,
60}
61
62impl ParseError {
63 pub(crate) const fn description(&self) -> &str {
64 use ParseError::*;
65 match self {
66 Empty => "attempt to parse integer from empty string",
67 InvalidDigit => "attempt to parse integer from string containing invalid digit",
68 PosOverflow => {
69 "attempt to parse integer too large to be represented by the target type"
70 }
71 NegOverflow => {
72 "attempt to parse integer too small to be represented by the target type"
73 }
74 Zero => {
75 "attempt to parse the integer `0` which cannot be represented by the target type"
76 }
77 Signed => "number would be signed for unsigned type",
78 InvalidRadix => "invalid radix",
79 Unknown => panic!("unknown error occurred"),
80 }
81 }
82}
83
84impl Display for ParseError {
85 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
86 write!(f, "{} {}", err_prefix!(), self.description())
87 }
88}
89
90impl Debug for ParseError {
91 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
92 Display::fmt(&self, f)
93 }
94}
95
96impl From<ParseIntError> for ParseError {
97 fn from(e: ParseIntError) -> ParseError {
98 from_int_error_kind(e.kind())
99 }
100}
101
102impl From<bnum::errors::ParseIntError> for ParseError {
103 fn from(e: bnum::errors::ParseIntError) -> Self {
104 from_int_error_kind(e.kind())
105 }
106}
107
108impl core::error::Error for ParseError {
109 fn description(&self) -> &str {
110 self.description()
111 }
112}
113
114pub(crate) const fn from_int_error_kind(e: &IntErrorKind) -> ParseError {
115 match e {
116 IntErrorKind::Empty => ParseError::Empty,
117 IntErrorKind::InvalidDigit => ParseError::InvalidDigit,
118 IntErrorKind::PosOverflow => ParseError::PosOverflow,
119 IntErrorKind::NegOverflow => ParseError::NegOverflow,
120 IntErrorKind::Zero => ParseError::Zero,
121 _ => ParseError::Unknown,
122 }
123}