Skip to main content

memfork_core/
id.rs

1//! Content-addressed commit identifiers.
2
3use core::fmt;
4
5use crate::error::Error;
6
7/// A BLAKE3-derived, content-addressed commit id (DESIGN §4.1).
8///
9/// `CommitId` is a pure function of the commit's parents and its canonically
10/// encoded operations, so the same sequence of operations produces the same ids
11/// on every operating system (DESIGN §3.6), which a golden file pins.
12#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
13pub struct CommitId(pub(crate) [u8; 32]);
14
15impl CommitId {
16    /// The raw 32 bytes of the id.
17    pub fn as_bytes(&self) -> &[u8; 32] {
18        &self.0
19    }
20
21    /// Rebuild an id from its raw bytes.
22    ///
23    /// Used when reading a journal record back. Nothing checks that the bytes
24    /// are the hash of anything: replay recomputes every id it installs, and
25    /// an id read from a record is only a reference to a commit replay has
26    /// already rebuilt.
27    pub fn from_bytes(bytes: [u8; 32]) -> Self {
28        CommitId(bytes)
29    }
30
31    /// The lowercase hex form, 64 characters.
32    pub fn to_hex(self) -> String {
33        let mut s = String::with_capacity(64);
34        for b in self.0 {
35            s.push(hex_digit(b >> 4));
36            s.push(hex_digit(b & 0x0f));
37        }
38        s
39    }
40
41    /// Parse a full 64-character lowercase or uppercase hex id.
42    pub fn from_hex(s: &str) -> Result<Self, Error> {
43        let bytes = s.as_bytes();
44        if bytes.len() != 64 {
45            return Err(Error::BadCommitId(s.to_owned()));
46        }
47        let mut out = [0u8; 32];
48        for (i, pair) in bytes.chunks_exact(2).enumerate() {
49            let hi = hex_value(pair[0]).ok_or_else(|| Error::BadCommitId(s.to_owned()))?;
50            let lo = hex_value(pair[1]).ok_or_else(|| Error::BadCommitId(s.to_owned()))?;
51            out[i] = (hi << 4) | lo;
52        }
53        Ok(CommitId(out))
54    }
55}
56
57fn hex_digit(nibble: u8) -> char {
58    match nibble {
59        0..=9 => (b'0' + nibble) as char,
60        _ => (b'a' + nibble - 10) as char,
61    }
62}
63
64fn hex_value(c: u8) -> Option<u8> {
65    match c {
66        b'0'..=b'9' => Some(c - b'0'),
67        b'a'..=b'f' => Some(c - b'a' + 10),
68        b'A'..=b'F' => Some(c - b'A' + 10),
69        _ => None,
70    }
71}
72
73impl fmt::Display for CommitId {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        f.write_str(&self.to_hex())
76    }
77}
78
79impl fmt::Debug for CommitId {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        write!(f, "CommitId({})", self.to_hex())
82    }
83}