1use core::mem::size_of;
2use core::num::Wrapping;
3use core::{f32, f64};
4use core::{i128, i16, i32, i64, i8, isize};
5use core::{u128, u16, u32, u64, u8, usize};
67/// A generic trait for converting a value to a number.
8///
9/// A value can be represented by the target type when it lies within
10/// the range of scalars supported by the target type.
11/// For example, a negative integer cannot be represented by an unsigned
12/// integer type, and an `i64` with a very high magnitude might not be
13/// convertible to an `i32`.
14/// On the other hand, conversions with possible precision loss or truncation
15/// are admitted, like an `f32` with a decimal part to an integer type, or
16/// even a large `f64` saturating to `f32` infinity.
17pub trait ToPrimitive {
18/// Converts the value of `self` to an `isize`. If the value cannot be
19 /// represented by an `isize`, then `None` is returned.
20#[inline]
21fn to_isize(&self) -> Option<isize> {
22self.to_i64().as_ref().and_then(ToPrimitive::to_isize)
23 }
2425/// Converts the value of `self` to an `i8`. If the value cannot be
26 /// represented by an `i8`, then `None` is returned.
27#[inline]
28fn to_i8(&self) -> Option<i8> {
29self.to_i64().as_ref().and_then(ToPrimitive::to_i8)
30 }
3132/// Converts the value of `self` to an `i16`. If the value cannot be
33 /// represented by an `i16`, then `None` is returned.
34#[inline]
35fn to_i16(&self) -> Option<i16> {
36self.to_i64().as_ref().and_then(ToPrimitive::to_i16)
37 }
3839/// Converts the value of `self` to an `i32`. If the value cannot be
40 /// represented by an `i32`, then `None` is returned.
41#[inline]
42fn to_i32(&self) -> Option<i32> {
43self.to_i64().as_ref().and_then(ToPrimitive::to_i32)
44 }
4546/// Converts the value of `self` to an `i64`. If the value cannot be
47 /// represented by an `i64`, then `None` is returned.
48fn to_i64(&self) -> Option<i64>;
4950/// Converts the value of `self` to an `i128`. If the value cannot be
51 /// represented by an `i128` (`i64` under the default implementation), then
52 /// `None` is returned.
53 ///
54 /// The default implementation converts through `to_i64()`. Types implementing
55 /// this trait should override this method if they can represent a greater range.
56#[inline]
57fn to_i128(&self) -> Option<i128> {
58self.to_i64().map(From::from)
59 }
6061/// Converts the value of `self` to a `usize`. If the value cannot be
62 /// represented by a `usize`, then `None` is returned.
63#[inline]
64fn to_usize(&self) -> Option<usize> {
65self.to_u64().as_ref().and_then(ToPrimitive::to_usize)
66 }
6768/// Converts the value of `self` to a `u8`. If the value cannot be
69 /// represented by a `u8`, then `None` is returned.
70#[inline]
71fn to_u8(&self) -> Option<u8> {
72self.to_u64().as_ref().and_then(ToPrimitive::to_u8)
73 }
7475/// Converts the value of `self` to a `u16`. If the value cannot be
76 /// represented by a `u16`, then `None` is returned.
77#[inline]
78fn to_u16(&self) -> Option<u16> {
79self.to_u64().as_ref().and_then(ToPrimitive::to_u16)
80 }
8182/// Converts the value of `self` to a `u32`. If the value cannot be
83 /// represented by a `u32`, then `None` is returned.
84#[inline]
85fn to_u32(&self) -> Option<u32> {
86self.to_u64().as_ref().and_then(ToPrimitive::to_u32)
87 }
8889/// Converts the value of `self` to a `u64`. If the value cannot be
90 /// represented by a `u64`, then `None` is returned.
91fn to_u64(&self) -> Option<u64>;
9293/// Converts the value of `self` to a `u128`. If the value cannot be
94 /// represented by a `u128` (`u64` under the default implementation), then
95 /// `None` is returned.
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]
100fn to_u128(&self) -> Option<u128> {
101self.to_u64().map(From::from)
102 }
103104/// Converts the value of `self` to an `f32`. Overflows may map to positive
105 /// or negative inifinity, otherwise `None` is returned if the value cannot
106 /// be represented by an `f32`.
107#[inline]
108fn to_f32(&self) -> Option<f32> {
109self.to_f64().as_ref().and_then(ToPrimitive::to_f32)
110 }
111112/// Converts the value of `self` to an `f64`. Overflows may map to positive
113 /// or negative inifinity, otherwise `None` is returned if the value cannot
114 /// be represented by an `f64`.
115 ///
116 /// The default implementation tries to convert through `to_i64()`, and
117 /// failing that through `to_u64()`. Types implementing this trait should
118 /// override this method if they can represent a greater range.
119#[inline]
120fn to_f64(&self) -> Option<f64> {
121match self.to_i64() {
122Some(i) => i.to_f64(),
123None => self.to_u64().as_ref().and_then(ToPrimitive::to_f64),
124 }
125 }
126}
127128macro_rules! impl_to_primitive_int_to_int {
129 ($SrcT:ident : $( $(#[$cfg:meta])* fn $method:ident -> $DstT:ident ; )*) => {$(
130#[inline]
131$(#[$cfg])*
132fn $method(&self) -> Option<$DstT> {
133let min = $DstT::MIN as $SrcT;
134let max = $DstT::MAX as $SrcT;
135if size_of::<$SrcT>() <= size_of::<$DstT>() || (min <= *self && *self <= max) {
136Some(*self as $DstT)
137 } else {
138None
139}
140 }
141 )*}
142}
143144macro_rules! impl_to_primitive_int_to_uint {
145 ($SrcT:ident : $( $(#[$cfg:meta])* fn $method:ident -> $DstT:ident ; )*) => {$(
146#[inline]
147$(#[$cfg])*
148fn $method(&self) -> Option<$DstT> {
149let max = $DstT::MAX as $SrcT;
150if 0 <= *self && (size_of::<$SrcT>() <= size_of::<$DstT>() || *self <= max) {
151Some(*self as $DstT)
152 } else {
153None
154}
155 }
156 )*}
157}
158159macro_rules! impl_to_primitive_int {
160 ($T:ident) => {
161impl ToPrimitive for $T {
162impl_to_primitive_int_to_int! { $T:
163fn to_isize -> isize;
164fn to_i8 -> i8;
165fn to_i16 -> i16;
166fn to_i32 -> i32;
167fn to_i64 -> i64;
168fn to_i128 -> i128;
169 }
170171impl_to_primitive_int_to_uint! { $T:
172fn to_usize -> usize;
173fn to_u8 -> u8;
174fn to_u16 -> u16;
175fn to_u32 -> u32;
176fn to_u64 -> u64;
177fn to_u128 -> u128;
178 }
179180#[inline]
181fn to_f32(&self) -> Option<f32> {
182Some(*self as f32)
183 }
184#[inline]
185fn to_f64(&self) -> Option<f64> {
186Some(*self as f64)
187 }
188 }
189 };
190}
191192impl_to_primitive_int!(isize);
193impl_to_primitive_int!(i8);
194impl_to_primitive_int!(i16);
195impl_to_primitive_int!(i32);
196impl_to_primitive_int!(i64);
197impl_to_primitive_int!(i128);
198199macro_rules! impl_to_primitive_uint_to_int {
200 ($SrcT:ident : $( $(#[$cfg:meta])* fn $method:ident -> $DstT:ident ; )*) => {$(
201#[inline]
202$(#[$cfg])*
203fn $method(&self) -> Option<$DstT> {
204let max = $DstT::MAX as $SrcT;
205if size_of::<$SrcT>() < size_of::<$DstT>() || *self <= max {
206Some(*self as $DstT)
207 } else {
208None
209}
210 }
211 )*}
212}
213214macro_rules! impl_to_primitive_uint_to_uint {
215 ($SrcT:ident : $( $(#[$cfg:meta])* fn $method:ident -> $DstT:ident ; )*) => {$(
216#[inline]
217$(#[$cfg])*
218fn $method(&self) -> Option<$DstT> {
219let max = $DstT::MAX as $SrcT;
220if size_of::<$SrcT>() <= size_of::<$DstT>() || *self <= max {
221Some(*self as $DstT)
222 } else {
223None
224}
225 }
226 )*}
227}
228229macro_rules! impl_to_primitive_uint {
230 ($T:ident) => {
231impl ToPrimitive for $T {
232impl_to_primitive_uint_to_int! { $T:
233fn to_isize -> isize;
234fn to_i8 -> i8;
235fn to_i16 -> i16;
236fn to_i32 -> i32;
237fn to_i64 -> i64;
238fn to_i128 -> i128;
239 }
240241impl_to_primitive_uint_to_uint! { $T:
242fn to_usize -> usize;
243fn to_u8 -> u8;
244fn to_u16 -> u16;
245fn to_u32 -> u32;
246fn to_u64 -> u64;
247fn to_u128 -> u128;
248 }
249250#[inline]
251fn to_f32(&self) -> Option<f32> {
252Some(*self as f32)
253 }
254#[inline]
255fn to_f64(&self) -> Option<f64> {
256Some(*self as f64)
257 }
258 }
259 };
260}
261262impl_to_primitive_uint!(usize);
263impl_to_primitive_uint!(u8);
264impl_to_primitive_uint!(u16);
265impl_to_primitive_uint!(u32);
266impl_to_primitive_uint!(u64);
267impl_to_primitive_uint!(u128);
268269macro_rules! impl_to_primitive_float_to_float {
270 ($SrcT:ident : $( fn $method:ident -> $DstT:ident ; )*) => {$(
271#[inline]
272fn $method(&self) -> Option<$DstT> {
273// We can safely cast all values, whether NaN, +-inf, or finite.
274 // Finite values that are reducing size may saturate to +-inf.
275Some(*self as $DstT)
276 }
277 )*}
278}
279280macro_rules! float_to_int_unchecked {
281// SAFETY: Must not be NaN or infinite; must be representable as the integer after truncating.
282 // We already checked that the float is in the exclusive range `(MIN-1, MAX+1)`.
283($float:expr => $int:ty) => {
284unsafe { $float.to_int_unchecked::<$int>() }
285 };
286}
287288macro_rules! impl_to_primitive_float_to_signed_int {
289 ($f:ident : $( $(#[$cfg:meta])* fn $method:ident -> $i:ident ; )*) => {$(
290#[inline]
291$(#[$cfg])*
292fn $method(&self) -> Option<$i> {
293// Float as int truncates toward zero, so we want to allow values
294 // in the exclusive range `(MIN-1, MAX+1)`.
295if size_of::<$f>() > size_of::<$i>() {
296// With a larger size, we can represent the range exactly.
297const MIN_M1: $f = $i::MIN as $f - 1.0;
298const MAX_P1: $f = $i::MAX as $f + 1.0;
299if *self > MIN_M1 && *self < MAX_P1 {
300return Some(float_to_int_unchecked!(*self => $i));
301 }
302 } else {
303// We can't represent `MIN-1` exactly, but there's no fractional part
304 // at this magnitude, so we can just use a `MIN` inclusive boundary.
305const MIN: $f = $i::MIN as $f;
306// We can't represent `MAX` exactly, but it will round up to exactly
307 // `MAX+1` (a power of two) when we cast it.
308const MAX_P1: $f = $i::MAX as $f;
309if *self >= MIN && *self < MAX_P1 {
310return Some(float_to_int_unchecked!(*self => $i));
311 }
312 }
313None
314}
315 )*}
316}
317318macro_rules! impl_to_primitive_float_to_unsigned_int {
319 ($f:ident : $( $(#[$cfg:meta])* fn $method:ident -> $u:ident ; )*) => {$(
320#[inline]
321$(#[$cfg])*
322fn $method(&self) -> Option<$u> {
323// Float as int truncates toward zero, so we want to allow values
324 // in the exclusive range `(-1, MAX+1)`.
325if size_of::<$f>() > size_of::<$u>() {
326// With a larger size, we can represent the range exactly.
327const MAX_P1: $f = $u::MAX as $f + 1.0;
328if *self > -1.0 && *self < MAX_P1 {
329return Some(float_to_int_unchecked!(*self => $u));
330 }
331 } else {
332// We can't represent `MAX` exactly, but it will round up to exactly
333 // `MAX+1` (a power of two) when we cast it.
334 // (`u128::MAX as f32` is infinity, but this is still ok.)
335const MAX_P1: $f = $u::MAX as $f;
336if *self > -1.0 && *self < MAX_P1 {
337return Some(float_to_int_unchecked!(*self => $u));
338 }
339 }
340None
341}
342 )*}
343}
344345macro_rules! impl_to_primitive_float {
346 ($T:ident) => {
347impl ToPrimitive for $T {
348impl_to_primitive_float_to_signed_int! { $T:
349fn to_isize -> isize;
350fn to_i8 -> i8;
351fn to_i16 -> i16;
352fn to_i32 -> i32;
353fn to_i64 -> i64;
354fn to_i128 -> i128;
355 }
356357impl_to_primitive_float_to_unsigned_int! { $T:
358fn to_usize -> usize;
359fn to_u8 -> u8;
360fn to_u16 -> u16;
361fn to_u32 -> u32;
362fn to_u64 -> u64;
363fn to_u128 -> u128;
364 }
365366impl_to_primitive_float_to_float! { $T:
367fn to_f32 -> f32;
368fn to_f64 -> f64;
369 }
370 }
371 };
372}
373374impl_to_primitive_float!(f32);
375impl_to_primitive_float!(f64);
376377/// A generic trait for converting a number to a value.
378///
379/// A value can be represented by the target type when it lies within
380/// the range of scalars supported by the target type.
381/// For example, a negative integer cannot be represented by an unsigned
382/// integer type, and an `i64` with a very high magnitude might not be
383/// convertible to an `i32`.
384/// On the other hand, conversions with possible precision loss or truncation
385/// are admitted, like an `f32` with a decimal part to an integer type, or
386/// even a large `f64` saturating to `f32` infinity.
387pub trait FromPrimitive: Sized {
388/// Converts an `isize` to return an optional value of this type. If the
389 /// value cannot be represented by this type, then `None` is returned.
390#[inline]
391fn from_isize(n: isize) -> Option<Self> {
392 n.to_i64().and_then(FromPrimitive::from_i64)
393 }
394395/// Converts an `i8` to return an optional value of this type. If the
396 /// value cannot be represented by this type, then `None` is returned.
397#[inline]
398fn from_i8(n: i8) -> Option<Self> {
399 FromPrimitive::from_i64(From::from(n))
400 }
401402/// Converts an `i16` to return an optional value of this type. If the
403 /// value cannot be represented by this type, then `None` is returned.
404#[inline]
405fn from_i16(n: i16) -> Option<Self> {
406 FromPrimitive::from_i64(From::from(n))
407 }
408409/// Converts an `i32` to return an optional value of this type. If the
410 /// value cannot be represented by this type, then `None` is returned.
411#[inline]
412fn from_i32(n: i32) -> Option<Self> {
413 FromPrimitive::from_i64(From::from(n))
414 }
415416/// Converts an `i64` to return an optional value of this type. If the
417 /// value cannot be represented by this type, then `None` is returned.
418fn from_i64(n: i64) -> Option<Self>;
419420/// Converts an `i128` to return an optional value of this type. If the
421 /// value cannot be represented by this type, then `None` is returned.
422 ///
423 /// The default implementation converts through `from_i64()`. Types implementing
424 /// this trait should override this method if they can represent a greater range.
425#[inline]
426fn from_i128(n: i128) -> Option<Self> {
427 n.to_i64().and_then(FromPrimitive::from_i64)
428 }
429430/// Converts a `usize` to return an optional value of this type. If the
431 /// value cannot be represented by this type, then `None` is returned.
432#[inline]
433fn from_usize(n: usize) -> Option<Self> {
434 n.to_u64().and_then(FromPrimitive::from_u64)
435 }
436437/// Converts an `u8` to return an optional value of this type. If the
438 /// value cannot be represented by this type, then `None` is returned.
439#[inline]
440fn from_u8(n: u8) -> Option<Self> {
441 FromPrimitive::from_u64(From::from(n))
442 }
443444/// Converts an `u16` to return an optional value of this type. If the
445 /// value cannot be represented by this type, then `None` is returned.
446#[inline]
447fn from_u16(n: u16) -> Option<Self> {
448 FromPrimitive::from_u64(From::from(n))
449 }
450451/// Converts an `u32` to return an optional value of this type. If the
452 /// value cannot be represented by this type, then `None` is returned.
453#[inline]
454fn from_u32(n: u32) -> Option<Self> {
455 FromPrimitive::from_u64(From::from(n))
456 }
457458/// Converts an `u64` to return an optional value of this type. If the
459 /// value cannot be represented by this type, then `None` is returned.
460fn from_u64(n: u64) -> Option<Self>;
461462/// Converts an `u128` to return an optional value of this type. If the
463 /// value cannot be represented by this type, then `None` is returned.
464 ///
465 /// The default implementation converts through `from_u64()`. Types implementing
466 /// this trait should override this method if they can represent a greater range.
467#[inline]
468fn from_u128(n: u128) -> Option<Self> {
469 n.to_u64().and_then(FromPrimitive::from_u64)
470 }
471472/// Converts a `f32` to return an optional value of this type. If the
473 /// value cannot be represented by this type, then `None` is returned.
474#[inline]
475fn from_f32(n: f32) -> Option<Self> {
476 FromPrimitive::from_f64(From::from(n))
477 }
478479/// Converts a `f64` to return an optional value of this type. If the
480 /// value cannot be represented by this type, then `None` is returned.
481 ///
482 /// The default implementation tries to convert through `from_i64()`, and
483 /// failing that through `from_u64()`. Types implementing this trait should
484 /// override this method if they can represent a greater range.
485#[inline]
486fn from_f64(n: f64) -> Option<Self> {
487match n.to_i64() {
488Some(i) => FromPrimitive::from_i64(i),
489None => n.to_u64().and_then(FromPrimitive::from_u64),
490 }
491 }
492}
493494macro_rules! impl_from_primitive {
495 ($T:ty, $to_ty:ident) => {
496#[allow(deprecated)]
497impl FromPrimitive for $T {
498#[inline]
499fn from_isize(n: isize) -> Option<$T> {
500 n.$to_ty()
501 }
502#[inline]
503fn from_i8(n: i8) -> Option<$T> {
504 n.$to_ty()
505 }
506#[inline]
507fn from_i16(n: i16) -> Option<$T> {
508 n.$to_ty()
509 }
510#[inline]
511fn from_i32(n: i32) -> Option<$T> {
512 n.$to_ty()
513 }
514#[inline]
515fn from_i64(n: i64) -> Option<$T> {
516 n.$to_ty()
517 }
518#[inline]
519fn from_i128(n: i128) -> Option<$T> {
520 n.$to_ty()
521 }
522523#[inline]
524fn from_usize(n: usize) -> Option<$T> {
525 n.$to_ty()
526 }
527#[inline]
528fn from_u8(n: u8) -> Option<$T> {
529 n.$to_ty()
530 }
531#[inline]
532fn from_u16(n: u16) -> Option<$T> {
533 n.$to_ty()
534 }
535#[inline]
536fn from_u32(n: u32) -> Option<$T> {
537 n.$to_ty()
538 }
539#[inline]
540fn from_u64(n: u64) -> Option<$T> {
541 n.$to_ty()
542 }
543#[inline]
544fn from_u128(n: u128) -> Option<$T> {
545 n.$to_ty()
546 }
547548#[inline]
549fn from_f32(n: f32) -> Option<$T> {
550 n.$to_ty()
551 }
552#[inline]
553fn from_f64(n: f64) -> Option<$T> {
554 n.$to_ty()
555 }
556 }
557 };
558}
559560impl_from_primitive!(isize, to_isize);
561impl_from_primitive!(i8, to_i8);
562impl_from_primitive!(i16, to_i16);
563impl_from_primitive!(i32, to_i32);
564impl_from_primitive!(i64, to_i64);
565impl_from_primitive!(i128, to_i128);
566impl_from_primitive!(usize, to_usize);
567impl_from_primitive!(u8, to_u8);
568impl_from_primitive!(u16, to_u16);
569impl_from_primitive!(u32, to_u32);
570impl_from_primitive!(u64, to_u64);
571impl_from_primitive!(u128, to_u128);
572impl_from_primitive!(f32, to_f32);
573impl_from_primitive!(f64, to_f64);
574575macro_rules! impl_to_primitive_wrapping {
576 ($( $(#[$cfg:meta])* fn $method:ident -> $i:ident ; )*) => {$(
577#[inline]
578$(#[$cfg])*
579fn $method(&self) -> Option<$i> {
580 (self.0).$method()
581 }
582 )*}
583}
584585impl<T: ToPrimitive> ToPrimitive for Wrapping<T> {
586impl_to_primitive_wrapping! {
587fn to_isize -> isize;
588fn to_i8 -> i8;
589fn to_i16 -> i16;
590fn to_i32 -> i32;
591fn to_i64 -> i64;
592fn to_i128 -> i128;
593594fn to_usize -> usize;
595fn to_u8 -> u8;
596fn to_u16 -> u16;
597fn to_u32 -> u32;
598fn to_u64 -> u64;
599fn to_u128 -> u128;
600601fn to_f32 -> f32;
602fn to_f64 -> f64;
603 }
604}
605606macro_rules! impl_from_primitive_wrapping {
607 ($( $(#[$cfg:meta])* fn $method:ident ( $i:ident ); )*) => {$(
608#[inline]
609$(#[$cfg])*
610fn $method(n: $i) -> Option<Self> {
611 T::$method(n).map(Wrapping)
612 }
613 )*}
614}
615616impl<T: FromPrimitive> FromPrimitive for Wrapping<T> {
617impl_from_primitive_wrapping! {
618fn from_isize(isize);
619fn from_i8(i8);
620fn from_i16(i16);
621fn from_i32(i32);
622fn from_i64(i64);
623fn from_i128(i128);
624625fn from_usize(usize);
626fn from_u8(u8);
627fn from_u16(u16);
628fn from_u32(u32);
629fn from_u64(u64);
630fn from_u128(u128);
631632fn from_f32(f32);
633fn from_f64(f64);
634 }
635}
636637/// Cast from one machine scalar to another.
638///
639/// # Examples
640///
641/// ```
642/// # use num_traits as num;
643/// let twenty: f32 = num::cast(0x14).unwrap();
644/// assert_eq!(twenty, 20f32);
645/// ```
646///
647#[inline]
648pub fn cast<T: NumCast, U: NumCast>(n: T) -> Option<U> {
649 NumCast::from(n)
650}
651652/// An interface for casting between machine scalars.
653pub trait NumCast: Sized + ToPrimitive {
654/// Creates a number from another value that can be converted into
655 /// a primitive via the `ToPrimitive` trait. If the source value cannot be
656 /// represented by the target type, then `None` is returned.
657 ///
658 /// A value can be represented by the target type when it lies within
659 /// the range of scalars supported by the target type.
660 /// For example, a negative integer cannot be represented by an unsigned
661 /// integer type, and an `i64` with a very high magnitude might not be
662 /// convertible to an `i32`.
663 /// On the other hand, conversions with possible precision loss or truncation
664 /// are admitted, like an `f32` with a decimal part to an integer type, or
665 /// even a large `f64` saturating to `f32` infinity.
666fn from<T: ToPrimitive>(n: T) -> Option<Self>;
667}
668669macro_rules! impl_num_cast {
670 ($T:ty, $conv:ident) => {
671impl NumCast for $T {
672#[inline]
673 #[allow(deprecated)]
674fn from<N: ToPrimitive>(n: N) -> Option<$T> {
675// `$conv` could be generated using `concat_idents!`, but that
676 // macro seems to be broken at the moment
677n.$conv()
678 }
679 }
680 };
681}
682683impl_num_cast!(u8, to_u8);
684impl_num_cast!(u16, to_u16);
685impl_num_cast!(u32, to_u32);
686impl_num_cast!(u64, to_u64);
687impl_num_cast!(u128, to_u128);
688impl_num_cast!(usize, to_usize);
689impl_num_cast!(i8, to_i8);
690impl_num_cast!(i16, to_i16);
691impl_num_cast!(i32, to_i32);
692impl_num_cast!(i64, to_i64);
693impl_num_cast!(i128, to_i128);
694impl_num_cast!(isize, to_isize);
695impl_num_cast!(f32, to_f32);
696impl_num_cast!(f64, to_f64);
697698impl<T: NumCast> NumCast for Wrapping<T> {
699fn from<U: ToPrimitive>(n: U) -> Option<Self> {
700 T::from(n).map(Wrapping)
701 }
702}
703704/// A generic interface for casting between machine scalars with the
705/// `as` operator, which admits narrowing and precision loss.
706/// Implementers of this trait `AsPrimitive` should behave like a primitive
707/// numeric type (e.g. a newtype around another primitive), and the
708/// intended conversion must never fail.
709///
710/// # Examples
711///
712/// ```
713/// # use num_traits::AsPrimitive;
714/// let three: i32 = (3.14159265f32).as_();
715/// assert_eq!(three, 3);
716/// ```
717///
718/// # Safety
719///
720/// **In Rust versions before 1.45.0**, some uses of the `as` operator were not entirely safe.
721/// In particular, it was undefined behavior if
722/// a truncated floating point value could not fit in the target integer
723/// type ([#10184](https://github.com/rust-lang/rust/issues/10184)).
724///
725/// ```ignore
726/// # use num_traits::AsPrimitive;
727/// let x: u8 = (1.04E+17).as_(); // UB
728/// ```
729///
730pub trait AsPrimitive<T>: 'static + Copy
731where
732T: 'static + Copy,
733{
734/// Convert a value to another, using the `as` operator.
735fn as_(self) -> T;
736}
737738macro_rules! impl_as_primitive {
739 (@ $T: ty => $(#[$cfg:meta])* impl $U: ty ) => {
740 $(#[$cfg])*
741impl AsPrimitive<$U> for $T {
742#[inline] fn as_(self) -> $U { self as $U }
743 }
744 };
745 (@ $T: ty => { $( $U: ty ),* } ) => {$(
746impl_as_primitive!(@ $T => impl $U);
747 )*};
748 ($T: ty => { $( $U: ty ),* } ) => {
749impl_as_primitive!(@ $T => { $( $U ),* });
750impl_as_primitive!(@ $T => { u8, u16, u32, u64, u128, usize });
751impl_as_primitive!(@ $T => { i8, i16, i32, i64, i128, isize });
752 };
753}
754755impl_as_primitive!(u8 => { char, f32, f64 });
756impl_as_primitive!(i8 => { f32, f64 });
757impl_as_primitive!(u16 => { f32, f64 });
758impl_as_primitive!(i16 => { f32, f64 });
759impl_as_primitive!(u32 => { f32, f64 });
760impl_as_primitive!(i32 => { f32, f64 });
761impl_as_primitive!(u64 => { f32, f64 });
762impl_as_primitive!(i64 => { f32, f64 });
763impl_as_primitive!(u128 => { f32, f64 });
764impl_as_primitive!(i128 => { f32, f64 });
765impl_as_primitive!(usize => { f32, f64 });
766impl_as_primitive!(isize => { f32, f64 });
767impl_as_primitive!(f32 => { f32, f64 });
768impl_as_primitive!(f64 => { f32, f64 });
769impl_as_primitive!(char => { char });
770impl_as_primitive!(bool => {});