Skip to main content

oxabl_cache_format/
ids.rs

1//! Fixed-length identifiers and their lowercase hex form.
2
3use std::fmt;
4
5use crate::error::{FormatError, Result};
6
7/// Ed25519 public key.
8pub type PublicKey = [u8; 32];
9/// Ed25519 signature.
10pub type Signature = [u8; 64];
11
12macro_rules! id_type {
13    ($(#[$doc:meta])* $name:ident, $len:literal) => {
14        $(#[$doc])*
15        #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
16        pub struct $name(pub [u8; $len]);
17
18        impl $name {
19            /// Length in bytes.
20            pub const LEN: usize = $len;
21
22            /// Lowercase hex, `2 * LEN` characters.
23            pub fn to_hex(&self) -> String {
24                to_hex(&self.0)
25            }
26
27            /// Parses lowercase hex of exactly `2 * LEN` characters.
28            pub fn from_hex(s: &str) -> Result<Self> {
29                let mut out = [0u8; $len];
30                from_hex(s, &mut out)?;
31                Ok(Self(out))
32            }
33        }
34
35        impl From<[u8; $len]> for $name {
36            fn from(bytes: [u8; $len]) -> Self {
37                Self(bytes)
38            }
39        }
40
41        impl fmt::Display for $name {
42            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43                f.write_str(&self.to_hex())
44            }
45        }
46
47        impl fmt::Debug for $name {
48            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49                write!(f, "{}({})", stringify!($name), self.to_hex())
50            }
51        }
52    };
53}
54
55id_type!(
56    /// Keyed lookup id of a compile key.
57    LookupId,
58    32
59);
60id_type!(
61    /// BLAKE3 of a sealed segment; also names a dictionary segment.
62    SegmentId,
63    32
64);
65id_type!(
66    /// Server-assigned pack id.
67    PackId,
68    16
69);
70id_type!(
71    /// Cache id as raw bytes.
72    CacheId,
73    16
74);
75id_type!(
76    /// Tenant id as raw bytes.
77    TenantId,
78    16
79);
80id_type!(
81    /// Request id as raw bytes.
82    RequestId,
83    16
84);
85
86const HEX: &[u8; 16] = b"0123456789abcdef";
87
88fn to_hex(bytes: &[u8]) -> String {
89    let mut out = String::with_capacity(bytes.len() * 2);
90    for b in bytes {
91        out.push(char::from(HEX[usize::from(b >> 4)]));
92        out.push(char::from(HEX[usize::from(b & 15)]));
93    }
94    out
95}
96
97fn nibble(c: u8) -> Result<u8> {
98    match c {
99        b'0'..=b'9' => Ok(c - b'0'),
100        b'a'..=b'f' => Ok(c - b'a' + 10),
101        _ => Err(FormatError::Invalid("hex digit")),
102    }
103}
104
105fn from_hex(s: &str, out: &mut [u8]) -> Result<()> {
106    let s = s.as_bytes();
107    if s.len() != out.len() * 2 {
108        return Err(FormatError::Invalid("hex length"));
109    }
110    for (i, byte) in out.iter_mut().enumerate() {
111        *byte = nibble(s[2 * i])? << 4 | nibble(s[2 * i + 1])?;
112    }
113    Ok(())
114}