Skip to main content

core/convert/
num.rs

1use crate::num::{IntErrorKind, TryFromIntError};
2
3/// Supporting trait for inherent methods of `f32` and `f64` such as `to_int_unchecked`.
4/// Typically doesn’t need to be used directly.
5#[unstable(feature = "convert_float_to_int", issue = "67057")]
6pub impl(self) trait FloatToInt<Int>: Sized {
7    #[unstable(feature = "convert_float_to_int", issue = "67057")]
8    #[doc(hidden)]
9    unsafe fn to_int_unchecked(self) -> Int;
10
11    #[unstable(feature = "float_conversions", issue = "159913")]
12    #[doc(hidden)]
13    fn to_int_saturating(self) -> Int;
14
15    #[unstable(feature = "float_conversions", issue = "159913")]
16    #[doc(hidden)]
17    fn to_int_checked(self) -> Option<Int>;
18}
19
20macro_rules! impl_float_to_int {
21    ($Float:ty => $($Int:ty),+) => {
22        $(
23            #[unstable(feature = "convert_float_to_int", issue = "67057")]
24            impl FloatToInt<$Int> for $Float {
25                #[inline]
26                unsafe fn to_int_unchecked(self) -> $Int {
27                    // SAFETY: the safety contract must be upheld by the caller.
28                    unsafe { crate::intrinsics::float_to_int_unchecked(self) }
29                }
30                #[inline]
31                fn to_int_saturating(self) -> $Int {
32                    // `as` already saturates and maps `NaN` to zero.
33                    self as $Int
34                }
35                #[inline]
36                fn to_int_checked(self) -> Option<$Int> {
37                    // We will compute LOW_THRESHOLD and HIGH_THRESHOLD
38                    // as <$Int>::MIN - 1 and <$Int>::MAX + 1 respectively,
39                    // or the next lower/higher value in case those are not
40                    // representable exactly. These thresholds represent the
41                    // first disallowed values.
42
43                    const LOW_THRESHOLD: $Float = {
44                        // The minimum of an integer type is representable or -INF
45                        // for all floats, as it is zero or a power of two.
46                        let int_min = <$Int>::MIN as $Float;
47                        let one_below_if_representable = int_min - 1.0;
48                        if one_below_if_representable == int_min {
49                            // We must allow int_min itself. In case int_min is
50                            // -INF this stays -INF, allowing any finite value.
51                            int_min.next_down()
52                        } else {
53                            one_below_if_representable
54                        }
55                    };
56
57                    const HIGH_THRESHOLD: $Float = {
58                        // The maximum of an integer type is always of the form
59                        // 2^k - 1 for some reasonable k. We can construct 2^k
60                        // exactly by summing 2^(k-1) twice, which fits in the
61                        // integer. The outcome will be exactly <$Int>::MAX + 1,
62                        // or INF allowing any finite value.
63                        let half = (<$Int>::MAX / 2) + 1;
64                        half as $Float + half as $Float
65                    };
66
67                    // NaN always fails these comparisons, and infinities at
68                    // least one.
69                    if LOW_THRESHOLD < self && self < HIGH_THRESHOLD {
70                        // SAFETY: we made sure we are in-bounds and finite.
71                        Some(unsafe { self.to_int_unchecked() })
72                    } else {
73                        None
74                    }
75                }
76            }
77        )+
78    }
79}
80
81impl_float_to_int!(f16 => u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);
82impl_float_to_int!(f32 => u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);
83impl_float_to_int!(f64 => u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);
84impl_float_to_int!(f128 => u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);
85
86/// Supporting trait for the inherent `cast` method converting between float types.
87/// Typically doesn’t need to be used directly.
88#[unstable(feature = "float_conversions", issue = "159913")]
89pub impl(self) trait FloatToFloat<Flt>: Sized {
90    #[unstable(feature = "float_conversions", issue = "159913")]
91    #[doc(hidden)]
92    fn cast(self) -> Flt;
93}
94
95macro_rules! impl_float_to_float {
96    ($Float:ty => $($Flt:ty),+) => {
97        $(
98            #[unstable(feature = "float_conversions", issue = "159913")]
99            impl FloatToFloat<$Flt> for $Float {
100                #[inline]
101                fn cast(self) -> $Flt {
102                    self as $Flt
103                }
104            }
105        )+
106    }
107}
108
109impl_float_to_float!(f16 => f16, f32, f64, f128);
110impl_float_to_float!(f32 => f16, f32, f64, f128);
111impl_float_to_float!(f64 => f16, f32, f64, f128);
112impl_float_to_float!(f128 => f16, f32, f64, f128);
113
114/// Implement `From<bool>` for integers
115macro_rules! impl_from_bool {
116    ($($int:ty)*) => {$(
117        #[stable(feature = "from_bool", since = "1.28.0")]
118        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
119        const impl From<bool> for $int {
120            /// Converts from [`bool`] to
121            #[doc = concat!("[`", stringify!($int), "`]")]
122            /// , by turning `false` into `0` and `true` into `1`.
123            ///
124            /// # Examples
125            ///
126            /// ```
127            #[doc = concat!("assert_eq!(", stringify!($int), "::from(false), 0);")]
128            ///
129            #[doc = concat!("assert_eq!(", stringify!($int), "::from(true), 1);")]
130            /// ```
131            #[inline(always)]
132            fn from(b: bool) -> Self {
133                b as Self
134            }
135        }
136    )*}
137}
138
139// boolean -> integer
140impl_from_bool!(u8 u16 u32 u64 u128 usize);
141impl_from_bool!(i8 i16 i32 i64 i128 isize);
142
143/// Implement `From<$small>` for `$large`
144macro_rules! impl_from {
145    ($small:ty => $large:ty, $(#[$attrs:meta]),+) => {
146        $(#[$attrs])+
147        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
148        const impl From<$small> for $large {
149            #[doc = concat!("Converts from [`", stringify!($small), "`] to [`", stringify!($large), "`] losslessly.")]
150            #[inline(always)]
151            fn from(small: $small) -> Self {
152                debug_assert!(<$large>::MIN as i128 <= <$small>::MIN as i128);
153                debug_assert!(<$small>::MAX as u128 <= <$large>::MAX as u128);
154                small as Self
155            }
156        }
157    }
158}
159
160// unsigned integer -> unsigned integer
161impl_from!(u8 => u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")]);
162impl_from!(u8 => u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")]);
163impl_from!(u8 => u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")]);
164impl_from!(u8 => u128, #[stable(feature = "i128", since = "1.26.0")]);
165impl_from!(u8 => usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")]);
166impl_from!(u16 => u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")]);
167impl_from!(u16 => u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")]);
168impl_from!(u16 => u128, #[stable(feature = "i128", since = "1.26.0")]);
169impl_from!(u32 => u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")]);
170impl_from!(u32 => u128, #[stable(feature = "i128", since = "1.26.0")]);
171impl_from!(u64 => u128, #[stable(feature = "i128", since = "1.26.0")]);
172
173// signed integer -> signed integer
174impl_from!(i8 => i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")]);
175impl_from!(i8 => i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")]);
176impl_from!(i8 => i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")]);
177impl_from!(i8 => i128, #[stable(feature = "i128", since = "1.26.0")]);
178impl_from!(i8 => isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")]);
179impl_from!(i16 => i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")]);
180impl_from!(i16 => i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")]);
181impl_from!(i16 => i128, #[stable(feature = "i128", since = "1.26.0")]);
182impl_from!(i32 => i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")]);
183impl_from!(i32 => i128, #[stable(feature = "i128", since = "1.26.0")]);
184impl_from!(i64 => i128, #[stable(feature = "i128", since = "1.26.0")]);
185
186// unsigned integer -> signed integer
187impl_from!(u8 => i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")]);
188impl_from!(u8 => i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")]);
189impl_from!(u8 => i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")]);
190impl_from!(u8 => i128, #[stable(feature = "i128", since = "1.26.0")]);
191impl_from!(u16 => i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")]);
192impl_from!(u16 => i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")]);
193impl_from!(u16 => i128, #[stable(feature = "i128", since = "1.26.0")]);
194impl_from!(u32 => i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")]);
195impl_from!(u32 => i128, #[stable(feature = "i128", since = "1.26.0")]);
196impl_from!(u64 => i128, #[stable(feature = "i128", since = "1.26.0")]);
197
198// The C99 standard defines bounds on INTPTR_MIN, INTPTR_MAX, and UINTPTR_MAX
199// which imply that pointer-sized integers must be at least 16 bits:
200// https://port70.net/~nsz/c/c99/n1256.html#7.18.2.4
201impl_from!(u16 => usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")]);
202impl_from!(u8 => isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")]);
203impl_from!(i16 => isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")]);
204
205// RISC-V defines the possibility of a 128-bit address space (RV128).
206
207// CHERI proposes 128-bit “capabilities”. Unclear if this would be relevant to usize/isize.
208// https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf
209// https://www.cl.cam.ac.uk/techreports/UCAM-CL-TR-951.pdf
210
211// Note: integers can only be represented with full precision in a float if
212// they fit in the significand, which is:
213// * 11 bits in f16
214// * 24 bits in f32
215// * 53 bits in f64
216// * 113 bits in f128
217// Lossy float conversions are not implemented at this time.
218// FIXME(f16,f128): The `f16`/`f128` impls `#[stable]` attributes should be changed to reference
219// `f16`/`f128` when they are stabilised (trait impls have to have a `#[stable]` attribute, but none
220// of the `f16`/`f128` impls can be used on stable as the `f16` and `f128` types are unstable).
221
222// signed integer -> float
223impl_from!(i8 => f16, #[unstable(feature = "f16", issue = "116909")], #[unstable_feature_bound(f16)]);
224impl_from!(i8 => f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")]);
225impl_from!(i8 => f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")]);
226impl_from!(i8 => f128, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f128)]);
227impl_from!(i16 => f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")]);
228impl_from!(i16 => f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")]);
229impl_from!(i16 => f128, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f128)]);
230impl_from!(i32 => f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")]);
231impl_from!(i32 => f128, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f128)]);
232impl_from!(i64 => f128, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f128)]);
233
234// unsigned integer -> float
235impl_from!(u8 => f16, #[unstable(feature = "f16", issue = "116909")], #[unstable_feature_bound(f16)]);
236impl_from!(u8 => f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")]);
237impl_from!(u8 => f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")]);
238impl_from!(u8 => f128, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f128)]);
239impl_from!(u16 => f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")]);
240impl_from!(u16 => f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")]);
241impl_from!(u16 => f128, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f128)]);
242impl_from!(u32 => f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")]);
243impl_from!(u32 => f128, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f128)]);
244impl_from!(u64 => f128, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f128)]);
245
246// float -> float
247
248// FIXME(f16): adding the additional `From<{float}>` impl to `f32` would break inference in cases
249// like `f32::from(1.0)`. The type checker has a custom workaround to keep that and similar code
250// compiling even with the second `From<16> for f32` instance. We keep this instance unstable for
251// now so that we can later remove the workaround.
252//
253// See also <https://github.com/rust-lang/rust/issues/123831>.
254impl_from!(f16 => f32, #[unstable(feature = "f32_from_f16", issue = "154005")], #[unstable_feature_bound(f32_from_f16)]);
255impl_from!(f16 => f64, #[unstable(feature = "f16", issue = "116909")], #[unstable_feature_bound(f16)]);
256// Also #[unstable(feature = "f16", issue = "116909")]:
257impl_from!(f16 => f128, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f16, f128)]);
258impl_from!(f32 => f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")]);
259impl_from!(f32 => f128, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f128)]);
260impl_from!(f64 => f128, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f128)]);
261
262macro_rules! impl_float_from_bool {
263    (
264        $(#[$attr:meta])*
265        $float:ty $(;
266            doctest_prefix: $(#[doc = $doctest_prefix:literal])*
267            doctest_suffix: $(#[doc = $doctest_suffix:literal])*
268        )?
269    ) => {
270        $(#[$attr])*
271        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
272            const impl From<bool> for $float {
273            #[doc = concat!("Converts a [`bool`] to [`", stringify!($float),"`] losslessly.")]
274            /// The resulting value is positive `0.0` for `false` and `1.0` for `true` values.
275            ///
276            /// # Examples
277            /// ```
278            $($(#[doc = $doctest_prefix])*)?
279            #[doc = concat!("let x = ", stringify!($float), "::from(false);")]
280            /// assert_eq!(x, 0.0);
281            /// assert!(x.is_sign_positive());
282            ///
283            #[doc = concat!("let y = ", stringify!($float), "::from(true);")]
284            /// assert_eq!(y, 1.0);
285            $($(#[doc = $doctest_suffix])*)?
286            /// ```
287            #[inline]
288            fn from(small: bool) -> Self {
289                small as u8 as Self
290            }
291        }
292    };
293}
294
295// boolean -> float
296impl_float_from_bool!(
297    #[unstable(feature = "f16", issue = "116909")]
298    #[unstable_feature_bound(f16)]
299    f16;
300    doctest_prefix:
301    // rustdoc doesn't remove the conventional space after the `///`
302    ///# #![allow(unused_features)]
303    ///#![feature(f16)]
304    ///# #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
305    ///
306    doctest_suffix:
307    ///# }
308);
309impl_float_from_bool!(
310    #[stable(feature = "float_from_bool", since = "1.68.0")]
311    f32
312);
313impl_float_from_bool!(
314    #[stable(feature = "float_from_bool", since = "1.68.0")]
315    f64
316);
317impl_float_from_bool!(
318    #[unstable(feature = "f128", issue = "116909")]
319    #[unstable_feature_bound(f128)]
320    f128;
321    doctest_prefix:
322    ///# #![allow(unused_features)]
323    ///#![feature(f128)]
324    ///# #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
325    ///
326    doctest_suffix:
327    ///# }
328);
329
330// no possible bounds violation
331macro_rules! impl_try_from_unbounded {
332    ($source:ty => $($target:ty),+) => {$(
333        #[stable(feature = "try_from", since = "1.34.0")]
334        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
335        const impl TryFrom<$source> for $target {
336            type Error = TryFromIntError;
337
338            /// Tries to create the target number type from a source
339            /// number type. This never returns an error.
340            #[inline]
341            fn try_from(value: $source) -> Result<Self, Self::Error> {
342                Ok(value as Self)
343            }
344        }
345    )*}
346}
347
348// only negative bounds
349macro_rules! impl_try_from_lower_bounded {
350    ($source:ty => $($target:ty),+) => {$(
351        #[stable(feature = "try_from", since = "1.34.0")]
352        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
353        const impl TryFrom<$source> for $target {
354            type Error = TryFromIntError;
355
356            /// Tries to create the target number type from a source
357            /// number type. This returns an error if the source value
358            #[doc = concat!("is less than [`", stringify!($target), "::MIN`].")]
359            #[inline]
360            fn try_from(u: $source) -> Result<Self, Self::Error> {
361                if u >= 0 {
362                    Ok(u as Self)
363                } else {
364                    Err(TryFromIntError(IntErrorKind::NegOverflow))
365                }
366            }
367        }
368    )*}
369}
370
371// unsigned to signed (only positive bound)
372macro_rules! impl_try_from_upper_bounded {
373    ($source:ty => $($target:ty),+) => {$(
374        #[stable(feature = "try_from", since = "1.34.0")]
375        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
376        const impl TryFrom<$source> for $target {
377            type Error = TryFromIntError;
378
379            /// Tries to create the target number type from a source
380            /// number type. This returns an error if the source value
381            #[doc = concat!("is greater than [`", stringify!($target), "::MAX`].")]
382            #[inline]
383            fn try_from(u: $source) -> Result<Self, Self::Error> {
384                if u > (Self::MAX as $source) {
385                    Err(TryFromIntError(IntErrorKind::PosOverflow))
386                } else {
387                    Ok(u as Self)
388                }
389            }
390        }
391    )*}
392}
393
394// all other cases
395macro_rules! impl_try_from_both_bounded {
396    ($source:ty => $($target:ty),+) => {$(
397        #[stable(feature = "try_from", since = "1.34.0")]
398        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
399        const impl TryFrom<$source> for $target {
400            type Error = TryFromIntError;
401
402            /// Tries to create the target number type from a source
403            /// number type. This returns an error if the source value
404            /// is outside of the range of the target type.
405            #[inline]
406            fn try_from(u: $source) -> Result<Self, Self::Error> {
407                let min = Self::MIN as $source;
408                let max = Self::MAX as $source;
409                if u < min {
410                    Err(TryFromIntError(IntErrorKind::NegOverflow))
411                } else if u > max {
412                    Err(TryFromIntError(IntErrorKind::PosOverflow))
413                } else {
414                    Ok(u as Self)
415                }
416            }
417        }
418    )*}
419}
420
421/// Implement `TryFrom<integer>` for `bool`
422macro_rules! impl_try_from_integer_for_bool {
423    ($signedness:ident $($int:ty)+) => {$(
424        #[stable(feature = "bool_try_from_int", since = "1.95.0")]
425        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
426        const impl TryFrom<$int> for bool {
427            type Error = TryFromIntError;
428
429            /// Tries to create a bool from an integer type.
430            /// Returns an error if the integer is not 0 or 1.
431            ///
432            /// # Examples
433            ///
434            /// ```
435            #[doc = concat!("assert_eq!(bool::try_from(0_", stringify!($int), "), Ok(false));")]
436            ///
437            #[doc = concat!("assert_eq!(bool::try_from(1_", stringify!($int), "), Ok(true));")]
438            ///
439            #[doc = concat!("assert!(bool::try_from(2_", stringify!($int), ").is_err());")]
440            /// ```
441            #[inline]
442            fn try_from(i: $int) -> Result<Self, Self::Error> {
443                sign_dependent_expr!{
444                    $signedness ?
445                    if signed {
446                        match i {
447                            0 => Ok(false),
448                            1 => Ok(true),
449                            ..0 => Err(TryFromIntError(IntErrorKind::NegOverflow)),
450                            2.. => Err(TryFromIntError(IntErrorKind::PosOverflow)),
451                        }
452                    }
453                    if unsigned {
454                        match i {
455                            0 => Ok(false),
456                            1 => Ok(true),
457                            2.. => Err(TryFromIntError(IntErrorKind::PosOverflow)),
458                        }
459                    }
460                }
461            }
462        }
463    )*}
464}
465
466macro_rules! rev {
467    ($mac:ident, $source:ty => $($target:ty),+) => {$(
468        $mac!($target => $source);
469    )*}
470}
471
472// integer -> bool
473impl_try_from_integer_for_bool!(unsigned u128 u64 u32 u16 u8);
474impl_try_from_integer_for_bool!(signed i128 i64 i32 i16 i8);
475
476// unsigned integer -> unsigned integer
477impl_try_from_upper_bounded!(u16 => u8);
478impl_try_from_upper_bounded!(u32 => u8, u16);
479impl_try_from_upper_bounded!(u64 => u8, u16, u32);
480impl_try_from_upper_bounded!(u128 => u8, u16, u32, u64);
481
482// signed integer -> signed integer
483impl_try_from_both_bounded!(i16 => i8);
484impl_try_from_both_bounded!(i32 => i8, i16);
485impl_try_from_both_bounded!(i64 => i8, i16, i32);
486impl_try_from_both_bounded!(i128 => i8, i16, i32, i64);
487
488// unsigned integer -> signed integer
489impl_try_from_upper_bounded!(u8 => i8);
490impl_try_from_upper_bounded!(u16 => i8, i16);
491impl_try_from_upper_bounded!(u32 => i8, i16, i32);
492impl_try_from_upper_bounded!(u64 => i8, i16, i32, i64);
493impl_try_from_upper_bounded!(u128 => i8, i16, i32, i64, i128);
494
495// signed integer -> unsigned integer
496impl_try_from_lower_bounded!(i8 => u8, u16, u32, u64, u128);
497impl_try_from_both_bounded!(i16 => u8);
498impl_try_from_lower_bounded!(i16 => u16, u32, u64, u128);
499impl_try_from_both_bounded!(i32 => u8, u16);
500impl_try_from_lower_bounded!(i32 => u32, u64, u128);
501impl_try_from_both_bounded!(i64 => u8, u16, u32);
502impl_try_from_lower_bounded!(i64 => u64, u128);
503impl_try_from_both_bounded!(i128 => u8, u16, u32, u64);
504impl_try_from_lower_bounded!(i128 => u128);
505
506// usize/isize
507impl_try_from_upper_bounded!(usize => isize);
508impl_try_from_lower_bounded!(isize => usize);
509
510#[cfg(target_pointer_width = "16")]
511mod ptr_try_from_impls {
512    use super::{IntErrorKind, TryFromIntError};
513
514    impl_try_from_upper_bounded!(usize => u8);
515    impl_try_from_unbounded!(usize => u16, u32, u64, u128);
516    impl_try_from_upper_bounded!(usize => i8, i16);
517    impl_try_from_unbounded!(usize => i32, i64, i128);
518
519    impl_try_from_both_bounded!(isize => u8);
520    impl_try_from_lower_bounded!(isize => u16, u32, u64, u128);
521    impl_try_from_both_bounded!(isize => i8);
522    impl_try_from_unbounded!(isize => i16, i32, i64, i128);
523
524    rev!(impl_try_from_upper_bounded, usize => u32, u64, u128);
525    rev!(impl_try_from_lower_bounded, usize => i8, i16);
526    rev!(impl_try_from_both_bounded, usize => i32, i64, i128);
527
528    rev!(impl_try_from_upper_bounded, isize => u16, u32, u64, u128);
529    rev!(impl_try_from_both_bounded, isize => i32, i64, i128);
530}
531
532#[cfg(target_pointer_width = "32")]
533mod ptr_try_from_impls {
534    use super::{IntErrorKind, TryFromIntError};
535
536    impl_try_from_upper_bounded!(usize => u8, u16);
537    impl_try_from_unbounded!(usize => u32, u64, u128);
538    impl_try_from_upper_bounded!(usize => i8, i16, i32);
539    impl_try_from_unbounded!(usize => i64, i128);
540
541    impl_try_from_both_bounded!(isize => u8, u16);
542    impl_try_from_lower_bounded!(isize => u32, u64, u128);
543    impl_try_from_both_bounded!(isize => i8, i16);
544    impl_try_from_unbounded!(isize => i32, i64, i128);
545
546    rev!(impl_try_from_unbounded, usize => u32);
547    rev!(impl_try_from_upper_bounded, usize => u64, u128);
548    rev!(impl_try_from_lower_bounded, usize => i8, i16, i32);
549    rev!(impl_try_from_both_bounded, usize => i64, i128);
550
551    rev!(impl_try_from_unbounded, isize => u16);
552    rev!(impl_try_from_upper_bounded, isize => u32, u64, u128);
553    rev!(impl_try_from_unbounded, isize => i32);
554    rev!(impl_try_from_both_bounded, isize => i64, i128);
555}
556
557#[cfg(target_pointer_width = "64")]
558mod ptr_try_from_impls {
559    use super::{IntErrorKind, TryFromIntError};
560
561    impl_try_from_upper_bounded!(usize => u8, u16, u32);
562    impl_try_from_unbounded!(usize => u64, u128);
563    impl_try_from_upper_bounded!(usize => i8, i16, i32, i64);
564    impl_try_from_unbounded!(usize => i128);
565
566    impl_try_from_both_bounded!(isize => u8, u16, u32);
567    impl_try_from_lower_bounded!(isize => u64, u128);
568    impl_try_from_both_bounded!(isize => i8, i16, i32);
569    impl_try_from_unbounded!(isize => i64, i128);
570
571    rev!(impl_try_from_unbounded, usize => u32, u64);
572    rev!(impl_try_from_upper_bounded, usize => u128);
573    rev!(impl_try_from_lower_bounded, usize => i8, i16, i32, i64);
574    rev!(impl_try_from_both_bounded, usize => i128);
575
576    rev!(impl_try_from_unbounded, isize => u16, u32);
577    rev!(impl_try_from_upper_bounded, isize => u64, u128);
578    rev!(impl_try_from_unbounded, isize => i32, i64);
579    rev!(impl_try_from_both_bounded, isize => i128);
580}
581
582// Conversion traits for non-zero integer types
583use crate::num::NonZero;
584
585macro_rules! impl_nonzero_int_from_nonzero_int {
586    ($Small:ty => $Large:ty) => {
587        #[stable(feature = "nz_int_conv", since = "1.41.0")]
588        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
589        const impl From<NonZero<$Small>> for NonZero<$Large> {
590            // Rustdocs on the impl block show a "[+] show undocumented items" toggle.
591            // Rustdocs on functions do not.
592            #[doc = concat!("Converts <code>[NonZero]\\<[", stringify!($Small), "]></code> ")]
593            #[doc = concat!("to <code>[NonZero]\\<[", stringify!($Large), "]></code> losslessly.")]
594            #[inline]
595            fn from(small: NonZero<$Small>) -> Self {
596                // SAFETY: input type guarantees the value is non-zero
597                unsafe { Self::new_unchecked(From::from(small.get())) }
598            }
599        }
600    };
601}
602
603// non-zero unsigned integer -> non-zero unsigned integer
604impl_nonzero_int_from_nonzero_int!(u8 => u16);
605impl_nonzero_int_from_nonzero_int!(u8 => u32);
606impl_nonzero_int_from_nonzero_int!(u8 => u64);
607impl_nonzero_int_from_nonzero_int!(u8 => u128);
608impl_nonzero_int_from_nonzero_int!(u8 => usize);
609impl_nonzero_int_from_nonzero_int!(u16 => u32);
610impl_nonzero_int_from_nonzero_int!(u16 => u64);
611impl_nonzero_int_from_nonzero_int!(u16 => u128);
612impl_nonzero_int_from_nonzero_int!(u16 => usize);
613impl_nonzero_int_from_nonzero_int!(u32 => u64);
614impl_nonzero_int_from_nonzero_int!(u32 => u128);
615impl_nonzero_int_from_nonzero_int!(u64 => u128);
616
617// non-zero signed integer -> non-zero signed integer
618impl_nonzero_int_from_nonzero_int!(i8 => i16);
619impl_nonzero_int_from_nonzero_int!(i8 => i32);
620impl_nonzero_int_from_nonzero_int!(i8 => i64);
621impl_nonzero_int_from_nonzero_int!(i8 => i128);
622impl_nonzero_int_from_nonzero_int!(i8 => isize);
623impl_nonzero_int_from_nonzero_int!(i16 => i32);
624impl_nonzero_int_from_nonzero_int!(i16 => i64);
625impl_nonzero_int_from_nonzero_int!(i16 => i128);
626impl_nonzero_int_from_nonzero_int!(i16 => isize);
627impl_nonzero_int_from_nonzero_int!(i32 => i64);
628impl_nonzero_int_from_nonzero_int!(i32 => i128);
629impl_nonzero_int_from_nonzero_int!(i64 => i128);
630
631// non-zero unsigned -> non-zero signed integer
632impl_nonzero_int_from_nonzero_int!(u8 => i16);
633impl_nonzero_int_from_nonzero_int!(u8 => i32);
634impl_nonzero_int_from_nonzero_int!(u8 => i64);
635impl_nonzero_int_from_nonzero_int!(u8 => i128);
636impl_nonzero_int_from_nonzero_int!(u8 => isize);
637impl_nonzero_int_from_nonzero_int!(u16 => i32);
638impl_nonzero_int_from_nonzero_int!(u16 => i64);
639impl_nonzero_int_from_nonzero_int!(u16 => i128);
640impl_nonzero_int_from_nonzero_int!(u32 => i64);
641impl_nonzero_int_from_nonzero_int!(u32 => i128);
642impl_nonzero_int_from_nonzero_int!(u64 => i128);
643
644macro_rules! impl_nonzero_int_try_from_int {
645    ($Int:ty) => {
646        #[stable(feature = "nzint_try_from_int_conv", since = "1.46.0")]
647        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
648        const impl TryFrom<$Int> for NonZero<$Int> {
649            type Error = TryFromIntError;
650
651            // Rustdocs on the impl block show a "[+] show undocumented items" toggle.
652            // Rustdocs on functions do not.
653            #[doc = concat!("Attempts to convert [`", stringify!($Int), "`] ")]
654            #[doc = concat!("to <code>[NonZero]\\<[", stringify!($Int), "]></code>.")]
655            #[inline]
656            fn try_from(value: $Int) -> Result<Self, Self::Error> {
657                Self::new(value).ok_or(TryFromIntError(IntErrorKind::Zero))
658            }
659        }
660    };
661}
662
663// integer -> non-zero integer
664impl_nonzero_int_try_from_int!(u8);
665impl_nonzero_int_try_from_int!(u16);
666impl_nonzero_int_try_from_int!(u32);
667impl_nonzero_int_try_from_int!(u64);
668impl_nonzero_int_try_from_int!(u128);
669impl_nonzero_int_try_from_int!(usize);
670impl_nonzero_int_try_from_int!(i8);
671impl_nonzero_int_try_from_int!(i16);
672impl_nonzero_int_try_from_int!(i32);
673impl_nonzero_int_try_from_int!(i64);
674impl_nonzero_int_try_from_int!(i128);
675impl_nonzero_int_try_from_int!(isize);
676
677macro_rules! impl_nonzero_int_try_from_nonzero_int {
678    ($source:ty => $($target:ty),+) => {$(
679        #[stable(feature = "nzint_try_from_nzint_conv", since = "1.49.0")]
680        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
681        const impl TryFrom<NonZero<$source>> for NonZero<$target> {
682            type Error = TryFromIntError;
683
684            // Rustdocs on the impl block show a "[+] show undocumented items" toggle.
685            // Rustdocs on functions do not.
686            #[doc = concat!("Attempts to convert <code>[NonZero]\\<[", stringify!($source), "]></code> ")]
687            #[doc = concat!("to <code>[NonZero]\\<[", stringify!($target), "]></code>.")]
688            #[inline]
689            fn try_from(value: NonZero<$source>) -> Result<Self, Self::Error> {
690                // SAFETY: Input is guaranteed to be non-zero.
691                Ok(unsafe { Self::new_unchecked(<$target>::try_from(value.get())?) })
692            }
693        }
694    )*};
695}
696
697// unsigned non-zero integer -> unsigned non-zero integer
698impl_nonzero_int_try_from_nonzero_int!(u16 => u8);
699impl_nonzero_int_try_from_nonzero_int!(u32 => u8, u16, usize);
700impl_nonzero_int_try_from_nonzero_int!(u64 => u8, u16, u32, usize);
701impl_nonzero_int_try_from_nonzero_int!(u128 => u8, u16, u32, u64, usize);
702impl_nonzero_int_try_from_nonzero_int!(usize => u8, u16, u32, u64, u128);
703
704// signed non-zero integer -> signed non-zero integer
705impl_nonzero_int_try_from_nonzero_int!(i16 => i8);
706impl_nonzero_int_try_from_nonzero_int!(i32 => i8, i16, isize);
707impl_nonzero_int_try_from_nonzero_int!(i64 => i8, i16, i32, isize);
708impl_nonzero_int_try_from_nonzero_int!(i128 => i8, i16, i32, i64, isize);
709impl_nonzero_int_try_from_nonzero_int!(isize => i8, i16, i32, i64, i128);
710
711// unsigned non-zero integer -> signed non-zero integer
712impl_nonzero_int_try_from_nonzero_int!(u8 => i8);
713impl_nonzero_int_try_from_nonzero_int!(u16 => i8, i16, isize);
714impl_nonzero_int_try_from_nonzero_int!(u32 => i8, i16, i32, isize);
715impl_nonzero_int_try_from_nonzero_int!(u64 => i8, i16, i32, i64, isize);
716impl_nonzero_int_try_from_nonzero_int!(u128 => i8, i16, i32, i64, i128, isize);
717impl_nonzero_int_try_from_nonzero_int!(usize => i8, i16, i32, i64, i128, isize);
718
719// signed non-zero integer -> unsigned non-zero integer
720impl_nonzero_int_try_from_nonzero_int!(i8 => u8, u16, u32, u64, u128, usize);
721impl_nonzero_int_try_from_nonzero_int!(i16 => u8, u16, u32, u64, u128, usize);
722impl_nonzero_int_try_from_nonzero_int!(i32 => u8, u16, u32, u64, u128, usize);
723impl_nonzero_int_try_from_nonzero_int!(i64 => u8, u16, u32, u64, u128, usize);
724impl_nonzero_int_try_from_nonzero_int!(i128 => u8, u16, u32, u64, u128, usize);
725impl_nonzero_int_try_from_nonzero_int!(isize => u8, u16, u32, u64, u128, usize);
726
727/// Conversion between integers, wrapping around or saturating at the target type's boundaries.
728#[unstable(feature = "integer_casts", issue = "157388")]
729#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
730pub impl(self) const trait BoundedCastFromInt<T>: Sized {
731    /// Converts `value` to this type, wrapping around at the boundary of the type.
732    #[unstable(feature = "integer_casts", issue = "157388")]
733    fn wrapping_cast_from(value: T) -> Self;
734
735    /// Converts `value` to this type, saturating at the numeric bounds instead of overflowing.
736    #[unstable(feature = "integer_casts", issue = "157388")]
737    fn saturating_cast_from(value: T) -> Self;
738}
739
740/// Fallible conversion between integers.
741#[unstable(feature = "integer_casts", issue = "157388")]
742#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
743pub impl(self) const trait CheckedCastFromInt<T>: Sized {
744    /// Converts `value` to this type, returning `None` if overflow would have occurred.
745    #[unstable(feature = "integer_casts", issue = "157388")]
746    fn checked_cast_from(value: T) -> Option<Self>;
747
748    /// Converts `value` to this type, assuming overflow cannot occur.
749    ///
750    /// # Safety
751    ///
752    /// This results in undefined behavior when `value` will overflow when
753    /// converted to this type.
754    #[unstable(feature = "integer_casts", issue = "157388")]
755    unsafe fn unchecked_cast_from(value: T) -> Self;
756
757    /// Converts `value` to this type, panicking on overflow.
758    ///
759    /// # Panics
760    ///
761    /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
762    #[unstable(feature = "integer_casts", issue = "157388")]
763    fn strict_cast_from(value: T) -> Self;
764}
765
766macro_rules! impl_int_cast {
767    ($Src:ty as [$($Dst:ty),*]) => {$(
768        #[unstable(feature = "integer_casts", issue = "157388")]
769        #[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
770        const impl CheckedCastFromInt<$Src> for $Dst {
771            #[inline]
772            fn checked_cast_from(value: $Src) -> Option<Self> {
773                value.try_into().ok()
774            }
775
776            #[inline(always)]
777            unsafe fn unchecked_cast_from(value: $Src) -> Self {
778                // SAFETY: the safety contract must be upheld by the caller.
779                unsafe { value.try_into().unwrap_unchecked() }
780            }
781
782            #[inline]
783            #[track_caller]
784            fn strict_cast_from(value: $Src) -> Self {
785                match value.try_into() {
786                    Ok(x) => x,
787                    Err(_) => core::num::imp::overflow_panic::cast_integer()
788                }
789            }
790        }
791
792        #[unstable(feature = "integer_casts", issue = "157388")]
793        #[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
794        const impl BoundedCastFromInt<$Src> for $Dst {
795            #[inline(always)]
796            fn wrapping_cast_from(value: $Src) -> Self {
797                value as Self
798            }
799
800            #[inline]
801            #[allow(unused_comparisons)]
802            #[allow(irrefutable_let_patterns)]
803            fn saturating_cast_from(value: $Src) -> Self {
804                if let Ok(x) = value.try_into() {
805                    return x;
806                }
807
808                if value < 0 { <$Dst>::MIN } else { <$Dst>::MAX }
809            }
810        }
811    )*};
812}
813
814macro_rules! impl_all_int_casts {
815    ([$($Src:ty),*]) => {$(
816        impl_int_cast!($Src as [u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize]);
817    )*};
818}
819
820impl_all_int_casts!([u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize]);