Skip to main content

fastnum/decimal/udec/impls/
to.rs

1use crate::{
2    bint::ParseError,
3    decimal::{Decimal, UnsignedDecimal},
4};
5
6type D<const N: usize> = Decimal<N>;
7type UD<const N: usize> = UnsignedDecimal<N>;
8
9impl<const N: usize> From<UD<N>> for D<N> {
10    #[inline]
11    fn from(ud: UD<N>) -> Self {
12        ud.0
13    }
14}
15
16macro_rules! to_num_impls {
17    ($($name:ident $num:ty,)*) => {
18        $(
19            impl<const N: usize> TryFrom<UD<N>> for $num {
20                type Error = ParseError;
21
22                #[inline]
23                fn try_from(ud: UD<N>) -> Result<Self, Self::Error> {
24                    <$num>::try_from(ud.0)
25                }
26            }
27        )*
28
29        impl<const N: usize> UD<N> {
30            $(
31                #[inline]
32                #[doc = concat!("Try converts [UnsignedDecimal] into [`", stringify!($num), "`].")]
33                pub const fn $name(self) -> Result<$num, ParseError> {
34                    self.0.$name()
35                }
36            )*
37        }
38    }
39}
40
41to_num_impls!(
42    to_u8 u8,
43    to_u16 u16,
44    to_u32 u32,
45    to_u64 u64,
46    to_u128 u128,
47    to_usize usize,
48
49    to_i8 i8,
50    to_i16 i16,
51    to_i32 i32,
52    to_i64 i64,
53    to_i128 i128,
54    to_isize isize,
55);
56
57impl<const N: usize> From<UD<N>> for f32 {
58    #[inline]
59    fn from(d: UD<N>) -> f32 {
60        f32::from(d.0)
61    }
62}
63
64impl<const N: usize> From<UD<N>> for f64 {
65    #[inline]
66    fn from(d: UD<N>) -> f64 {
67        f64::from(d.0)
68    }
69}
70
71impl<const N: usize> UD<N> {
72    /// Converts [UnsignedDecimal] into [`f32`].
73    pub const fn to_f32(self) -> f32 {
74        self.0.to_f32()
75    }
76
77    /// Converts [UnsignedDecimal] into [`f64`].
78    pub const fn to_f64(self) -> f64 {
79        self.0.to_f64()
80    }
81}