Skip to main content

osom_encoders_x86_64/models/
encoded_instruction.rs

1use _osom_encoders_common::fixed_bytes::FixedBytes;
2
3/// Represents a binary encoded `X86_64` instruction.
4#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5#[repr(transparent)]
6#[must_use]
7pub struct EncodedX86_64Instruction {
8    value: FixedBytes<15>,
9}
10
11impl EncodedX86_64Instruction {
12    /// The maximum size (in bytes) of an encoded `X86_64` instruction.
13    pub const MAX_SIZE: usize = 15;
14
15    /// Represents the [`EncodedX86_64Instruction`] as a slice of bytes.
16    #[inline(always)]
17    #[must_use]
18    pub const fn as_slice(&self) -> &[u8] {
19        self.value.as_slice()
20    }
21
22    /// Represents the [`EncodedX86_64Instruction`] as a slice of bytes.
23    #[inline(always)]
24    #[must_use]
25    pub const fn as_slice_mut(&mut self) -> &mut [u8] {
26        self.value.as_slice_mut()
27    }
28
29    /// Creates a new [`EncodedX86_64Instruction`] from an array of `SIZE` bytes.
30    ///
31    /// # Panics
32    ///
33    /// This function panics if the array is too large.
34    #[inline]
35    pub const fn from_array<const SIZE: usize>(array: [u8; SIZE]) -> Self {
36        if SIZE == 0 {
37            return Self::new();
38        }
39
40        const {
41            assert!(SIZE <= Self::MAX_SIZE, "SIZE must be less than or equal to MAX_SIZE");
42        }
43        let mut result = Self::new();
44        result.push_array(array);
45        result
46    }
47
48    /// Creates a new, empty [`EncodedX86_64Instruction`].
49    #[inline]
50    pub(crate) const fn new() -> Self {
51        Self {
52            value: FixedBytes::new(),
53        }
54    }
55
56    /// Pushes an array of `N` bytes to the instruction.
57    ///
58    /// # Panics
59    ///
60    /// This function panics if the array is too large.
61    #[inline]
62    pub(crate) const fn push_array<const SIZE: usize>(&mut self, array: [u8; SIZE]) {
63        if SIZE == 0 {
64            return;
65        }
66
67        const {
68            assert!(SIZE <= Self::MAX_SIZE, "SIZE must be less than or equal to MAX_SIZE");
69        }
70        self.value.push_array(array);
71    }
72
73    /// Pushes slice to the instruction.
74    ///
75    /// # Panics
76    ///
77    /// This function panics if the slice is too large.
78    #[inline]
79    pub(crate) const fn push_slice(&mut self, slice: &[u8]) {
80        self.value.push_slice(slice);
81    }
82}
83
84impl AsRef<[u8]> for EncodedX86_64Instruction {
85    #[inline(always)]
86    fn as_ref(&self) -> &[u8] {
87        self.as_slice()
88    }
89}
90
91impl AsMut<[u8]> for EncodedX86_64Instruction {
92    #[inline(always)]
93    fn as_mut(&mut self) -> &mut [u8] {
94        self.as_slice_mut()
95    }
96}