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            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        const impl 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, #[unstable(feature = "f16", issue = "116909")], #[unstable_feature_bound(f16)]);
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, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f128)]);
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, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f128)]);
148impl_from!(i32 => f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")]);
149impl_from!(i32 => f128, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f128)]);
150impl_from!(i64 => f128, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f128)]);
151
152// unsigned integer -> float
153impl_from!(u8 => f16, #[unstable(feature = "f16", issue = "116909")], #[unstable_feature_bound(f16)]);
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, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f128)]);
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, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f128)]);
160impl_from!(u32 => f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")]);
161impl_from!(u32 => f128, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f128)]);
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, #[unstable(feature = "f16", issue = "116909")], #[unstable_feature_bound(f16)]);
174// Also #[unstable(feature = "f16", issue = "116909")]:
175impl_from!(f16 => f128, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f16, f128)]);
176impl_from!(f32 => f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")]);
177impl_from!(f32 => f128, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f128)]);
178impl_from!(f64 => f128, #[unstable(feature = "f128", issue = "116909")], #[unstable_feature_bound(f128)]);
179
180macro_rules! impl_float_from_bool {
181    (
182        $(#[$attr:meta])*
183        $float:ty $(;
184            doctest_prefix: $(#[doc = $doctest_prefix:literal])*
185            doctest_suffix: $(#[doc = $doctest_suffix:literal])*
186        )?
187    ) => {
188        $(#[$attr])*
189        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
190            const impl From<bool> for $float {
191            #[doc = concat!("Converts a [`bool`] to [`", stringify!($float),"`] losslessly.")]
192            /// The resulting value is positive `0.0` for `false` and `1.0` for `true` values.
193            ///
194            /// # Examples
195            /// ```
196            $($(#[doc = $doctest_prefix])*)?
197            #[doc = concat!("let x = ", stringify!($float), "::from(false);")]
198            /// assert_eq!(x, 0.0);
199            /// assert!(x.is_sign_positive());
200            ///
201            #[doc = concat!("let y = ", stringify!($float), "::from(true);")]
202            /// assert_eq!(y, 1.0);
203            $($(#[doc = $doctest_suffix])*)?
204            /// ```
205            #[inline]
206            fn from(small: bool) -> Self {
207                small as u8 as Self
208            }
209        }
210    };
211}
212
213// boolean -> float
214impl_float_from_bool!(
215    #[unstable(feature = "f16", issue = "116909")]
216    #[unstable_feature_bound(f16)]
217    f16;
218    doctest_prefix:
219    // rustdoc doesn't remove the conventional space after the `///`
220    ///# #![allow(unused_features)]
221    ///#![feature(f16)]
222    ///# #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
223    ///
224    doctest_suffix:
225    ///# }
226);
227impl_float_from_bool!(
228    #[stable(feature = "float_from_bool", since = "1.68.0")]
229    f32
230);
231impl_float_from_bool!(
232    #[stable(feature = "float_from_bool", since = "1.68.0")]
233    f64
234);
235impl_float_from_bool!(
236    #[unstable(feature = "f128", issue = "116909")]
237    #[unstable_feature_bound(f128)]
238    f128;
239    doctest_prefix:
240    ///# #![allow(unused_features)]
241    ///#![feature(f128)]
242    ///# #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
243    ///
244    doctest_suffix:
245    ///# }
246);
247
248// no possible bounds violation
249macro_rules! impl_try_from_unbounded {
250    ($source:ty => $($target:ty),+) => {$(
251        #[stable(feature = "try_from", since = "1.34.0")]
252        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
253        const 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        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
272        const impl TryFrom<$source> for $target {
273            type Error = TryFromIntError;
274
275            /// Tries to create the target number type from a source
276            /// number type. This returns an error if the source value
277            /// is outside of the range of the target type.
278            #[inline]
279            fn try_from(u: $source) -> Result<Self, Self::Error> {
280                if u >= 0 {
281                    Ok(u as Self)
282                } else {
283                    Err(TryFromIntError(IntErrorKind::NegOverflow))
284                }
285            }
286        }
287    )*}
288}
289
290// unsigned to signed (only positive bound)
291macro_rules! impl_try_from_upper_bounded {
292    ($source:ty => $($target:ty),+) => {$(
293        #[stable(feature = "try_from", since = "1.34.0")]
294        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
295        const impl TryFrom<$source> for $target {
296            type Error = TryFromIntError;
297
298            /// Tries to create the target number type from a source
299            /// number type. This returns an error if the source value
300            /// is outside of the range of the target type.
301            #[inline]
302            fn try_from(u: $source) -> Result<Self, Self::Error> {
303                if u > (Self::MAX as $source) {
304                    Err(TryFromIntError(IntErrorKind::PosOverflow))
305                } else {
306                    Ok(u as Self)
307                }
308            }
309        }
310    )*}
311}
312
313// all other cases
314macro_rules! impl_try_from_both_bounded {
315    ($source:ty => $($target:ty),+) => {$(
316        #[stable(feature = "try_from", since = "1.34.0")]
317        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
318        const impl TryFrom<$source> for $target {
319            type Error = TryFromIntError;
320
321            /// Tries to create the target number type from a source
322            /// number type. This returns an error if the source value
323            /// is outside of the range of the target type.
324            #[inline]
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 {
329                    Err(TryFromIntError(IntErrorKind::NegOverflow))
330                } else if u > max {
331                    Err(TryFromIntError(IntErrorKind::PosOverflow))
332                } else {
333                    Ok(u as Self)
334                }
335            }
336        }
337    )*}
338}
339
340/// Implement `TryFrom<integer>` for `bool`
341macro_rules! impl_try_from_integer_for_bool {
342    ($signedness:ident $($int:ty)+) => {$(
343        #[stable(feature = "bool_try_from_int", since = "1.95.0")]
344        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
345        const impl TryFrom<$int> for bool {
346            type Error = TryFromIntError;
347
348            /// Tries to create a bool from an integer type.
349            /// Returns an error if the integer is not 0 or 1.
350            ///
351            /// # Examples
352            ///
353            /// ```
354            #[doc = concat!("assert_eq!(bool::try_from(0_", stringify!($int), "), Ok(false));")]
355            ///
356            #[doc = concat!("assert_eq!(bool::try_from(1_", stringify!($int), "), Ok(true));")]
357            ///
358            #[doc = concat!("assert!(bool::try_from(2_", stringify!($int), ").is_err());")]
359            /// ```
360            #[inline]
361            fn try_from(i: $int) -> Result<Self, Self::Error> {
362                sign_dependent_expr!{
363                    $signedness ?
364                    if signed {
365                        match i {
366                            0 => Ok(false),
367                            1 => Ok(true),
368                            ..0 => Err(TryFromIntError(IntErrorKind::NegOverflow)),
369                            2.. => Err(TryFromIntError(IntErrorKind::PosOverflow)),
370                        }
371                    }
372                    if unsigned {
373                        match i {
374                            0 => Ok(false),
375                            1 => Ok(true),
376                            2.. => Err(TryFromIntError(IntErrorKind::PosOverflow)),
377                        }
378                    }
379                }
380            }
381        }
382    )*}
383}
384
385macro_rules! rev {
386    ($mac:ident, $source:ty => $($target:ty),+) => {$(
387        $mac!($target => $source);
388    )*}
389}
390
391// integer -> bool
392impl_try_from_integer_for_bool!(unsigned u128 u64 u32 u16 u8);
393impl_try_from_integer_for_bool!(signed i128 i64 i32 i16 i8);
394
395// unsigned integer -> unsigned integer
396impl_try_from_upper_bounded!(u16 => u8);
397impl_try_from_upper_bounded!(u32 => u8, u16);
398impl_try_from_upper_bounded!(u64 => u8, u16, u32);
399impl_try_from_upper_bounded!(u128 => u8, u16, u32, u64);
400
401// signed integer -> signed integer
402impl_try_from_both_bounded!(i16 => i8);
403impl_try_from_both_bounded!(i32 => i8, i16);
404impl_try_from_both_bounded!(i64 => i8, i16, i32);
405impl_try_from_both_bounded!(i128 => i8, i16, i32, i64);
406
407// unsigned integer -> signed integer
408impl_try_from_upper_bounded!(u8 => i8);
409impl_try_from_upper_bounded!(u16 => i8, i16);
410impl_try_from_upper_bounded!(u32 => i8, i16, i32);
411impl_try_from_upper_bounded!(u64 => i8, i16, i32, i64);
412impl_try_from_upper_bounded!(u128 => i8, i16, i32, i64, i128);
413
414// signed integer -> unsigned integer
415impl_try_from_lower_bounded!(i8 => u8, u16, u32, u64, u128);
416impl_try_from_both_bounded!(i16 => u8);
417impl_try_from_lower_bounded!(i16 => u16, u32, u64, u128);
418impl_try_from_both_bounded!(i32 => u8, u16);
419impl_try_from_lower_bounded!(i32 => u32, u64, u128);
420impl_try_from_both_bounded!(i64 => u8, u16, u32);
421impl_try_from_lower_bounded!(i64 => u64, u128);
422impl_try_from_both_bounded!(i128 => u8, u16, u32, u64);
423impl_try_from_lower_bounded!(i128 => u128);
424
425// usize/isize
426impl_try_from_upper_bounded!(usize => isize);
427impl_try_from_lower_bounded!(isize => usize);
428
429#[cfg(target_pointer_width = "16")]
430mod ptr_try_from_impls {
431    use super::{IntErrorKind, TryFromIntError};
432
433    impl_try_from_upper_bounded!(usize => u8);
434    impl_try_from_unbounded!(usize => u16, u32, u64, u128);
435    impl_try_from_upper_bounded!(usize => i8, i16);
436    impl_try_from_unbounded!(usize => i32, i64, i128);
437
438    impl_try_from_both_bounded!(isize => u8);
439    impl_try_from_lower_bounded!(isize => u16, u32, u64, u128);
440    impl_try_from_both_bounded!(isize => i8);
441    impl_try_from_unbounded!(isize => i16, i32, i64, i128);
442
443    rev!(impl_try_from_upper_bounded, usize => u32, u64, u128);
444    rev!(impl_try_from_lower_bounded, usize => i8, i16);
445    rev!(impl_try_from_both_bounded, usize => i32, i64, i128);
446
447    rev!(impl_try_from_upper_bounded, isize => u16, u32, u64, u128);
448    rev!(impl_try_from_both_bounded, isize => i32, i64, i128);
449}
450
451#[cfg(target_pointer_width = "32")]
452mod ptr_try_from_impls {
453    use super::{IntErrorKind, TryFromIntError};
454
455    impl_try_from_upper_bounded!(usize => u8, u16);
456    impl_try_from_unbounded!(usize => u32, u64, u128);
457    impl_try_from_upper_bounded!(usize => i8, i16, i32);
458    impl_try_from_unbounded!(usize => i64, i128);
459
460    impl_try_from_both_bounded!(isize => u8, u16);
461    impl_try_from_lower_bounded!(isize => u32, u64, u128);
462    impl_try_from_both_bounded!(isize => i8, i16);
463    impl_try_from_unbounded!(isize => i32, i64, i128);
464
465    rev!(impl_try_from_unbounded, usize => u32);
466    rev!(impl_try_from_upper_bounded, usize => u64, u128);
467    rev!(impl_try_from_lower_bounded, usize => i8, i16, i32);
468    rev!(impl_try_from_both_bounded, usize => i64, i128);
469
470    rev!(impl_try_from_unbounded, isize => u16);
471    rev!(impl_try_from_upper_bounded, isize => u32, u64, u128);
472    rev!(impl_try_from_unbounded, isize => i32);
473    rev!(impl_try_from_both_bounded, isize => i64, i128);
474}
475
476#[cfg(target_pointer_width = "64")]
477mod ptr_try_from_impls {
478    use super::{IntErrorKind, TryFromIntError};
479
480    impl_try_from_upper_bounded!(usize => u8, u16, u32);
481    impl_try_from_unbounded!(usize => u64, u128);
482    impl_try_from_upper_bounded!(usize => i8, i16, i32, i64);
483    impl_try_from_unbounded!(usize => i128);
484
485    impl_try_from_both_bounded!(isize => u8, u16, u32);
486    impl_try_from_lower_bounded!(isize => u64, u128);
487    impl_try_from_both_bounded!(isize => i8, i16, i32);
488    impl_try_from_unbounded!(isize => i64, i128);
489
490    rev!(impl_try_from_unbounded, usize => u32, u64);
491    rev!(impl_try_from_upper_bounded, usize => u128);
492    rev!(impl_try_from_lower_bounded, usize => i8, i16, i32, i64);
493    rev!(impl_try_from_both_bounded, usize => i128);
494
495    rev!(impl_try_from_unbounded, isize => u16, u32);
496    rev!(impl_try_from_upper_bounded, isize => u64, u128);
497    rev!(impl_try_from_unbounded, isize => i32, i64);
498    rev!(impl_try_from_both_bounded, isize => i128);
499}
500
501// Conversion traits for non-zero integer types
502use crate::num::NonZero;
503
504macro_rules! impl_nonzero_int_from_nonzero_int {
505    ($Small:ty => $Large:ty) => {
506        #[stable(feature = "nz_int_conv", since = "1.41.0")]
507        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
508        const impl From<NonZero<$Small>> for NonZero<$Large> {
509            // Rustdocs on the impl block show a "[+] show undocumented items" toggle.
510            // Rustdocs on functions do not.
511            #[doc = concat!("Converts <code>[NonZero]\\<[", stringify!($Small), "]></code> ")]
512            #[doc = concat!("to <code>[NonZero]\\<[", stringify!($Large), "]></code> losslessly.")]
513            #[inline]
514            fn from(small: NonZero<$Small>) -> Self {
515                // SAFETY: input type guarantees the value is non-zero
516                unsafe { Self::new_unchecked(From::from(small.get())) }
517            }
518        }
519    };
520}
521
522// non-zero unsigned integer -> non-zero unsigned integer
523impl_nonzero_int_from_nonzero_int!(u8 => u16);
524impl_nonzero_int_from_nonzero_int!(u8 => u32);
525impl_nonzero_int_from_nonzero_int!(u8 => u64);
526impl_nonzero_int_from_nonzero_int!(u8 => u128);
527impl_nonzero_int_from_nonzero_int!(u8 => usize);
528impl_nonzero_int_from_nonzero_int!(u16 => u32);
529impl_nonzero_int_from_nonzero_int!(u16 => u64);
530impl_nonzero_int_from_nonzero_int!(u16 => u128);
531impl_nonzero_int_from_nonzero_int!(u16 => usize);
532impl_nonzero_int_from_nonzero_int!(u32 => u64);
533impl_nonzero_int_from_nonzero_int!(u32 => u128);
534impl_nonzero_int_from_nonzero_int!(u64 => u128);
535
536// non-zero signed integer -> non-zero signed integer
537impl_nonzero_int_from_nonzero_int!(i8 => i16);
538impl_nonzero_int_from_nonzero_int!(i8 => i32);
539impl_nonzero_int_from_nonzero_int!(i8 => i64);
540impl_nonzero_int_from_nonzero_int!(i8 => i128);
541impl_nonzero_int_from_nonzero_int!(i8 => isize);
542impl_nonzero_int_from_nonzero_int!(i16 => i32);
543impl_nonzero_int_from_nonzero_int!(i16 => i64);
544impl_nonzero_int_from_nonzero_int!(i16 => i128);
545impl_nonzero_int_from_nonzero_int!(i16 => isize);
546impl_nonzero_int_from_nonzero_int!(i32 => i64);
547impl_nonzero_int_from_nonzero_int!(i32 => i128);
548impl_nonzero_int_from_nonzero_int!(i64 => i128);
549
550// non-zero unsigned -> non-zero signed integer
551impl_nonzero_int_from_nonzero_int!(u8 => i16);
552impl_nonzero_int_from_nonzero_int!(u8 => i32);
553impl_nonzero_int_from_nonzero_int!(u8 => i64);
554impl_nonzero_int_from_nonzero_int!(u8 => i128);
555impl_nonzero_int_from_nonzero_int!(u8 => isize);
556impl_nonzero_int_from_nonzero_int!(u16 => i32);
557impl_nonzero_int_from_nonzero_int!(u16 => i64);
558impl_nonzero_int_from_nonzero_int!(u16 => i128);
559impl_nonzero_int_from_nonzero_int!(u32 => i64);
560impl_nonzero_int_from_nonzero_int!(u32 => i128);
561impl_nonzero_int_from_nonzero_int!(u64 => i128);
562
563macro_rules! impl_nonzero_int_try_from_int {
564    ($Int:ty) => {
565        #[stable(feature = "nzint_try_from_int_conv", since = "1.46.0")]
566        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
567        const impl TryFrom<$Int> for NonZero<$Int> {
568            type Error = TryFromIntError;
569
570            // Rustdocs on the impl block show a "[+] show undocumented items" toggle.
571            // Rustdocs on functions do not.
572            #[doc = concat!("Attempts to convert [`", stringify!($Int), "`] ")]
573            #[doc = concat!("to <code>[NonZero]\\<[", stringify!($Int), "]></code>.")]
574            #[inline]
575            fn try_from(value: $Int) -> Result<Self, Self::Error> {
576                Self::new(value).ok_or(TryFromIntError(IntErrorKind::Zero))
577            }
578        }
579    };
580}
581
582// integer -> non-zero integer
583impl_nonzero_int_try_from_int!(u8);
584impl_nonzero_int_try_from_int!(u16);
585impl_nonzero_int_try_from_int!(u32);
586impl_nonzero_int_try_from_int!(u64);
587impl_nonzero_int_try_from_int!(u128);
588impl_nonzero_int_try_from_int!(usize);
589impl_nonzero_int_try_from_int!(i8);
590impl_nonzero_int_try_from_int!(i16);
591impl_nonzero_int_try_from_int!(i32);
592impl_nonzero_int_try_from_int!(i64);
593impl_nonzero_int_try_from_int!(i128);
594impl_nonzero_int_try_from_int!(isize);
595
596macro_rules! impl_nonzero_int_try_from_nonzero_int {
597    ($source:ty => $($target:ty),+) => {$(
598        #[stable(feature = "nzint_try_from_nzint_conv", since = "1.49.0")]
599        #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
600        const impl TryFrom<NonZero<$source>> for NonZero<$target> {
601            type Error = TryFromIntError;
602
603            // Rustdocs on the impl block show a "[+] show undocumented items" toggle.
604            // Rustdocs on functions do not.
605            #[doc = concat!("Attempts to convert <code>[NonZero]\\<[", stringify!($source), "]></code> ")]
606            #[doc = concat!("to <code>[NonZero]\\<[", stringify!($target), "]></code>.")]
607            #[inline]
608            fn try_from(value: NonZero<$source>) -> Result<Self, Self::Error> {
609                // SAFETY: Input is guaranteed to be non-zero.
610                Ok(unsafe { Self::new_unchecked(<$target>::try_from(value.get())?) })
611            }
612        }
613    )*};
614}
615
616// unsigned non-zero integer -> unsigned non-zero integer
617impl_nonzero_int_try_from_nonzero_int!(u16 => u8);
618impl_nonzero_int_try_from_nonzero_int!(u32 => u8, u16, usize);
619impl_nonzero_int_try_from_nonzero_int!(u64 => u8, u16, u32, usize);
620impl_nonzero_int_try_from_nonzero_int!(u128 => u8, u16, u32, u64, usize);
621impl_nonzero_int_try_from_nonzero_int!(usize => u8, u16, u32, u64, u128);
622
623// signed non-zero integer -> signed non-zero integer
624impl_nonzero_int_try_from_nonzero_int!(i16 => i8);
625impl_nonzero_int_try_from_nonzero_int!(i32 => i8, i16, isize);
626impl_nonzero_int_try_from_nonzero_int!(i64 => i8, i16, i32, isize);
627impl_nonzero_int_try_from_nonzero_int!(i128 => i8, i16, i32, i64, isize);
628impl_nonzero_int_try_from_nonzero_int!(isize => i8, i16, i32, i64, i128);
629
630// unsigned non-zero integer -> signed non-zero integer
631impl_nonzero_int_try_from_nonzero_int!(u8 => i8);
632impl_nonzero_int_try_from_nonzero_int!(u16 => i8, i16, isize);
633impl_nonzero_int_try_from_nonzero_int!(u32 => i8, i16, i32, isize);
634impl_nonzero_int_try_from_nonzero_int!(u64 => i8, i16, i32, i64, isize);
635impl_nonzero_int_try_from_nonzero_int!(u128 => i8, i16, i32, i64, i128, isize);
636impl_nonzero_int_try_from_nonzero_int!(usize => i8, i16, i32, i64, i128, isize);
637
638// signed non-zero integer -> unsigned non-zero integer
639impl_nonzero_int_try_from_nonzero_int!(i8 => u8, u16, u32, u64, u128, usize);
640impl_nonzero_int_try_from_nonzero_int!(i16 => u8, u16, u32, u64, u128, usize);
641impl_nonzero_int_try_from_nonzero_int!(i32 => u8, u16, u32, u64, u128, usize);
642impl_nonzero_int_try_from_nonzero_int!(i64 => u8, u16, u32, u64, u128, usize);
643impl_nonzero_int_try_from_nonzero_int!(i128 => u8, u16, u32, u64, u128, usize);
644impl_nonzero_int_try_from_nonzero_int!(isize => u8, u16, u32, u64, u128, usize);
645
646/// Conversion between integers, wrapping around or saturating at the target type's boundaries.
647#[unstable(feature = "integer_casts", issue = "157388")]
648#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
649pub impl(self) const trait BoundedCastFromInt<T>: Sized {
650    /// Converts `value` to this type, wrapping around at the boundary of the type.
651    #[unstable(feature = "integer_casts", issue = "157388")]
652    fn wrapping_cast_from(value: T) -> Self;
653
654    /// Converts `value` to this type, saturating at the numeric bounds instead of overflowing.
655    #[unstable(feature = "integer_casts", issue = "157388")]
656    fn saturating_cast_from(value: T) -> Self;
657}
658
659/// Fallible conversion between integers.
660#[unstable(feature = "integer_casts", issue = "157388")]
661#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
662pub impl(self) const trait CheckedCastFromInt<T>: Sized {
663    /// Converts `value` to this type, returning `None` if overflow would have occurred.
664    #[unstable(feature = "integer_casts", issue = "157388")]
665    fn checked_cast_from(value: T) -> Option<Self>;
666
667    /// Converts `value` to this type, assuming overflow cannot occur.
668    ///
669    /// # Safety
670    ///
671    /// This results in undefined behavior when `value` will overflow when
672    /// converted to this type.
673    #[unstable(feature = "integer_casts", issue = "157388")]
674    unsafe fn unchecked_cast_from(value: T) -> Self;
675
676    /// Converts `value` to this type, panicking on overflow.
677    ///
678    /// # Panics
679    ///
680    /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
681    #[unstable(feature = "integer_casts", issue = "157388")]
682    fn strict_cast_from(value: T) -> Self;
683}
684
685macro_rules! impl_int_cast {
686    ($Src:ty as [$($Dst:ty),*]) => {$(
687        #[unstable(feature = "integer_casts", issue = "157388")]
688        #[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
689        const impl CheckedCastFromInt<$Src> for $Dst {
690            #[inline]
691            fn checked_cast_from(value: $Src) -> Option<Self> {
692                value.try_into().ok()
693            }
694
695            #[inline(always)]
696            unsafe fn unchecked_cast_from(value: $Src) -> Self {
697                // SAFETY: the safety contract must be upheld by the caller.
698                unsafe { value.try_into().unwrap_unchecked() }
699            }
700
701            #[inline]
702            #[track_caller]
703            fn strict_cast_from(value: $Src) -> Self {
704                match value.try_into() {
705                    Ok(x) => x,
706                    Err(_) => core::num::imp::overflow_panic::cast_integer()
707                }
708            }
709        }
710
711        #[unstable(feature = "integer_casts", issue = "157388")]
712        #[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
713        const impl BoundedCastFromInt<$Src> for $Dst {
714            #[inline(always)]
715            fn wrapping_cast_from(value: $Src) -> Self {
716                value as Self
717            }
718
719            #[inline]
720            #[allow(unused_comparisons)]
721            #[allow(irrefutable_let_patterns)]
722            fn saturating_cast_from(value: $Src) -> Self {
723                if let Ok(x) = value.try_into() {
724                    return x;
725                }
726
727                if value < 0 { <$Dst>::MIN } else { <$Dst>::MAX }
728            }
729        }
730    )*};
731}
732
733macro_rules! impl_all_int_casts {
734    ([$($Src:ty),*]) => {$(
735        impl_int_cast!($Src as [u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize]);
736    )*};
737}
738
739impl_all_int_casts!([u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize]);