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