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