Skip to main content

hidpp/
nibble.rs

1//! A very simple u4/nibble implementation.
2
3/// Represents an unsigned 4-bit value (nibble) encoded as a byte.
4#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
5#[cfg_attr(feature = "serde", derive(serde::Serialize))]
6pub struct U4(u8);
7
8impl U4 {
9    /// Constructs a nibble from the 4 low/rightmost bits of a byte.
10    #[must_use]
11    pub fn from_lo(raw: u8) -> Self {
12        Self(raw & 0x0f)
13    }
14
15    /// Constructs a nibble from the 4 high/leftmost bits of a byte.
16    #[must_use]
17    pub fn from_hi(raw: u8) -> Self {
18        Self(raw >> 4)
19    }
20
21    /// Constructs a byte with the nibble set as the 4 low/rightmost bits.
22    #[must_use]
23    pub fn to_lo(self) -> u8 {
24        self.0
25    }
26
27    /// Constructs a byte with the nibble set as the 4 high/leftmost bits.
28    #[must_use]
29    pub fn to_hi(self) -> u8 {
30        self.0 << 4
31    }
32}
33
34/// Combines two nibbles to a byte, with `a` being set to the 4 leftmost and
35/// `b` being set to the 4 rightmost bits.
36#[must_use]
37pub fn combine(a: U4, b: U4) -> u8 {
38    a.to_hi() | b.to_lo()
39}