xrunits/
data.rs

1use crate::{Unit,CastTo};
2use std::fmt::{Display, Formatter};
3
4pub trait Data : Unit + From<f64> {}
5
6macro_rules! build_type {
7    ($type_name : ident,
8     $trait_name : ident,
9     $short_name : ident,
10     $display_name : expr,
11     $num : expr,$den : expr) => {
12        #[derive(Debug,Copy,Clone,PartialEq,PartialOrd)]
13        pub struct $type_name(f64);
14        impl<T : Into<f64>> From<T> for $type_name {
15            fn from(other : T) -> Self {
16                $type_name(other.into())
17            }
18        }
19        pub trait $trait_name {
20            fn $short_name(self) -> $type_name;
21        }
22        impl<T : Into<f64>> $trait_name for T {
23            fn $short_name(self) -> $type_name {
24                $type_name(self.into())
25            }
26        }
27        impl Unit for $type_name {
28            const NUM: i32 = $num;
29            const DEN: i32 = $den;
30
31            fn value(&self) -> f64 {
32                self.0
33            }
34        }
35        impl Data for $type_name {}
36        impl Display for $type_name {
37            fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
38                write!(f,concat!("{}",$display_name),self.0)
39            }
40        }
41        impl<T : Data> CastTo<T> for $type_name {}
42    };
43}
44// too large
45// build_type!(Tebibyte,BuildTebibyte,tib,"TiB",137_438_953_472,1);
46build_type!(Gibibyte,BuildGibibyte,gib,"GiB",1_073_741_824,1);
47build_type!(Mebibyte,BuildMebibyte,mib,"MiB",1_048_576,1);
48build_type!(Kibibyte,BuildKibibyte,kib,"KiB",1024,1);
49build_type!(Byte,BuildByte,byte,"Byte",1,1);
50build_type!(Bit,BuildBit,bit,"Bit",1,8);
51
52#[cfg(test)]
53mod tests{
54    use crate::CastTo;
55    use crate::data::{BuildGibibyte, Mebibyte};
56
57    #[test]
58    fn test() {
59        let gb2 = 2.gib();
60        let mb : Mebibyte = gb2.cast_to();
61        println!("{}={}",gb2,mb);
62    }
63}