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
/// Traits for types that manipulate memory-mapped registers

pub trait RegisterRW {
    fn read(&self) -> u32;
    fn write(&self, val: u32);

    #[inline]
    fn set_bit(&self, bit_index: u32) {
        let w = self.read();
        let bit = 1 << bit_index;
        self.write(w | bit);
    }

    #[inline]
    fn clear_bit(&self, bit_index: u32) {
        let w = self.read();
        let bit = 1 << bit_index;
        self.write(w & (!bit));
    }
}

pub trait RegisterR {
    fn read(&self) -> u32;
}

pub trait RegisterW {
    fn write(&self, val: u32);

    #[inline]
    fn set_bit(&self, bit_index: u32) {
        // For this kind of register, reads always return zero
        // and zero bits have no effect, so we simply write the
        // single bit requested.
        let bit = 1 << bit_index;
        self.write(bit);
    }
}

pub trait ToWord {
    fn to_word(self) -> u32;
}

impl ToWord for u32 {
    #[inline]
    fn to_word(self) -> u32 {
        self
    }
}

impl ToWord for u8 {
    #[inline]
    fn to_word(self) -> u32 {
        self as u32
    }
}

impl ToWord for bool {
    #[inline]
    fn to_word(self) -> u32 {
        if self {
            1
        } else {
            0
        }
    }
}

pub trait FromWord {
    fn from_word(u32) -> Self;
}

impl FromWord for u32 {
    #[inline]
    fn from_word(w: u32) -> Self {
        w
    }
}

impl FromWord for bool {
    #[inline]
    fn from_word(w: u32) -> bool {
        if w & 1 == 1 {
            true
        } else {
            false
        }
    }
}