null_kane/
constructor.rs

1use crate::{Currency, CurrencyLocale};
2
3/// Assumes that the f32 is meant as a money value, for example 10.99 would be 10.99
4impl<L> From<f32> for Currency<L>
5where
6    L: CurrencyLocale + Default,
7{
8    fn from(value: f32) -> Self {
9        let val = (value * 100.0).round().trunc().abs() as usize;
10        Self::new(value.is_sign_negative(), val, L::default())
11    }
12}
13
14impl<L> From<Currency<L>> for f32
15where
16    L: CurrencyLocale + Default,
17{
18    fn from(value: Currency<L>) -> Self {
19        let float = value.amount as f32 / 100.0;
20        if value.negative {
21            0.0 - float
22        } else {
23            float
24        }
25    }
26}
27
28/// Assumes that the f64 is meant as a money value, for example 10.99 would be 10.99
29impl<L> From<f64> for Currency<L>
30where
31    L: CurrencyLocale + Default,
32{
33    fn from(value: f64) -> Self {
34        let val = (value * 100.0).round().trunc().abs() as usize;
35        Self::new(value.is_sign_negative(), val, L::default())
36    }
37}
38
39macro_rules! from_unsigned {
40    ($x:ty) => (
41        impl<L> From<$x> for Currency<L>
42        where
43            L: CurrencyLocale + Default,
44        {
45            fn from(value: $x) -> Self {
46                Self::new(false, value as usize, L::default())
47            }
48        }
49
50    );
51     ($x:ty, $($y:ty),+) => (
52        from_unsigned!($x);
53        from_unsigned!($($y),+);
54        )
55}
56
57macro_rules! from_signed {
58    ($x:ty) => (
59        impl<L> From<$x> for Currency<L>
60        where
61            L: CurrencyLocale + Default,
62        {
63            fn from(value: $x) -> Self {
64                Self::new(value.is_negative(), value.abs() as usize, L::default())
65            }
66        }
67
68    );
69     ($x:ty, $($y:ty),+) => (
70        from_signed!($x);
71        from_signed!($($y),+);
72        )
73}
74
75from_signed!(i8, i16, i32, i64, isize);
76from_unsigned!(u8, u16, u32, u64, usize);