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)]
10pub struct TryFromIntError(pub(crate) ());
11
12#[stable(feature = "try_from", since = "1.34.0")]
13impl fmt::Display for TryFromIntError {
14    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
15        #[allow(deprecated)]
16        self.description().fmt(fmt)
17    }
18}
19
20#[stable(feature = "try_from", since = "1.34.0")]
21impl Error for TryFromIntError {
22    #[allow(deprecated)]
23    fn description(&self) -> &str {
24        "out of range integral type conversion attempted"
25    }
26}
27
28#[stable(feature = "try_from", since = "1.34.0")]
29#[rustc_const_unstable(feature = "const_try", issue = "74935")]
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_try", issue = "74935")]
38impl const From<!> for TryFromIntError {
39    #[inline]
40    fn from(never: !) -> TryFromIntError {
41        // Match rather than coerce to make sure that code like
42        // `From<Infallible> for TryFromIntError` above will keep working
43        // when `Infallible` becomes an alias to `!`.
44        match never {}
45    }
46}
47
48/// An error which can be returned when parsing an integer.
49///
50/// For example, this error is returned by the `from_str_radix()` functions
51/// on the primitive integer types (such as [`i8::from_str_radix`])
52/// and is used as the error type in their [`FromStr`] implementations.
53///
54/// [`FromStr`]: crate::str::FromStr
55///
56/// # Potential causes
57///
58/// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
59/// in the string e.g., when it is obtained from the standard input.
60/// Using the [`str::trim()`] method ensures that no whitespace remains before parsing.
61///
62/// # Example
63///
64/// ```
65/// if let Err(e) = i32::from_str_radix("a12", 10) {
66///     println!("Failed conversion to i32: {e}");
67/// }
68/// ```
69#[derive(Debug, Clone, PartialEq, Eq)]
70#[stable(feature = "rust1", since = "1.0.0")]
71pub struct ParseIntError {
72    pub(super) kind: IntErrorKind,
73}
74
75/// Enum to store the various types of errors that can cause parsing an integer to fail.
76///
77/// # Example
78///
79/// ```
80/// # fn main() {
81/// if let Err(e) = i32::from_str_radix("a12", 10) {
82///     println!("Failed conversion to i32: {:?}", e.kind());
83/// }
84/// # }
85/// ```
86#[stable(feature = "int_error_matching", since = "1.55.0")]
87#[derive(Debug, Clone, PartialEq, Eq, Copy, Hash)]
88#[non_exhaustive]
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    pub const fn kind(&self) -> &IntErrorKind {
124        &self.kind
125    }
126}
127
128#[stable(feature = "rust1", since = "1.0.0")]
129impl fmt::Display for ParseIntError {
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        #[allow(deprecated)]
132        self.description().fmt(f)
133    }
134}
135
136#[stable(feature = "rust1", since = "1.0.0")]
137impl Error for ParseIntError {
138    #[allow(deprecated)]
139    fn description(&self) -> &str {
140        match self.kind {
141            IntErrorKind::Empty => "cannot parse integer from empty string",
142            IntErrorKind::InvalidDigit => "invalid digit found in string",
143            IntErrorKind::PosOverflow => "number too large to fit in target type",
144            IntErrorKind::NegOverflow => "number too small to fit in target type",
145            IntErrorKind::Zero => "number would be zero for non-zero type",
146        }
147    }
148}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy