Skip to main content

sealmap_model/
hash.rs

1use std::fmt;
2
3use serde::{Deserialize, Serialize};
4
5/// A stable, portable content hash: BLAKE3 over text with `\r\n` and lone
6/// `\r` normalised to `\n`.
7///
8/// Displayed and serialised as `blake3:<64 hex chars>`, so the algorithm is
9/// self-describing if it ever changes.
10///
11/// ```
12/// use sealmap_model::ContentHash;
13///
14/// let unix = ContentHash::of_text("fn main() {}\n");
15/// let windows = ContentHash::of_text("fn main() {}\r\n");
16/// assert_eq!(unix, windows);
17/// assert!(unix.to_string().starts_with("blake3:"));
18/// ```
19#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
20#[serde(transparent)]
21pub struct ContentHash(String);
22
23impl ContentHash {
24    /// Hash `text` after normalising line endings.
25    pub fn of_text(text: &str) -> Self {
26        let normalised = normalise_newlines(text);
27        Self::of_bytes(normalised.as_bytes())
28    }
29
30    /// Hash raw bytes with no normalisation.
31    pub fn of_bytes(bytes: &[u8]) -> Self {
32        Self(format!("blake3:{}", blake3::hash(bytes).to_hex()))
33    }
34
35    /// Parse a previously displayed hash (`blake3:<hex>`).
36    ///
37    /// Returns `None` if the prefix or the hex payload is malformed.
38    pub fn parse(s: &str) -> Option<Self> {
39        let hex = s.strip_prefix("blake3:")?;
40        (hex.len() == 64 && hex.bytes().all(|b| b.is_ascii_hexdigit())).then(|| Self(s.to_ascii_lowercase()))
41    }
42
43    /// The full `blake3:<hex>` string.
44    pub fn as_str(&self) -> &str {
45        &self.0
46    }
47
48    /// The first `n` hex characters of the digest, handy for short stable ids.
49    pub fn short(&self, n: usize) -> &str {
50        let hex = &self.0["blake3:".len()..];
51        &hex[..n.min(hex.len())]
52    }
53}
54
55impl fmt::Display for ContentHash {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        f.write_str(&self.0)
58    }
59}
60
61/// A per-symbol content fingerprint: the first 16 bytes of a BLAKE3 digest.
62///
63/// Language adapters compute two per symbol (see `sealmap-extract`'s `fingerprint`
64/// module): `sig_hash` over the contract and `body_hash` over the
65/// implementation. The model only stores, compares, prints and parses them.
66///
67/// Displayed and serialised as `blake3-16:<32 hex chars>`. 128 bits keeps an
68/// accidental collision out of reach for any realistic number of symbols
69/// while halving the text a full digest would cost in every model and lock.
70///
71/// [`Fingerprint::default`] is all zeros and means "not fingerprinted": a
72/// symbol built by hand with [`Symbol::new`](crate::Symbol::new) carries it
73/// until a language adapter fills in real values.
74///
75/// ```
76/// use sealmap_model::Fingerprint;
77///
78/// let f = Fingerprint::from_bytes([0xab; 16]);
79/// let text = f.to_string();
80/// assert_eq!(text, format!("blake3-16:{}", "ab".repeat(16)));
81/// assert_eq!(Fingerprint::parse(&text), Some(f));
82/// assert!(Fingerprint::default().is_unset());
83/// ```
84#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
85pub struct Fingerprint([u8; 16]);
86
87impl Fingerprint {
88    /// The text prefix naming the algorithm and length.
89    pub const PREFIX: &'static str = "blake3-16:";
90
91    /// Wrap 16 digest bytes.
92    pub const fn from_bytes(bytes: [u8; 16]) -> Self {
93        Self(bytes)
94    }
95
96    /// Truncate a full BLAKE3 digest.
97    pub fn from_blake3(hash: &blake3::Hash) -> Self {
98        let mut b = [0u8; 16];
99        b.copy_from_slice(&hash.as_bytes()[..16]);
100        Self(b)
101    }
102
103    /// The digest bytes.
104    pub fn as_bytes(&self) -> &[u8; 16] {
105        &self.0
106    }
107
108    /// `true` for the all-zero "not fingerprinted" value.
109    pub fn is_unset(&self) -> bool {
110        self.0 == [0; 16]
111    }
112
113    /// Parse `blake3-16:<32 hex>` (either case).
114    pub fn parse(s: &str) -> Option<Self> {
115        let hex = s.strip_prefix(Self::PREFIX)?;
116        if hex.len() != 32 {
117            return None;
118        }
119        let mut b = [0u8; 16];
120        for (i, out) in b.iter_mut().enumerate() {
121            *out = u8::from_str_radix(hex.get(2 * i..2 * i + 2)?, 16).ok()?;
122        }
123        Some(Self(b))
124    }
125
126    /// Fold two fingerprints of the same symbol into one, independent of
127    /// their order. Used when `#[cfg]`-gated twins share an id and are
128    /// merged by [`Codebase::add_symbol`](crate::Codebase::add_symbol): a
129    /// change to either twin changes the merged value.
130    ///
131    /// ```
132    /// use sealmap_model::Fingerprint;
133    ///
134    /// let (a, b) = (Fingerprint::from_bytes([1; 16]), Fingerprint::from_bytes([2; 16]));
135    /// assert_eq!(a.merge(b), b.merge(a));
136    /// assert_ne!(a.merge(b), a);
137    /// ```
138    pub fn merge(self, other: Self) -> Self {
139        let (lo, hi) = if self <= other { (self, other) } else { (other, self) };
140        let mut h = blake3::Hasher::new_derive_key("sealmap sm1 2026-10 merged twin fingerprints");
141        h.update(&lo.0);
142        h.update(&hi.0);
143        Self::from_blake3(&h.finalize())
144    }
145}
146
147impl fmt::Display for Fingerprint {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        f.write_str(Self::PREFIX)?;
150        for b in &self.0 {
151            write!(f, "{b:02x}")?;
152        }
153        Ok(())
154    }
155}
156
157impl Serialize for Fingerprint {
158    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
159        serializer.collect_str(self)
160    }
161}
162
163impl<'de> Deserialize<'de> for Fingerprint {
164    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
165        let s = String::deserialize(deserializer)?;
166        Self::parse(&s).ok_or_else(|| serde::de::Error::custom(format!("invalid fingerprint `{s}`")))
167    }
168}
169
170/// Convert `\r\n` and lone `\r` to `\n`.
171pub(crate) fn normalise_newlines(text: &str) -> std::borrow::Cow<'_, str> {
172    if !text.contains('\r') {
173        return std::borrow::Cow::Borrowed(text);
174    }
175    std::borrow::Cow::Owned(text.replace("\r\n", "\n").replace('\r', "\n"))
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181
182    #[test]
183    fn parse_round_trips() {
184        let h = ContentHash::of_text("x");
185        assert_eq!(ContentHash::parse(h.as_str()), Some(h.clone()));
186        assert_eq!(ContentHash::parse("md5:abc"), None);
187        assert_eq!(h.short(8).len(), 8);
188    }
189}