osom_encoders_x86_64/models/
size.rs

1use osom_encoders_common::osom_debug_assert;
2
3/// Represents all the sizes used by the project from the X64 instruction set.
4#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
5#[repr(u8)]
6#[must_use]
7pub enum Size {
8    Bit8 = 1, // We start from 1 to allow Option<Size> optimization
9    Bit16,
10    Bit32,
11    Bit64,
12}
13
14impl Size {
15    #[inline(always)]
16    #[must_use]
17    pub const fn as_u8(self) -> u8 {
18        let result = self as u8;
19        unsafe { core::hint::assert_unchecked(result <= 15) };
20        result
21    }
22
23    /// Creates a new `Size` from a `u8` index.
24    ///
25    /// # Safety
26    ///
27    /// The index must be in the range `1..=4`, otherwise the behavior is undefined.
28    #[inline(always)]
29    pub const unsafe fn from_u8_unchecked(index: u8) -> Self {
30        osom_debug_assert!(index > 0 && index <= 4);
31        unsafe { core::mem::transmute(index) }
32    }
33
34    /// Creates a new `Size` from a `u8` index.
35    ///
36    /// # Returns
37    ///
38    /// - `Some(Size)` if the `u8` is in the range `1..=4`
39    /// - `None` if the `u8` is 0 or greater than 4
40    #[must_use]
41    pub const fn from_u8(value: u8) -> Option<Self> {
42        if value == 0 || value > 4 {
43            return None;
44        }
45        Some(unsafe { Self::from_u8_unchecked(value) })
46    }
47
48    /// The same as `==` operator but const.
49    #[inline(always)]
50    #[must_use]
51    pub const fn equals(self, other: Self) -> bool {
52        self.as_u8() == other.as_u8()
53    }
54}
55
56impl core::hash::Hash for Size {
57    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
58        self.as_u8().hash(state);
59    }
60}