core/num/
error.rs

1//! Error types for conversion to integral types.
2
3#[cfg(not(feature = "ferrocene_certified"))]
4use crate::convert::Infallible;
5#[cfg(not(feature = "ferrocene_certified"))]
6use crate::error::Error;
7#[cfg(not(feature = "ferrocene_certified"))]
8use crate::fmt;
9
10/// The error type returned when a checked integral type conversion fails.
11#[stable(feature = "try_from", since = "1.34.0")]
12#[cfg_attr(not(feature = "ferrocene_certified"), derive(Debug, Copy, Clone, PartialEq, Eq))]
13pub struct TryFromIntError(pub(crate) ());
14
15#[stable(feature = "try_from", since = "1.34.0")]
16#[cfg(not(feature = "ferrocene_certified"))]
17impl fmt::Display for TryFromIntError {
18    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19        "out of range integral type conversion attempted".fmt(f)
20    }
21}
22
23#[stable(feature = "try_from", since = "1.34.0")]
24#[cfg(not(feature = "ferrocene_certified"))]
25impl Error for TryFromIntError {}
26
27#[stable(feature = "try_from", since = "1.34.0")]
28#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
29#[cfg(not(feature = "ferrocene_certified"))]
30impl const From<Infallible> for TryFromIntError {
31    fn from(x: Infallible) -> TryFromIntError {
32        match x {}
33    }
34}
35
36#[unstable(feature = "never_type", issue = "35121")]
37#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
38#[cfg(not(feature = "ferrocene_certified"))]
39impl const From<!> for TryFromIntError {
40    #[inline]
41    fn from(never: !) -> TryFromIntError {
42        // Match rather than coerce to make sure that code like
43        // `From<Infallible> for TryFromIntError` above will keep working
44        // when `Infallible` becomes an alias to `!`.
45        match never {}
46    }
47}
48
49/// An error which can be returned when parsing an integer.
50///
51/// For example, this error is returned by the `from_str_radix()` functions
52/// on the primitive integer types (such as [`i8::from_str_radix`])
53/// and is used as the error type in their [`FromStr`] implementations.
54///
55/// [`FromStr`]: crate::str::FromStr
56///
57/// # Potential causes
58///
59/// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
60/// in the string e.g., when it is obtained from the standard input.
61/// Using the [`str::trim()`] method ensures that no whitespace remains before parsing.
62///
63/// # Example
64///
65/// ```
66/// if let Err(e) = i32::from_str_radix("a12", 10) {
67///     println!("Failed conversion to i32: {e}");
68/// }
69/// ```
70#[derive(Debug, Clone, PartialEq, Eq)]
71#[stable(feature = "rust1", since = "1.0.0")]
72#[cfg(not(feature = "ferrocene_certified"))]
73pub struct ParseIntError {
74    pub(super) kind: IntErrorKind,
75}
76
77/// Enum to store the various types of errors that can cause parsing an integer to fail.
78///
79/// # Example
80///
81/// ```
82/// # fn main() {
83/// if let Err(e) = i32::from_str_radix("a12", 10) {
84///     println!("Failed conversion to i32: {:?}", e.kind());
85/// }
86/// # }
87/// ```
88#[stable(feature = "int_error_matching", since = "1.55.0")]
89#[derive(Debug, Clone, PartialEq, Eq, Copy, Hash)]
90#[non_exhaustive]
91#[cfg(not(feature = "ferrocene_certified"))]
92pub enum IntErrorKind {
93    /// Value being parsed is empty.
94    ///
95    /// This variant will be constructed when parsing an empty string.
96    #[stable(feature = "int_error_matching", since = "1.55.0")]
97    Empty,
98    /// Contains an invalid digit in its context.
99    ///
100    /// Among other causes, this variant will be constructed when parsing a string that
101    /// contains a non-ASCII char.
102    ///
103    /// This variant is also constructed when a `+` or `-` is misplaced within a string
104    /// either on its own or in the middle of a number.
105    #[stable(feature = "int_error_matching", since = "1.55.0")]
106    InvalidDigit,
107    /// Integer is too large to store in target integer type.
108    #[stable(feature = "int_error_matching", since = "1.55.0")]
109    PosOverflow,
110    /// Integer is too small to store in target integer type.
111    #[stable(feature = "int_error_matching", since = "1.55.0")]
112    NegOverflow,
113    /// Value was Zero
114    ///
115    /// This variant will be emitted when the parsing string has a value of zero, which
116    /// would be illegal for non-zero types.
117    #[stable(feature = "int_error_matching", since = "1.55.0")]
118    Zero,
119}
120
121#[cfg(not(feature = "ferrocene_certified"))]
122impl ParseIntError {
123    /// Outputs the detailed cause of parsing an integer failing.
124    #[must_use]
125    #[rustc_const_stable(feature = "const_int_from_str", since = "1.82.0")]
126    #[stable(feature = "int_error_matching", since = "1.55.0")]
127    pub const fn kind(&self) -> &IntErrorKind {
128        &self.kind
129    }
130}
131
132#[stable(feature = "rust1", since = "1.0.0")]
133#[cfg(not(feature = "ferrocene_certified"))]
134impl fmt::Display for ParseIntError {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        match self.kind {
137            IntErrorKind::Empty => "cannot parse integer from empty string",
138            IntErrorKind::InvalidDigit => "invalid digit found in string",
139            IntErrorKind::PosOverflow => "number too large to fit in target type",
140            IntErrorKind::NegOverflow => "number too small to fit in target type",
141            IntErrorKind::Zero => "number would be zero for non-zero type",
142        }
143        .fmt(f)
144    }
145}
146
147#[stable(feature = "rust1", since = "1.0.0")]
148#[cfg(not(feature = "ferrocene_certified"))]
149impl Error for ParseIntError {}