Skip to main content

oxabl_cache_format/
namespace.rs

1use crate::error::{FormatError, Result};
2
3/// Cache namespace of an entry.
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5pub enum Namespace {
6    Trusted,
7    Personal,
8}
9
10impl Namespace {
11    pub fn to_u8(self) -> u8 {
12        match self {
13            Self::Trusted => 0,
14            Self::Personal => 1,
15        }
16    }
17
18    pub fn from_u8(v: u8) -> Result<Self> {
19        match v {
20            0 => Ok(Self::Trusted),
21            1 => Ok(Self::Personal),
22            _ => Err(FormatError::Invalid("namespace")),
23        }
24    }
25}
26
27/// Set of namespaces a lookup asks about. At least one is set in an encodable value.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub struct Namespaces {
30    pub trusted: bool,
31    pub personal: bool,
32}
33
34impl Namespaces {
35    pub fn contains(&self, ns: Namespace) -> bool {
36        match ns {
37            Namespace::Trusted => self.trusted,
38            Namespace::Personal => self.personal,
39        }
40    }
41
42    pub fn len(&self) -> usize {
43        usize::from(self.trusted) + usize::from(self.personal)
44    }
45
46    pub fn is_empty(&self) -> bool {
47        self.len() == 0
48    }
49
50    pub(crate) fn to_bits(self) -> u8 {
51        u8::from(self.trusted) | u8::from(self.personal) << 1
52    }
53
54    pub(crate) fn from_bits(bits: u8) -> Result<Self> {
55        if bits & !0b11 != 0 || bits == 0 {
56            return Err(FormatError::Invalid("namespaces"));
57        }
58        Ok(Self {
59            trusted: bits & 1 != 0,
60            personal: bits & 2 != 0,
61        })
62    }
63}