Skip to main content

kernel/lib/types/
packed_u8.rs

1// SPDX-License-Identifier: GPL-3.0-only
2//! Packed u8; store multiple values shorter than 8 bits in one byte
3//!
4//! Authors: MarioS271
5
6#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
7#[repr(transparent)]
8pub struct PackedU8(u8);
9
10impl PackedU8 {
11    /// Get `bits` bits starting from bit `start`
12    pub fn get(self, start: u8, bits: u8) -> u8 {
13        (self.0 >> start) & ((1 << bits) - 1)
14    }
15
16    /// Set `bits` bits starting from bit `start` to `value`
17    /// `value` will be shortened to `bits` bits to avoid overwriting other data
18    pub fn set(&mut self, start: u8, bits: u8, value: u8) {
19        let mask = ((1 << bits) - 1) << start;
20        self.0 = (self.0 & !mask) | ((value << start) & mask);
21    }
22}
23
24impl Default for PackedU8 {
25    fn default() -> Self {
26        Self(0)
27    }
28}