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 pub fn from_lo(raw: u8) -> Self {
11 Self(raw & 0x0f)
12 }
13
14 /// Constructs a nibble from the 4 high/leftmost bits of a byte.
15 pub fn from_hi(raw: u8) -> Self {
16 Self(raw >> 4)
17 }
18
19 /// Constructs a byte with the nibble set as the 4 low/rightmost bits.
20 pub fn to_lo(self) -> u8 {
21 self.0
22 }
23
24 /// Constructs a byte with the nibble set as the 4 high/leftmost bits.
25 pub fn to_hi(self) -> u8 {
26 self.0 << 4
27 }
28}
29
30/// Combines two nibbles to a byte, with `a` being set to the 4 leftmost and
31/// `b` being set to the 4 rightmost bits.
32pub fn combine(a: U4, b: U4) -> u8 {
33 a.to_hi() | b.to_lo()
34}