1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//! Extension traits that add convenience methods for working with bitrates and frequencies.

#![no_std]

/// Bits per second
#[derive(Clone, Copy, Debug)]
pub struct Bps<T>(pub T);

/// Hertz
#[derive(Clone, Copy, Debug)]
pub struct Hertz<T>(pub T);

/// KiloHertz
#[derive(Clone, Copy, Debug)]
pub struct KiloHertz<T>(pub T);

/// MegaHertz
#[derive(Clone, Copy, Debug)]
pub struct MegaHertz<T>(pub T);

/// Macro to add extension traits for integer types.
#[macro_export]
macro_rules! bitrate {
    ($(
        ($TXExt:ident, $tx:ident, $txstring:expr),
    )+) => {
        $(
            #[doc = "Extension trait that adds convenience methods to the `"]
            #[doc = $txstring]
            #[doc = "` type."]
            pub trait $TXExt<T> {
                /// Wrap in `Bps`
                fn bps(self) -> Bps<T>;

                /// Wrap in `Hertz`
                fn hz(self) -> Hertz<T>;

                /// Wrap in `KiloHertz`
                fn khz(self) -> KiloHertz<T>;

                /// Wrap in `MegaHertz`
                fn mhz(self) -> MegaHertz<T>;
            }

            impl $TXExt<$tx> for $tx {
                fn bps(self) -> Bps<$tx> {
                    Bps(self)
                }

                fn hz(self) -> Hertz<$tx> {
                    Hertz(self)
                }

                fn khz(self) -> KiloHertz<$tx> {
                    KiloHertz(self)
                }

                fn mhz(self) -> MegaHertz<$tx> {
                    MegaHertz(self)
                }
            }

            impl Into<Hertz<$tx>> for KiloHertz<$tx> {
                fn into(self) -> Hertz<$tx> {
                    Hertz(self.0 * 1_000)
                }
            }

            impl Into<Hertz<$tx>> for MegaHertz<$tx> {
                fn into(self) -> Hertz<$tx> {
                    Hertz(self.0 * 1_000_000)
                }
            }

            impl Into<KiloHertz<$tx>> for MegaHertz<$tx> {
                fn into(self) -> KiloHertz<$tx> {
                    KiloHertz(self.0 * 1_000)
                }
            }
        )+
    }
}

bitrate! {
    (U32BitrateExt, u32, "u32"),
    (U64BitrateExt, u64, "u64"),
    (U128BitrateExt, u128, "u128"),
    (USizeBitrateExt, usize, "usize"),
    (I32BitrateExt, i32, "i32"),
    (I64BitrateExt, i64, "i64"),
    (I128BitrateExt, i128, "i128"),
    (ISizeBitrateExt, isize, "isize"),
}