lcd1602_driver/
utils.rs

1//! Common tools
2
3/// The state of a bit,
4/// It's either [`BitState::Clear`] to represent a 0
5/// or [`BitState::Set`] to represent a 1
6#[derive(PartialEq)]
7pub enum BitState {
8    /// Bit is 0
9    Clear,
10    /// Bit is 1
11    Set,
12}
13
14/// Simple bit ops
15pub trait BitOps {
16    #[allow(missing_docs)]
17    fn set_bit(&mut self, pos: u8) -> Self;
18    #[allow(missing_docs)]
19    fn clear_bit(&mut self, pos: u8) -> Self;
20    #[allow(missing_docs)]
21    fn check_bit(&self, pos: u8) -> BitState;
22}
23
24impl BitOps for u8 {
25    fn set_bit(&mut self, pos: u8) -> Self {
26        assert!(pos <= 7, "bit offset larger than 7");
27        *self |= 1u8 << pos;
28        *self
29    }
30
31    fn clear_bit(&mut self, pos: u8) -> Self {
32        assert!(pos <= 7, "bit offset larger than 7");
33        *self &= !(1u8 << pos);
34        *self
35    }
36
37    fn check_bit(&self, pos: u8) -> BitState {
38        assert!(pos <= 7, "bit offset larger than 7");
39
40        match self.checked_shr(pos as u32).unwrap() & 1 == 1 {
41            true => BitState::Set,
42            false => BitState::Clear,
43        }
44    }
45}