Skip to main content

core/num/
error.rs

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