| 1 | use std::cmp; |
| 2 | |
| 3 | use crate::{hwdb, Error, Result}; |
| 4 | |
| 5 | /// Trie child entry in the hardware database. |
| 6 | /// |
| 7 | /// Array of child entries that directly follows the node record. |
| 8 | #[repr(C, packed(8))] |
| 9 | #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] |
| 10 | pub struct TrieChildEntry { |
| 11 | c: u8, |
| 12 | _padding: [u8; 7], |
| 13 | child_off: u64, |
| 14 | } |
| 15 | |
| 16 | impl TrieChildEntry { |
| 17 | /// Creates a new [TrieChildEntry]. |
| 18 | pub const fn new() -> Self { |
| 19 | Self { |
| 20 | c: 0, |
| 21 | _padding: [0u8; 7], |
| 22 | child_off: 0, |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | /// Gets the length of the encoded [TrieChildEntry]. |
| 27 | pub fn len(&self) -> usize { |
| 28 | hwdb::child_entry_size() |
| 29 | } |
| 30 | |
| 31 | /// Gets whether the [TrieChildEntry] is empty. |
| 32 | pub const fn is_empty(&self) -> bool { |
| 33 | false |
| 34 | } |
| 35 | |
| 36 | /// Gets the index of the child node. |
| 37 | pub const fn c(&self) -> u8 { |
| 38 | self.c |
| 39 | } |
| 40 | |
| 41 | /// Sets the index of the child node. |
| 42 | pub fn set_c(&mut self, val: u8) { |
| 43 | self.c = val; |
| 44 | } |
| 45 | |
| 46 | /// Builder function that sets the index of the child node. |
| 47 | pub fn with_c(mut self, val: u8) -> Self { |
| 48 | self.set_c(val); |
| 49 | self |
| 50 | } |
| 51 | |
| 52 | /// Gets the offset of the child node. |
| 53 | pub const fn child_off(&self) -> u64 { |
| 54 | self.child_off |
| 55 | } |
| 56 | |
| 57 | /// Sets the offset of the child node. |
| 58 | pub fn set_child_off(&mut self, val: u64) { |
| 59 | self.child_off = val; |
| 60 | } |
| 61 | |
| 62 | /// Builder function that sets the offset of the child node. |
| 63 | pub fn with_child_off(mut self, val: u64) -> Self { |
| 64 | self.set_child_off(val); |
| 65 | self |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | impl TryFrom<&[u8]> for TrieChildEntry { |
| 70 | type Error = Error; |
| 71 | |
| 72 | fn try_from(val: &[u8]) -> Result<Self> { |
| 73 | if val.len() < hwdb::child_entry_size() { |
| 74 | Err(Error::InvalidLen(val.len())) |
| 75 | } else { |
| 76 | // TODO: parse use get ranges and offsets |
| 77 | let mut idx = 0usize; |
| 78 | |
| 79 | let c = val[idx]; |
| 80 | let _padding = [0u8; 7]; |
| 81 | |
| 82 | // skip `c` index + padding |
| 83 | idx += 8; |
| 84 | |
| 85 | let child_off = |
| 86 | u64::from_le_bytes(val[idx..idx + std::mem::size_of::<u64>()].try_into()?); |
| 87 | |
| 88 | Ok(Self { |
| 89 | c, |
| 90 | _padding, |
| 91 | child_off, |
| 92 | }) |
| 93 | } |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | impl Ord for TrieChildEntry { |
| 98 | fn cmp(&self, other: &Self) -> cmp::Ordering { |
| 99 | self.c.cmp(&other.c) |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | impl PartialOrd for TrieChildEntry { |
| 104 | fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { |
| 105 | Some(self.c.cmp(&other.c)) |
| 106 | } |
| 107 | } |