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