num_traits/
cast.rs

1use core::mem::size_of;
2use core::num::Wrapping;
3use core::{f32, f64};
4#[cfg(has_i128)]
5use core::{i128, u128};
6use core::{i16, i32, i64, i8, isize};
7use core::{u16, u32, u64, u8, usize};
8
9use float::FloatCore;
10
11/// A generic trait for converting a value to a number.
12pub trait ToPrimitive {
13    /// Converts the value of `self` to an `isize`. If the value cannot be
14    /// represented by an `isize`, then `None` is returned.
15    #[inline]
16    fn to_isize(&self) -> Option<isize> {
17        self.to_i64().as_ref().and_then(ToPrimitive::to_isize)
18    }
19
20    /// Converts the value of `self` to an `i8`. If the value cannot be
21    /// represented by an `i8`, then `None` is returned.
22    #[inline]
23    fn to_i8(&self) -> Option<i8> {
24        self.to_i64().as_ref().and_then(ToPrimitive::to_i8)
25    }
26
27    /// Converts the value of `self` to an `i16`. If the value cannot be
28    /// represented by an `i16`, then `None` is returned.
29    #[inline]
30    fn to_i16(&self) -> Option<i16> {
31        self.to_i64().as_ref().and_then(ToPrimitive::to_i16)
32    }
33
34    /// Converts the value of `self` to an `i32`. If the value cannot be
35    /// represented by an `i32`, then `None` is returned.
36    #[inline]
37    fn to_i32(&self) -> Option<i32> {
38        self.to_i64().as_ref().and_then(ToPrimitive::to_i32)
39    }
40
41    /// Converts the value of `self` to an `i64`. If the value cannot be
42    /// represented by an `i64`, then `None` is returned.
43    fn to_i64(&self) -> Option<i64>;
44
45    /// Converts the value of `self` to an `i128`. If the value cannot be
46    /// represented by an `i128` (`i64` under the default implementation), then
47    /// `None` is returned.
48    ///
49    /// This method is only available with feature `i128` enabled on Rust >= 1.26.
50    ///
51    /// The default implementation converts through `to_i64()`. Types implementing
52    /// this trait should override this method if they can represent a greater range.
53    #[inline]
54    #[cfg(has_i128)]
55    fn to_i128(&self) -> Option<i128> {
56        self.to_i64().map(From::from)
57    }
58
59    /// Converts the value of `self` to a `usize`. If the value cannot be
60    /// represented by a `usize`, then `None` is returned.
61    #[inline]
62    fn to_usize(&self) -> Option<usize> {
63        self.to_u64().as_ref().and_then(ToPrimitive::to_usize)
64    }
65
66    /// Converts the value of `self` to a `u8`. If the value cannot be
67    /// represented by a `u8`, then `None` is returned.
68    #[inline]
69    fn to_u8(&self) -> Option<u8> {
70        self.to_u64().as_ref().and_then(ToPrimitive::to_u8)
71    }
72
73    /// Converts the value of `self` to a `u16`. If the value cannot be
74    /// represented by a `u16`, then `None` is returned.
75    #[inline]
76    fn to_u16(&self) -> Option<u16> {
77        self.to_u64().as_ref().and_then(ToPrimitive::to_u16)
78    }
79
80    /// Converts the value of `self` to a `u32`. If the value cannot be
81    /// represented by a `u32`, then `None` is returned.
82    #[inline]
83    fn to_u32(&self) -> Option<u32> {
84        self.to_u64().as_ref().and_then(ToPrimitive::to_u32)
85    }
86
87    /// Converts the value of `self` to a `u64`. If the value cannot be
88    /// represented by a `u64`, then `None` is returned.
89    fn to_u64(&self) -> Option<u64>;
90
91    /// Converts the value of `self` to a `u128`. If the value cannot be
92    /// represented by a `u128` (`u64` under the default implementation), then
93    /// `None` is returned.
94    ///
95    /// This method is only available with feature `i128` enabled on Rust >= 1.26.
96    ///
97    /// The default implementation converts through `to_u64()`.  Types implementing
98    /// this trait should override this method if they can represent a greater range.
99    #[inline]
100    #[cfg(has_i128)]
101    fn to_u128(&self) -> Option<u128> {
102        self.to_u64().map(From::from)
103    }
104
105    /// Converts the value of `self` to an `f32`. If the value cannot be
106    /// represented by an `f32`, then `None` is returned.
107    #[inline]
108    fn to_f32(&self) -> Option<f32> {
109        self.to_f64().as_ref().and_then(ToPrimitive::to_f32)
110    }
111
112    /// Converts the value of `self` to an `f64`. If the value cannot be
113    /// represented by an `f64`, then `None` is returned.
114    #[inline]
115    fn to_f64(&self) -> Option<f64> {
116        match self.to_i64() {
117            Some(i) => i.to_f64(),
118            None => self.to_u64().as_ref().and_then(ToPrimitive::to_f64),
119        }
120    }
121}
122
123macro_rules! impl_to_primitive_int_to_int {
124    ($SrcT:ident : $( $(#[$cfg:meta])* fn $method:ident -> $DstT:ident ; )*) => {$(
125        #[inline]
126        $(#[$cfg])*
127        fn $method(&self) -> Option<$DstT> {
128            let min = $DstT::MIN as $SrcT;
129            let max = $DstT::MAX as $SrcT;
130            if size_of::<$SrcT>() <= size_of::<$DstT>() || (min <= *self && *self <= max) {
131                Some(*self as $DstT)
132            } else {
133                None
134            }
135        }
136    )*}
137}
138
139macro_rules! impl_to_primitive_int_to_uint {
140    ($SrcT:ident : $( $(#[$cfg:meta])* fn $method:ident -> $DstT:ident ; )*) => {$(
141        #[inline]
142        $(#[$cfg])*
143        fn $method(&self) -> Option<$DstT> {
144            let max = $DstT::MAX as $SrcT;
145            if 0 <= *self && (size_of::<$SrcT>() <= size_of::<$DstT>() || *self <= max) {
146                Some(*self as $DstT)
147            } else {
148                None
149            }
150        }
151    )*}
152}
153
154macro_rules! impl_to_primitive_int {
155    ($T:ident) => {
156        impl ToPrimitive for $T {
157            impl_to_primitive_int_to_int! { $T:
158                fn to_isize -> isize;
159                fn to_i8 -> i8;
160                fn to_i16 -> i16;
161                fn to_i32 -> i32;
162                fn to_i64 -> i64;
163                #[cfg(has_i128)]
164                fn to_i128 -> i128;
165            }
166
167            impl_to_primitive_int_to_uint! { $T:
168                fn to_usize -> usize;
169                fn to_u8 -> u8;
170                fn to_u16 -> u16;
171                fn to_u32 -> u32;
172                fn to_u64 -> u64;
173                #[cfg(has_i128)]
174                fn to_u128 -> u128;
175            }
176
177            #[inline]
178            fn to_f32(&self) -> Option<f32> {
179                Some(*self as f32)
180            }
181            #[inline]
182            fn to_f64(&self) -> Option<f64> {
183                Some(*self as f64)
184            }
185        }
186    };
187}
188
189impl_to_primitive_int!(isize);
190impl_to_primitive_int!(i8);
191impl_to_primitive_int!(i16);
192impl_to_primitive_int!(i32);
193impl_to_primitive_int!(i64);
194#[cfg(has_i128)]
195impl_to_primitive_int!(i128);
196
197macro_rules! impl_to_primitive_uint_to_int {
198    ($SrcT:ident : $( $(#[$cfg:meta])* fn $method:ident -> $DstT:ident ; )*) => {$(
199        #[inline]
200        $(#[$cfg])*
201        fn $method(&self) -> Option<$DstT> {
202            let max = $DstT::MAX as $SrcT;
203            if size_of::<$SrcT>() < size_of::<$DstT>() || *self <= max {
204                Some(*self as $DstT)
205            } else {
206                None
207            }
208        }
209    )*}
210}
211
212macro_rules! impl_to_primitive_uint_to_uint {
213    ($SrcT:ident : $( $(#[$cfg:meta])* fn $method:ident -> $DstT:ident ; )*) => {$(
214        #[inline]
215        $(#[$cfg])*
216        fn $method(&self) -> Option<$DstT> {
217            let max = $DstT::MAX as $SrcT;
218            if size_of::<$SrcT>() <= size_of::<$DstT>() || *self <= max {
219                Some(*self as $DstT)
220            } else {
221                None
222            }
223        }
224    )*}
225}
226
227macro_rules! impl_to_primitive_uint {
228    ($T:ident) => {
229        impl ToPrimitive for $T {
230            impl_to_primitive_uint_to_int! { $T:
231                fn to_isize -> isize;
232                fn to_i8 -> i8;
233                fn to_i16 -> i16;
234                fn to_i32 -> i32;
235                fn to_i64 -> i64;
236                #[cfg(has_i128)]
237                fn to_i128 -> i128;
238            }
239
240            impl_to_primitive_uint_to_uint! { $T:
241                fn to_usize -> usize;
242                fn to_u8 -> u8;
243                fn to_u16 -> u16;
244                fn to_u32 -> u32;
245                fn to_u64 -> u64;
246                #[cfg(has_i128)]
247                fn to_u128 -> u128;
248            }
249
250            #[inline]
251            fn to_f32(&self) -> Option<f32> {
252                Some(*self as f32)
253            }
254            #[inline]
255            fn to_f64(&self) -> Option<f64> {
256                Some(*self as f64)
257            }
258        }
259    };
260}
261
262impl_to_primitive_uint!(usize);
263impl_to_primitive_uint!(u8);
264impl_to_primitive_uint!(u16);
265impl_to_primitive_uint!(u32);
266impl_to_primitive_uint!(u64);
267#[cfg(has_i128)]
268impl_to_primitive_uint!(u128);
269
270macro_rules! impl_to_primitive_float_to_float {
271    ($SrcT:ident : $( fn $method:ident -> $DstT:ident ; )*) => {$(
272        #[inline]
273        fn $method(&self) -> Option<$DstT> {
274            // Only finite values that are reducing size need to worry about overflow.
275            if size_of::<$SrcT>() > size_of::<$DstT>() && FloatCore::is_finite(*self) {
276                let n = *self as f64;
277                if n < $DstT::MIN as f64 || n > $DstT::MAX as f64 {
278                    return None;
279                }
280            }
281            // We can safely cast NaN, +-inf, and finite values in range.
282            Some(*self as $DstT)
283        }
284    )*}
285}
286
287macro_rules! impl_to_primitive_float_to_signed_int {
288    ($f:ident : $( $(#[$cfg:meta])* fn $method:ident -> $i:ident ; )*) => {$(
289        #[inline]
290        $(#[$cfg])*
291        fn $method(&self) -> Option<$i> {
292            // Float as int truncates toward zero, so we want to allow values
293            // in the exclusive range `(MIN-1, MAX+1)`.
294            if size_of::<$f>() > size_of::<$i>() {
295                // With a larger size, we can represent the range exactly.
296                const MIN_M1: $f = $i::MIN as $f - 1.0;
297                const MAX_P1: $f = $i::MAX as $f + 1.0;
298                if *self > MIN_M1 && *self < MAX_P1 {
299                    return Some(*self as $i);
300                }
301            } else {
302                // We can't represent `MIN-1` exactly, but there's no fractional part
303                // at this magnitude, so we can just use a `MIN` inclusive boundary.
304                const MIN: $f = $i::MIN as $f;
305                // We can't represent `MAX` exactly, but it will round up to exactly
306                // `MAX+1` (a power of two) when we cast it.
307                const MAX_P1: $f = $i::MAX as $f;
308                if *self >= MIN && *self < MAX_P1 {
309                    return Some(*self as $i);
310                }
311            }
312            None
313        }
314    )*}
315}
316
317macro_rules! impl_to_primitive_float_to_unsigned_int {
318    ($f:ident : $( $(#[$cfg:meta])* fn $method:ident -> $u:ident ; )*) => {$(
319        #[inline]
320        $(#[$cfg])*
321        fn $method(&self) -> Option<$u> {
322            // Float as int truncates toward zero, so we want to allow values
323            // in the exclusive range `(-1, MAX+1)`.
324            if size_of::<$f>() > size_of::<$u>() {
325                // With a larger size, we can represent the range exactly.
326                const MAX_P1: $f = $u::MAX as $f + 1.0;
327                if *self > -1.0 && *self < MAX_P1 {
328                    return Some(*self as $u);
329                }
330            } else {
331                // We can't represent `MAX` exactly, but it will round up to exactly
332                // `MAX+1` (a power of two) when we cast it.
333                // (`u128::MAX as f32` is infinity, but this is still ok.)
334                const MAX_P1: $f = $u::MAX as $f;
335                if *self > -1.0 && *self < MAX_P1 {
336                    return Some(*self as $u);
337                }
338            }
339            None
340        }
341    )*}
342}
343
344macro_rules! impl_to_primitive_float {
345    ($T:ident) => {
346        impl ToPrimitive for $T {
347            impl_to_primitive_float_to_signed_int! { $T:
348                fn to_isize -> isize;
349                fn to_i8 -> i8;
350                fn to_i16 -> i16;
351                fn to_i32 -> i32;
352                fn to_i64 -> i64;
353                #[cfg(has_i128)]
354                fn to_i128 -> i128;
355            }
356
357            impl_to_primitive_float_to_unsigned_int! { $T:
358                fn to_usize -> usize;
359                fn to_u8 -> u8;
360                fn to_u16 -> u16;
361                fn to_u32 -> u32;
362                fn to_u64 -> u64;
363                #[cfg(has_i128)]
364                fn to_u128 -> u128;
365            }
366
367            impl_to_primitive_float_to_float! { $T:
368                fn to_f32 -> f32;
369                fn to_f64 -> f64;
370            }
371        }
372    };
373}
374
375impl_to_primitive_float!(f32);
376impl_to_primitive_float!(f64);
377
378/// A generic trait for converting a number to a value.
379pub trait FromPrimitive: Sized {
380    /// Converts an `isize` to return an optional value of this type. If the
381    /// value cannot be represented by this type, then `None` is returned.
382    #[inline]
383    fn from_isize(n: isize) -> Option<Self> {
384        n.to_i64().and_then(FromPrimitive::from_i64)
385    }
386
387    /// Converts an `i8` to return an optional value of this type. If the
388    /// value cannot be represented by this type, then `None` is returned.
389    #[inline]
390    fn from_i8(n: i8) -> Option<Self> {
391        FromPrimitive::from_i64(From::from(n))
392    }
393
394    /// Converts an `i16` to return an optional value of this type. If the
395    /// value cannot be represented by this type, then `None` is returned.
396    #[inline]
397    fn from_i16(n: i16) -> Option<Self> {
398        FromPrimitive::from_i64(From::from(n))
399    }
400
401    /// Converts an `i32` to return an optional value of this type. If the
402    /// value cannot be represented by this type, then `None` is returned.
403    #[inline]
404    fn from_i32(n: i32) -> Option<Self> {
405        FromPrimitive::from_i64(From::from(n))
406    }
407
408    /// Converts an `i64` to return an optional value of this type. If the
409    /// value cannot be represented by this type, then `None` is returned.
410    fn from_i64(n: i64) -> Option<Self>;
411
412    /// Converts an `i128` to return an optional value of this type. If the
413    /// value cannot be represented by this type, then `None` is returned.
414    ///
415    /// This method is only available with feature `i128` enabled on Rust >= 1.26.
416    ///
417    /// The default implementation converts through `from_i64()`. Types implementing
418    /// this trait should override this method if they can represent a greater range.
419    #[inline]
420    #[cfg(has_i128)]
421    fn from_i128(n: i128) -> Option<Self> {
422        n.to_i64().and_then(FromPrimitive::from_i64)
423    }
424
425    /// Converts a `usize` to return an optional value of this type. If the
426    /// value cannot be represented by this type, then `None` is returned.
427    #[inline]
428    fn from_usize(n: usize) -> Option<Self> {
429        n.to_u64().and_then(FromPrimitive::from_u64)
430    }
431
432    /// Converts an `u8` to return an optional value of this type. If the
433    /// value cannot be represented by this type, then `None` is returned.
434    #[inline]
435    fn from_u8(n: u8) -> Option<Self> {
436        FromPrimitive::from_u64(From::from(n))
437    }
438
439    /// Converts an `u16` to return an optional value of this type. If the
440    /// value cannot be represented by this type, then `None` is returned.
441    #[inline]
442    fn from_u16(n: u16) -> Option<Self> {
443        FromPrimitive::from_u64(From::from(n))
444    }
445
446    /// Converts an `u32` to return an optional value of this type. If the
447    /// value cannot be represented by this type, then `None` is returned.
448    #[inline]
449    fn from_u32(n: u32) -> Option<Self> {
450        FromPrimitive::from_u64(From::from(n))
451    }
452
453    /// Converts an `u64` to return an optional value of this type. If the
454    /// value cannot be represented by this type, then `None` is returned.
455    fn from_u64(n: u64) -> Option<Self>;
456
457    /// Converts an `u128` to return an optional value of this type. If the
458    /// value cannot be represented by this type, then `None` is returned.
459    ///
460    /// This method is only available with feature `i128` enabled on Rust >= 1.26.
461    ///
462    /// The default implementation converts through `from_u64()`. Types implementing
463    /// this trait should override this method if they can represent a greater range.
464    #[inline]
465    #[cfg(has_i128)]
466    fn from_u128(n: u128) -> Option<Self> {
467        n.to_u64().and_then(FromPrimitive::from_u64)
468    }
469
470    /// Converts a `f32` to return an optional value of this type. If the
471    /// value cannot be represented by this type, then `None` is returned.
472    #[inline]
473    fn from_f32(n: f32) -> Option<Self> {
474        FromPrimitive::from_f64(From::from(n))
475    }
476
477    /// Converts a `f64` to return an optional value of this type. If the
478    /// value cannot be represented by this type, then `None` is returned.
479    #[inline]
480    fn from_f64(n: f64) -> Option<Self> {
481        match n.to_i64() {
482            Some(i) => FromPrimitive::from_i64(i),
483            None => n.to_u64().and_then(FromPrimitive::from_u64),
484        }
485    }
486}
487
488macro_rules! impl_from_primitive {
489    ($T:ty, $to_ty:ident) => {
490        #[allow(deprecated)]
491        impl FromPrimitive for $T {
492            #[inline]
493            fn from_isize(n: isize) -> Option<$T> {
494                n.$to_ty()
495            }
496            #[inline]
497            fn from_i8(n: i8) -> Option<$T> {
498                n.$to_ty()
499            }
500            #[inline]
501            fn from_i16(n: i16) -> Option<$T> {
502                n.$to_ty()
503            }
504            #[inline]
505            fn from_i32(n: i32) -> Option<$T> {
506                n.$to_ty()
507            }
508            #[inline]
509            fn from_i64(n: i64) -> Option<$T> {
510                n.$to_ty()
511            }
512            #[cfg(has_i128)]
513            #[inline]
514            fn from_i128(n: i128) -> Option<$T> {
515                n.$to_ty()
516            }
517
518            #[inline]
519            fn from_usize(n: usize) -> Option<$T> {
520                n.$to_ty()
521            }
522            #[inline]
523            fn from_u8(n: u8) -> Option<$T> {
524                n.$to_ty()
525            }
526            #[inline]
527            fn from_u16(n: u16) -> Option<$T> {
528                n.$to_ty()
529            }
530            #[inline]
531            fn from_u32(n: u32) -> Option<$T> {
532                n.$to_ty()
533            }
534            #[inline]
535            fn from_u64(n: u64) -> Option<$T> {
536                n.$to_ty()
537            }
538            #[cfg(has_i128)]
539            #[inline]
540            fn from_u128(n: u128) -> Option<$T> {
541                n.$to_ty()
542            }
543
544            #[inline]
545            fn from_f32(n: f32) -> Option<$T> {
546                n.$to_ty()
547            }
548            #[inline]
549            fn from_f64(n: f64) -> Option<$T> {
550                n.$to_ty()
551            }
552        }
553    };
554}
555
556impl_from_primitive!(isize, to_isize);
557impl_from_primitive!(i8, to_i8);
558impl_from_primitive!(i16, to_i16);
559impl_from_primitive!(i32, to_i32);
560impl_from_primitive!(i64, to_i64);
561#[cfg(has_i128)]
562impl_from_primitive!(i128, to_i128);
563impl_from_primitive!(usize, to_usize);
564impl_from_primitive!(u8, to_u8);
565impl_from_primitive!(u16, to_u16);
566impl_from_primitive!(u32, to_u32);
567impl_from_primitive!(u64, to_u64);
568#[cfg(has_i128)]
569impl_from_primitive!(u128, to_u128);
570impl_from_primitive!(f32, to_f32);
571impl_from_primitive!(f64, to_f64);
572
573macro_rules! impl_to_primitive_wrapping {
574    ($( $(#[$cfg:meta])* fn $method:ident -> $i:ident ; )*) => {$(
575        #[inline]
576        $(#[$cfg])*
577        fn $method(&self) -> Option<$i> {
578            (self.0).$method()
579        }
580    )*}
581}
582
583impl<T: ToPrimitive> ToPrimitive for Wrapping<T> {
584    impl_to_primitive_wrapping! {
585        fn to_isize -> isize;
586        fn to_i8 -> i8;
587        fn to_i16 -> i16;
588        fn to_i32 -> i32;
589        fn to_i64 -> i64;
590        #[cfg(has_i128)]
591        fn to_i128 -> i128;
592
593        fn to_usize -> usize;
594        fn to_u8 -> u8;
595        fn to_u16 -> u16;
596        fn to_u32 -> u32;
597        fn to_u64 -> u64;
598        #[cfg(has_i128)]
599        fn to_u128 -> u128;
600
601        fn to_f32 -> f32;
602        fn to_f64 -> f64;
603    }
604}
605
606macro_rules! impl_from_primitive_wrapping {
607    ($( $(#[$cfg:meta])* fn $method:ident ( $i:ident ); )*) => {$(
608        #[inline]
609        $(#[$cfg])*
610        fn $method(n: $i) -> Option<Self> {
611            T::$method(n).map(Wrapping)
612        }
613    )*}
614}
615
616impl<T: FromPrimitive> FromPrimitive for Wrapping<T> {
617    impl_from_primitive_wrapping! {
618        fn from_isize(isize);
619        fn from_i8(i8);
620        fn from_i16(i16);
621        fn from_i32(i32);
622        fn from_i64(i64);
623        #[cfg(has_i128)]
624        fn from_i128(i128);
625
626        fn from_usize(usize);
627        fn from_u8(u8);
628        fn from_u16(u16);
629        fn from_u32(u32);
630        fn from_u64(u64);
631        #[cfg(has_i128)]
632        fn from_u128(u128);
633
634        fn from_f32(f32);
635        fn from_f64(f64);
636    }
637}
638
639/// Cast from one machine scalar to another.
640///
641/// # Examples
642///
643/// ```
644/// # use num_traits as num;
645/// let twenty: f32 = num::cast(0x14).unwrap();
646/// assert_eq!(twenty, 20f32);
647/// ```
648///
649#[inline]
650pub fn cast<T: NumCast, U: NumCast>(n: T) -> Option<U> {
651    NumCast::from(n)
652}
653
654/// An interface for casting between machine scalars.
655pub trait NumCast: Sized + ToPrimitive {
656    /// Creates a number from another value that can be converted into
657    /// a primitive via the `ToPrimitive` trait. If the source value cannot be
658    /// represented by the target type, then `None` is returned.
659    fn from<T: ToPrimitive>(n: T) -> Option<Self>;
660}
661
662macro_rules! impl_num_cast {
663    ($T:ty, $conv:ident) => {
664        impl NumCast for $T {
665            #[inline]
666            #[allow(deprecated)]
667            fn from<N: ToPrimitive>(n: N) -> Option<$T> {
668                // `$conv` could be generated using `concat_idents!`, but that
669                // macro seems to be broken at the moment
670                n.$conv()
671            }
672        }
673    };
674}
675
676impl_num_cast!(u8, to_u8);
677impl_num_cast!(u16, to_u16);
678impl_num_cast!(u32, to_u32);
679impl_num_cast!(u64, to_u64);
680#[cfg(has_i128)]
681impl_num_cast!(u128, to_u128);
682impl_num_cast!(usize, to_usize);
683impl_num_cast!(i8, to_i8);
684impl_num_cast!(i16, to_i16);
685impl_num_cast!(i32, to_i32);
686impl_num_cast!(i64, to_i64);
687#[cfg(has_i128)]
688impl_num_cast!(i128, to_i128);
689impl_num_cast!(isize, to_isize);
690impl_num_cast!(f32, to_f32);
691impl_num_cast!(f64, to_f64);
692
693impl<T: NumCast> NumCast for Wrapping<T> {
694    fn from<U: ToPrimitive>(n: U) -> Option<Self> {
695        T::from(n).map(Wrapping)
696    }
697}
698
699/// A generic interface for casting between machine scalars with the
700/// `as` operator, which admits narrowing and precision loss.
701/// Implementers of this trait `AsPrimitive` should behave like a primitive
702/// numeric type (e.g. a newtype around another primitive), and the
703/// intended conversion must never fail.
704///
705/// # Examples
706///
707/// ```
708/// # use num_traits::AsPrimitive;
709/// let three: i32 = (3.14159265f32).as_();
710/// assert_eq!(three, 3);
711/// ```
712///
713/// # Safety
714///
715/// Currently, some uses of the `as` operator are not entirely safe.
716/// In particular, it is undefined behavior if:
717///
718/// - A truncated floating point value cannot fit in the target integer
719///   type ([#10184](https://github.com/rust-lang/rust/issues/10184));
720///
721/// ```ignore
722/// # use num_traits::AsPrimitive;
723/// let x: u8 = (1.04E+17).as_(); // UB
724/// ```
725///
726/// - Or a floating point value does not fit in another floating
727///   point type ([#15536](https://github.com/rust-lang/rust/issues/15536)).
728///
729/// ```ignore
730/// # use num_traits::AsPrimitive;
731/// let x: f32 = (1e300f64).as_(); // UB
732/// ```
733///
734pub trait AsPrimitive<T>: 'static + Copy
735where
736    T: 'static + Copy,
737{
738    /// Convert a value to another, using the `as` operator.
739    fn as_(self) -> T;
740}
741
742macro_rules! impl_as_primitive {
743    (@ $T: ty => $(#[$cfg:meta])* impl $U: ty ) => {
744        $(#[$cfg])*
745        impl AsPrimitive<$U> for $T {
746            #[inline] fn as_(self) -> $U { self as $U }
747        }
748    };
749    (@ $T: ty => { $( $U: ty ),* } ) => {$(
750        impl_as_primitive!(@ $T => impl $U);
751    )*};
752    ($T: ty => { $( $U: ty ),* } ) => {
753        impl_as_primitive!(@ $T => { $( $U ),* });
754        impl_as_primitive!(@ $T => { u8, u16, u32, u64, usize });
755        impl_as_primitive!(@ $T => #[cfg(has_i128)] impl u128);
756        impl_as_primitive!(@ $T => { i8, i16, i32, i64, isize });
757        impl_as_primitive!(@ $T => #[cfg(has_i128)] impl i128);
758    };
759}
760
761impl_as_primitive!(u8 => { char, f32, f64 });
762impl_as_primitive!(i8 => { f32, f64 });
763impl_as_primitive!(u16 => { f32, f64 });
764impl_as_primitive!(i16 => { f32, f64 });
765impl_as_primitive!(u32 => { f32, f64 });
766impl_as_primitive!(i32 => { f32, f64 });
767impl_as_primitive!(u64 => { f32, f64 });
768impl_as_primitive!(i64 => { f32, f64 });
769#[cfg(has_i128)]
770impl_as_primitive!(u128 => { f32, f64 });
771#[cfg(has_i128)]
772impl_as_primitive!(i128 => { f32, f64 });
773impl_as_primitive!(usize => { f32, f64 });
774impl_as_primitive!(isize => { f32, f64 });
775impl_as_primitive!(f32 => { f32, f64 });
776impl_as_primitive!(f64 => { f32, f64 });
777impl_as_primitive!(char => { char });
778impl_as_primitive!(bool => {});