Skip to main content

core/convert/
num.rs

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