Skip to main content

core/num/
error.rs

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