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