]> git.lizzy.rs Git - rust.git/blob - src/libcore/convert/num.rs
Rollup merge of #66881 - krishna-veerareddy:issue-66780-bool-ord-optimization, r...
[rust.git] / src / libcore / convert / num.rs
1 use super::{From, TryFrom};
2 use crate::num::TryFromIntError;
3
4 mod private {
5     /// This trait being unreachable from outside the crate
6     /// prevents other implementations of the `FloatToInt` trait,
7     /// which allows potentially adding more trait methods after the trait is `#[stable]`.
8     #[unstable(feature = "convert_float_to_int", issue = "67057")]
9     pub trait Sealed {}
10 }
11
12 /// Supporting trait for inherent methods of `f32` and `f64` such as `round_unchecked_to`.
13 /// Typically doesn’t need to be used directly.
14 #[unstable(feature = "convert_float_to_int", issue = "67057")]
15 pub trait FloatToInt<Int>: private::Sealed + Sized {
16     #[cfg(not(bootstrap))]
17     #[unstable(feature = "float_approx_unchecked_to", issue = "67058")]
18     #[doc(hidden)]
19     unsafe fn approx_unchecked(self) -> Int;
20 }
21
22 macro_rules! impl_float_to_int {
23     ( $Float: ident => $( $Int: ident )+ ) => {
24         #[unstable(feature = "convert_float_to_int", issue = "67057")]
25         impl private::Sealed for $Float {}
26         $(
27             #[unstable(feature = "convert_float_to_int", issue = "67057")]
28             impl FloatToInt<$Int> for $Float {
29                 #[cfg(not(bootstrap))]
30                 #[doc(hidden)]
31                 #[inline]
32                 unsafe fn approx_unchecked(self) -> $Int {
33                     crate::intrinsics::float_to_int_approx_unchecked(self)
34                 }
35             }
36         )+
37     }
38 }
39
40 impl_float_to_int!(f32 => u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize);
41 impl_float_to_int!(f64 => u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize);
42
43 // Conversion traits for primitive integer and float types
44 // Conversions T -> T are covered by a blanket impl and therefore excluded
45 // Some conversions from and to usize/isize are not implemented due to portability concerns
46 macro_rules! impl_from {
47     ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => {
48         #[$attr]
49         #[doc = $doc]
50         impl From<$Small> for $Large {
51             #[inline]
52             fn from(small: $Small) -> $Large {
53                 small as $Large
54             }
55         }
56     };
57     ($Small: ty, $Large: ty, #[$attr:meta]) => {
58         impl_from!($Small,
59                    $Large,
60                    #[$attr],
61                    concat!("Converts `",
62                            stringify!($Small),
63                            "` to `",
64                            stringify!($Large),
65                            "` losslessly."));
66     }
67 }
68
69 macro_rules! impl_from_bool {
70     ($target: ty, #[$attr:meta]) => {
71         impl_from!(bool, $target, #[$attr], concat!("Converts a `bool` to a `",
72             stringify!($target), "`. The resulting value is `0` for `false` and `1` for `true`
73 values.
74
75 # Examples
76
77 ```
78 assert_eq!(", stringify!($target), "::from(true), 1);
79 assert_eq!(", stringify!($target), "::from(false), 0);
80 ```"));
81     };
82 }
83
84 // Bool -> Any
85 impl_from_bool! { u8, #[stable(feature = "from_bool", since = "1.28.0")] }
86 impl_from_bool! { u16, #[stable(feature = "from_bool", since = "1.28.0")] }
87 impl_from_bool! { u32, #[stable(feature = "from_bool", since = "1.28.0")] }
88 impl_from_bool! { u64, #[stable(feature = "from_bool", since = "1.28.0")] }
89 impl_from_bool! { u128, #[stable(feature = "from_bool", since = "1.28.0")] }
90 impl_from_bool! { usize, #[stable(feature = "from_bool", since = "1.28.0")] }
91 impl_from_bool! { i8, #[stable(feature = "from_bool", since = "1.28.0")] }
92 impl_from_bool! { i16, #[stable(feature = "from_bool", since = "1.28.0")] }
93 impl_from_bool! { i32, #[stable(feature = "from_bool", since = "1.28.0")] }
94 impl_from_bool! { i64, #[stable(feature = "from_bool", since = "1.28.0")] }
95 impl_from_bool! { i128, #[stable(feature = "from_bool", since = "1.28.0")] }
96 impl_from_bool! { isize, #[stable(feature = "from_bool", since = "1.28.0")] }
97
98 // Unsigned -> Unsigned
99 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
100 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
101 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
102 impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] }
103 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
104 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
105 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
106 impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] }
107 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
108 impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] }
109 impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] }
110
111 // Signed -> Signed
112 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
113 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
114 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
115 impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] }
116 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
117 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
118 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
119 impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] }
120 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
121 impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] }
122 impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] }
123
124 // Unsigned -> Signed
125 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
126 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
127 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
128 impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] }
129 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
130 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
131 impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] }
132 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
133 impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] }
134 impl_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
139 impl_from! { u16, usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
140 impl_from! { u8, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
141 impl_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 256-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 // http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf
148
149 // Note: integers can only be represented with full precision in a float if
150 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
151 // Lossy float conversions are not implemented at this time.
152
153 // Signed -> Float
154 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
155 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
156 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
157 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
158 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
159
160 // Unsigned -> Float
161 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
162 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
163 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
164 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
165 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
166
167 // Float -> Float
168 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
169
170 // no possible bounds violation
171 macro_rules! try_from_unbounded {
172     ($source:ty, $($target:ty),*) => {$(
173         #[stable(feature = "try_from", since = "1.34.0")]
174         impl TryFrom<$source> for $target {
175             type Error = TryFromIntError;
176
177             /// Try to create the target number type from a source
178             /// number type. This returns an error if the source value
179             /// is outside of the range of the target type.
180             #[inline]
181             fn try_from(value: $source) -> Result<Self, Self::Error> {
182                 Ok(value as $target)
183             }
184         }
185     )*}
186 }
187
188 // only negative bounds
189 macro_rules! try_from_lower_bounded {
190     ($source:ty, $($target:ty),*) => {$(
191         #[stable(feature = "try_from", since = "1.34.0")]
192         impl TryFrom<$source> for $target {
193             type Error = TryFromIntError;
194
195             /// Try to create the target number type from a source
196             /// number type. This returns an error if the source value
197             /// is outside of the range of the target type.
198             #[inline]
199             fn try_from(u: $source) -> Result<$target, TryFromIntError> {
200                 if u >= 0 {
201                     Ok(u as $target)
202                 } else {
203                     Err(TryFromIntError(()))
204                 }
205             }
206         }
207     )*}
208 }
209
210 // unsigned to signed (only positive bound)
211 macro_rules! try_from_upper_bounded {
212     ($source:ty, $($target:ty),*) => {$(
213         #[stable(feature = "try_from", since = "1.34.0")]
214         impl TryFrom<$source> for $target {
215             type Error = TryFromIntError;
216
217             /// Try to create the target number type from a source
218             /// number type. This returns an error if the source value
219             /// is outside of the range of the target type.
220             #[inline]
221             fn try_from(u: $source) -> Result<$target, TryFromIntError> {
222                 if u > (<$target>::max_value() as $source) {
223                     Err(TryFromIntError(()))
224                 } else {
225                     Ok(u as $target)
226                 }
227             }
228         }
229     )*}
230 }
231
232 // all other cases
233 macro_rules! try_from_both_bounded {
234     ($source:ty, $($target:ty),*) => {$(
235         #[stable(feature = "try_from", since = "1.34.0")]
236         impl TryFrom<$source> for $target {
237             type Error = TryFromIntError;
238
239             /// Try to create the target number type from a source
240             /// number type. This returns an error if the source value
241             /// is outside of the range of the target type.
242             #[inline]
243             fn try_from(u: $source) -> Result<$target, TryFromIntError> {
244                 let min = <$target>::min_value() as $source;
245                 let max = <$target>::max_value() as $source;
246                 if u < min || u > max {
247                     Err(TryFromIntError(()))
248                 } else {
249                     Ok(u as $target)
250                 }
251             }
252         }
253     )*}
254 }
255
256 macro_rules! rev {
257     ($mac:ident, $source:ty, $($target:ty),*) => {$(
258         $mac!($target, $source);
259     )*}
260 }
261
262 // intra-sign conversions
263 try_from_upper_bounded!(u16, u8);
264 try_from_upper_bounded!(u32, u16, u8);
265 try_from_upper_bounded!(u64, u32, u16, u8);
266 try_from_upper_bounded!(u128, u64, u32, u16, u8);
267
268 try_from_both_bounded!(i16, i8);
269 try_from_both_bounded!(i32, i16, i8);
270 try_from_both_bounded!(i64, i32, i16, i8);
271 try_from_both_bounded!(i128, i64, i32, i16, i8);
272
273 // unsigned-to-signed
274 try_from_upper_bounded!(u8, i8);
275 try_from_upper_bounded!(u16, i8, i16);
276 try_from_upper_bounded!(u32, i8, i16, i32);
277 try_from_upper_bounded!(u64, i8, i16, i32, i64);
278 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
279
280 // signed-to-unsigned
281 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
282 try_from_lower_bounded!(i16, u16, u32, u64, u128);
283 try_from_lower_bounded!(i32, u32, u64, u128);
284 try_from_lower_bounded!(i64, u64, u128);
285 try_from_lower_bounded!(i128, u128);
286 try_from_both_bounded!(i16, u8);
287 try_from_both_bounded!(i32, u16, u8);
288 try_from_both_bounded!(i64, u32, u16, u8);
289 try_from_both_bounded!(i128, u64, u32, u16, u8);
290
291 // usize/isize
292 try_from_upper_bounded!(usize, isize);
293 try_from_lower_bounded!(isize, usize);
294
295 #[cfg(target_pointer_width = "16")]
296 mod ptr_try_from_impls {
297     use super::TryFromIntError;
298     use crate::convert::TryFrom;
299
300     try_from_upper_bounded!(usize, u8);
301     try_from_unbounded!(usize, u16, u32, u64, u128);
302     try_from_upper_bounded!(usize, i8, i16);
303     try_from_unbounded!(usize, i32, i64, i128);
304
305     try_from_both_bounded!(isize, u8);
306     try_from_lower_bounded!(isize, u16, u32, u64, u128);
307     try_from_both_bounded!(isize, i8);
308     try_from_unbounded!(isize, i16, i32, i64, i128);
309
310     rev!(try_from_upper_bounded, usize, u32, u64, u128);
311     rev!(try_from_lower_bounded, usize, i8, i16);
312     rev!(try_from_both_bounded, usize, i32, i64, i128);
313
314     rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
315     rev!(try_from_both_bounded, isize, i32, i64, i128);
316 }
317
318 #[cfg(target_pointer_width = "32")]
319 mod ptr_try_from_impls {
320     use super::TryFromIntError;
321     use crate::convert::TryFrom;
322
323     try_from_upper_bounded!(usize, u8, u16);
324     try_from_unbounded!(usize, u32, u64, u128);
325     try_from_upper_bounded!(usize, i8, i16, i32);
326     try_from_unbounded!(usize, i64, i128);
327
328     try_from_both_bounded!(isize, u8, u16);
329     try_from_lower_bounded!(isize, u32, u64, u128);
330     try_from_both_bounded!(isize, i8, i16);
331     try_from_unbounded!(isize, i32, i64, i128);
332
333     rev!(try_from_unbounded, usize, u32);
334     rev!(try_from_upper_bounded, usize, u64, u128);
335     rev!(try_from_lower_bounded, usize, i8, i16, i32);
336     rev!(try_from_both_bounded, usize, i64, i128);
337
338     rev!(try_from_unbounded, isize, u16);
339     rev!(try_from_upper_bounded, isize, u32, u64, u128);
340     rev!(try_from_unbounded, isize, i32);
341     rev!(try_from_both_bounded, isize, i64, i128);
342 }
343
344 #[cfg(target_pointer_width = "64")]
345 mod ptr_try_from_impls {
346     use super::TryFromIntError;
347     use crate::convert::TryFrom;
348
349     try_from_upper_bounded!(usize, u8, u16, u32);
350     try_from_unbounded!(usize, u64, u128);
351     try_from_upper_bounded!(usize, i8, i16, i32, i64);
352     try_from_unbounded!(usize, i128);
353
354     try_from_both_bounded!(isize, u8, u16, u32);
355     try_from_lower_bounded!(isize, u64, u128);
356     try_from_both_bounded!(isize, i8, i16, i32);
357     try_from_unbounded!(isize, i64, i128);
358
359     rev!(try_from_unbounded, usize, u32, u64);
360     rev!(try_from_upper_bounded, usize, u128);
361     rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
362     rev!(try_from_both_bounded, usize, i128);
363
364     rev!(try_from_unbounded, isize, u16, u32);
365     rev!(try_from_upper_bounded, isize, u64, u128);
366     rev!(try_from_unbounded, isize, i32, i64);
367     rev!(try_from_both_bounded, isize, i128);
368 }
369
370 // Conversion traits for non-zero integer types
371 use crate::num::NonZeroI128;
372 use crate::num::NonZeroI16;
373 use crate::num::NonZeroI32;
374 use crate::num::NonZeroI64;
375 use crate::num::NonZeroI8;
376 use crate::num::NonZeroIsize;
377 use crate::num::NonZeroU128;
378 use crate::num::NonZeroU16;
379 use crate::num::NonZeroU32;
380 use crate::num::NonZeroU64;
381 use crate::num::NonZeroU8;
382 use crate::num::NonZeroUsize;
383
384 macro_rules! nzint_impl_from {
385     ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => {
386         #[$attr]
387         #[doc = $doc]
388         impl From<$Small> for $Large {
389             #[inline]
390             fn from(small: $Small) -> $Large {
391                 // SAFETY: input type guarantees the value is non-zero
392                 unsafe {
393                     <$Large>::new_unchecked(small.get().into())
394                 }
395             }
396         }
397     };
398     ($Small: ty, $Large: ty, #[$attr:meta]) => {
399         nzint_impl_from!($Small,
400                    $Large,
401                    #[$attr],
402                    concat!("Converts `",
403                            stringify!($Small),
404                            "` to `",
405                            stringify!($Large),
406                            "` losslessly."));
407     }
408 }
409
410 // Non-zero Unsigned -> Non-zero Unsigned
411 nzint_impl_from! { NonZeroU8, NonZeroU16, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
412 nzint_impl_from! { NonZeroU8, NonZeroU32, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
413 nzint_impl_from! { NonZeroU8, NonZeroU64, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
414 nzint_impl_from! { NonZeroU8, NonZeroU128, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
415 nzint_impl_from! { NonZeroU8, NonZeroUsize, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
416 nzint_impl_from! { NonZeroU16, NonZeroU32, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
417 nzint_impl_from! { NonZeroU16, NonZeroU64, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
418 nzint_impl_from! { NonZeroU16, NonZeroU128, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
419 nzint_impl_from! { NonZeroU16, NonZeroUsize, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
420 nzint_impl_from! { NonZeroU32, NonZeroU64, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
421 nzint_impl_from! { NonZeroU32, NonZeroU128, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
422 nzint_impl_from! { NonZeroU64, NonZeroU128, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
423
424 // Non-zero Signed -> Non-zero Signed
425 nzint_impl_from! { NonZeroI8, NonZeroI16, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
426 nzint_impl_from! { NonZeroI8, NonZeroI32, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
427 nzint_impl_from! { NonZeroI8, NonZeroI64, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
428 nzint_impl_from! { NonZeroI8, NonZeroI128, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
429 nzint_impl_from! { NonZeroI8, NonZeroIsize, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
430 nzint_impl_from! { NonZeroI16, NonZeroI32, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
431 nzint_impl_from! { NonZeroI16, NonZeroI64, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
432 nzint_impl_from! { NonZeroI16, NonZeroI128, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
433 nzint_impl_from! { NonZeroI16, NonZeroIsize, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
434 nzint_impl_from! { NonZeroI32, NonZeroI64, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
435 nzint_impl_from! { NonZeroI32, NonZeroI128, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
436 nzint_impl_from! { NonZeroI64, NonZeroI128, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
437
438 // NonZero UnSigned -> Non-zero Signed
439 nzint_impl_from! { NonZeroU8, NonZeroI16, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
440 nzint_impl_from! { NonZeroU8, NonZeroI32, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
441 nzint_impl_from! { NonZeroU8, NonZeroI64, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
442 nzint_impl_from! { NonZeroU8, NonZeroI128, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
443 nzint_impl_from! { NonZeroU8, NonZeroIsize, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
444 nzint_impl_from! { NonZeroU16, NonZeroI32, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
445 nzint_impl_from! { NonZeroU16, NonZeroI64, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
446 nzint_impl_from! { NonZeroU16, NonZeroI128, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
447 nzint_impl_from! { NonZeroU32, NonZeroI64, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
448 nzint_impl_from! { NonZeroU32, NonZeroI128, #[stable(feature = "nz_int_conv", since = "1.41.0")] }
449 nzint_impl_from! { NonZeroU64, NonZeroI128, #[stable(feature = "nz_int_conv", since = "1.41.0")] }