diff --git a/Cargo.lock b/Cargo.lock index 3953c908..2c3c8620 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -154,7 +154,6 @@ version = "0.0.0" dependencies = [ "bough-typed-hash-derive", "facet", - "facet-json", "sha2", "tempfile", "tracing", diff --git a/crates/bough-cli/src/render.rs b/crates/bough-cli/src/render.rs index 6bcb84f9..d61cdfe4 100644 --- a/crates/bough-cli/src/render.rs +++ b/crates/bough-cli/src/render.rs @@ -1,7 +1,7 @@ use std::path::PathBuf; use bough_core::{LanguageId, Mutation}; -use bough_typed_hash::{MemoryHashStore, TypedHashable}; +use bough_typed_hash::TypedHashable; use facet::Facet; use crate::config::{Cli, Config, Format}; @@ -134,8 +134,7 @@ impl Render for MutantFiles { } fn mutation_hash(m: &Mutation) -> String { - let mut store = MemoryHashStore::new(); - let hash = m.hash(&mut store).expect("hashing should not fail"); + let hash = m.hash().expect("hashing should not fail"); format!("{hash}") } diff --git a/crates/bough-core/src/mutant.rs b/crates/bough-core/src/mutant.rs index e364a049..f81be7d9 100644 --- a/crates/bough-core/src/mutant.rs +++ b/crates/bough-core/src/mutant.rs @@ -641,8 +641,6 @@ mod tests { assert!(binary_ops.is_empty()); } - use bough_typed_hash::HashStore; - fn hash_mutant(mutant: &Mutant) -> [u8; 32] { use bough_typed_hash::sha2::Digest; let mut state = bough_typed_hash::ShaState::new(); @@ -744,9 +742,8 @@ mod tests { MutantKind::StatementBlock, Span::new(Point::new(0, 0, 0), Point::new(1, 0, 10)), ); - let mut store = bough_typed_hash::MemoryHashStore::new(); - let hash = m.hash(&mut store).unwrap(); - assert!(store.contains(&hash)); + let hash = m.hash().unwrap(); + assert_eq!(hash.to_string().len(), 64); } // bough[verify mutant.based.hash.base] @@ -827,9 +824,8 @@ mod tests { Span::new(Point::new(0, 0, 0), Point::new(1, 0, 10)), ); let based = BasedMutant::new(mutant, &base); - let mut store = bough_typed_hash::MemoryHashStore::new(); - let hash = based.hash(&mut store).unwrap(); - assert!(store.contains(&hash)); + let hash = based.hash().unwrap(); + assert_eq!(hash.to_string().len(), 64); } // bough[verify span.point] diff --git a/crates/bough-core/src/mutation.rs b/crates/bough-core/src/mutation.rs index 36df1379..18e9f5a4 100644 --- a/crates/bough-core/src/mutation.rs +++ b/crates/bough-core/src/mutation.rs @@ -66,7 +66,7 @@ mod tests { use crate::file::Twig; use crate::mutant::{BinaryOpMutationKind, MutantKind, Point, Span}; use crate::twig::TwigsIterBuilder; - use bough_typed_hash::{HashInto, HashStore}; + use bough_typed_hash::HashInto; use std::path::PathBuf; fn make_base() -> (tempfile::TempDir, Base) { @@ -290,9 +290,8 @@ mod tests { mutant: mutant.clone(), subst: "-".into(), }; - let mut store = bough_typed_hash::MemoryHashStore::new(); - let hash = mutation.hash(&mut store).unwrap(); - assert!(store.contains(&hash)); + let hash = mutation.hash().unwrap(); + assert_eq!(hash.to_string().len(), 64); } // bough[verify mutation.hash.mutant] diff --git a/crates/bough-core/src/session.rs b/crates/bough-core/src/session.rs index b8148035..a3fbd10f 100644 --- a/crates/bough-core/src/session.rs +++ b/crates/bough-core/src/session.rs @@ -88,12 +88,11 @@ impl Session { pub fn tend_add_missing_states(&mut self) -> Result, Error> { let mutations_in_base: HashSet = self.base.mutations().collect::>()?; - let mut hash_store = bough_typed_hash::MemoryHashStore::new(); let mut added = Vec::new(); for mutation in &mutations_in_base { let hash = mutation - .hash(&mut hash_store) + .hash() .expect("hashing should not fail"); if self.mutations_state.get(&hash).is_none() { let state = State::new(mutation.clone()); @@ -163,11 +162,9 @@ impl Session { pub fn tend_remove_stale_states(&mut self) -> Result, Error> { let mutations_in_base: HashSet = self.base.mutations().collect::>()?; - let mut hash_store = bough_typed_hash::MemoryHashStore::new(); - let hashes_in_base: HashSet = mutations_in_base .iter() - .map(|m| m.hash(&mut hash_store).expect("hashing should not fail")) + .map(|m| m.hash().expect("hashing should not fail")) .collect(); let stale_keys: Vec = self diff --git a/crates/bough-typed-hash/Cargo.toml b/crates/bough-typed-hash/Cargo.toml index dbeee2ef..0c97f360 100644 --- a/crates/bough-typed-hash/Cargo.toml +++ b/crates/bough-typed-hash/Cargo.toml @@ -4,17 +4,11 @@ version.workspace = true edition.workspace = true license.workspace = true -[features] -default = [] -disk = ["facet-json"] - [dependencies] sha2 = "0.10" tracing = "0.1" facet = "0.44" -facet-json = { version = "0.44", optional = true } bough-typed-hash-derive = { path = "../bough-typed-hash-derive" } [dev-dependencies] -facet-json = "0.44" tempfile = "3" diff --git a/crates/bough-typed-hash/src/error.rs b/crates/bough-typed-hash/src/error.rs index 93c6d1c5..16a191e2 100644 --- a/crates/bough-typed-hash/src/error.rs +++ b/crates/bough-typed-hash/src/error.rs @@ -1,11 +1,8 @@ use crate::TypedHash; -/// Errors from hash parsing, lookup, and I/O. #[derive(Debug)] pub enum HashError { - Io(std::io::Error), InvalidHex(String), - PrefixTooShort { prefix: String, min_prefix_len: usize }, NotFound(String), Ambiguous { prefix: String, matches: Vec }, } @@ -13,11 +10,7 @@ pub enum HashError { impl std::fmt::Display for HashError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::Io(e) => write!(f, "I/O error: {e}"), Self::InvalidHex(s) => write!(f, "invalid hex: {s}"), - Self::PrefixTooShort { prefix, min_prefix_len } => { - write!(f, "prefix '{prefix}' too short (min {min_prefix_len})") - } Self::NotFound(s) => write!(f, "hash not found: {s}"), Self::Ambiguous { prefix, matches } => { write!(f, "ambiguous prefix '{prefix}', {} matches", matches.len()) @@ -27,9 +20,3 @@ impl std::fmt::Display for HashError { } impl std::error::Error for HashError {} - -impl From for HashError { - fn from(e: std::io::Error) -> Self { - Self::Io(e) - } -} diff --git a/crates/bough-typed-hash/src/lib.rs b/crates/bough-typed-hash/src/lib.rs index d396a382..91bc602e 100644 --- a/crates/bough-typed-hash/src/lib.rs +++ b/crates/bough-typed-hash/src/lib.rs @@ -5,12 +5,10 @@ //! - [`TypedHash`] — a typed 32-byte hash value //! - [`TypedHashable`] — produces a [`TypedHash`] from data //! -//! [`HashStore`] provides reverse lookup for hash validation. -//! //! # Example //! //! ``` -//! use bough_typed_hash::{HashInto, TypedHash, TypedHashable, MemoryHashStore, HashStore}; +//! use bough_typed_hash::{HashInto, TypedHash, TypedHashable}; //! //! #[derive(Clone, bough_typed_hash::TypedHashable)] //! pub struct Config { @@ -18,15 +16,13 @@ //! version: u32, //! } //! -//! let mut store = MemoryHashStore::new(); //! let cfg = Config { name: "app".into(), version: 1 }; -//! let hash = cfg.hash(&mut store).unwrap(); -//! assert!(store.contains(&hash)); +//! let hash = cfg.hash().unwrap(); +//! assert_eq!(hash.to_string().len(), 64); //! ``` use sha2::{Digest, Sha256}; use std::path::{Path, PathBuf}; -use tracing::{trace, warn}; pub use bough_typed_hash_derive::{HashInto, TypedHash, TypedHashable}; @@ -40,16 +36,11 @@ pub use sha2; pub type ShaState = Sha256; mod error; -mod store; mod unvalidated; pub use error::HashError; -pub use store::{ChainStore, HashStore, MemoryHashStore}; pub use unvalidated::UnvalidatedHash; -#[cfg(feature = "disk")] -pub use store::DiskHashStore; - /// Contributes bytes to a SHA-256 hash. /// /// Primitives and building blocks implement this trait. Types that produce @@ -59,91 +50,37 @@ pub trait HashInto { } /// A typed 32-byte SHA-256 hash. -/// -/// Not directly constructable from external input — use [`TypedHash::parse`] -/// or [`TypedHash::from_bytes`] with a [`HashStore`] to validate existence. pub trait TypedHash: Sized { #[doc(hidden)] fn from_raw(bytes: [u8; 32]) -> Self; fn as_bytes(&self) -> &[u8; 32]; - /// Parse a hex string (full 64-char or unique prefix, min 2 chars) and - /// validate against a store. - fn parse>( - s: &str, - store: &dyn HashStore, - ) -> Result> { - trace!(input_len = s.len(), "parsing hash"); - if s.len() == 64 { - let bytes = hex_to_bytes(s).map_err(|e| HashError::InvalidHex(e))?; - return Self::from_bytes(bytes, store); - } - - if s.len() < store.min_prefix_len() { - return Err(HashError::PrefixTooShort { - prefix: s.to_string(), - min_prefix_len: store.min_prefix_len(), - }); - } - - if s.chars().any(|c| !c.is_ascii_hexdigit()) { - return Err(HashError::InvalidHex(s.to_string())); - } - let matches: Vec = store.resolve_prefix(s) - .into_iter() - .map(|h| Self::from_raw(*h.as_bytes())) - .collect(); - - match matches.len() { - 0 => Err(HashError::NotFound(s.to_string())), - 1 => Ok(matches.into_iter().next().unwrap()), - _ => { - warn!(prefix = s, count = matches.len(), "ambiguous hash prefix"); - Err(HashError::Ambiguous { - prefix: s.to_string(), - matches, - }) - } - } - } - - /// Validate raw bytes against a store. - fn from_bytes>( - bytes: [u8; 32], - store: &dyn HashStore, - ) -> Result> { - let hash = Self::from_raw(bytes); - if store.contains(&hash) { - Ok(hash) - } else { - let mut hex = String::with_capacity(64); - for b in &bytes { - use std::fmt::Write; - write!(hex, "{b:02x}").unwrap(); - } - Err(HashError::NotFound(hex)) - } - } } /// Data that produces a [`TypedHash`]. /// /// Only root objects addressed by hash implement this. Building blocks -/// implement [`HashInto`] only. Calling [`hash`](TypedHashable::hash) -/// computes the hash and inserts the value into the provided store. +/// implement [`HashInto`] only. pub trait TypedHashable: HashInto + Clone + Sized { type Hash: TypedHash; - fn hash(&self, store: &mut dyn HashStore) -> Result { + fn hash(&self) -> Result { let mut state = Sha256::new(); self.hash_into(&mut state)?; let bytes: [u8; 32] = state.finalize().into(); - let hash = Self::Hash::from_raw(bytes); - store.insert(self.clone()); - Ok(hash) + Ok(Self::Hash::from_raw(bytes)) + } +} + +pub fn bytes_to_hex(bytes: &[u8; 32]) -> String { + let mut hex = String::with_capacity(64); + for b in bytes { + use std::fmt::Write; + write!(hex, "{b:02x}").unwrap(); } + hex } pub fn hex_to_bytes(hex: &str) -> Result<[u8; 32], String> { diff --git a/crates/bough-typed-hash/src/store.rs b/crates/bough-typed-hash/src/store.rs deleted file mode 100644 index e4c9ff33..00000000 --- a/crates/bough-typed-hash/src/store.rs +++ /dev/null @@ -1,243 +0,0 @@ -use crate::{TypedHash, TypedHashable}; -use sha2::{Digest, Sha256}; -use tracing::trace; - -fn raw_hash(value: &T) -> T::Hash { - let mut state = Sha256::new(); - value.hash_into(&mut state).expect("hash computation failed"); - T::Hash::from_raw(state.finalize().into()) -} - -/// Reverse lookup: hash → value. -/// -/// Used by [`TypedHash::parse`] and [`TypedHash::from_bytes`] to validate -/// that a hash corresponds to a known value. -pub trait HashStore { - fn get(&self, hash: &T::Hash) -> Option<&T>; - fn insert(&mut self, value: T); - - fn contains(&self, hash: &T::Hash) -> bool { - self.get(hash).is_some() - } - - /// Minimum hex prefix length this store accepts. - fn min_prefix_len(&self) -> usize; - - /// All hashes whose hex representation starts with `hex_prefix`. - fn resolve_prefix(&self, hex_prefix: &str) -> Vec<&T::Hash>; -} - -struct Entry { - hash: T::Hash, - value: T, -} - -/// In-memory hash store. -/// -/// # Example -/// -/// ``` -/// use bough_typed_hash::{TypedHashable, HashStore, MemoryHashStore}; -/// -/// #[derive(Clone, bough_typed_hash::TypedHashable)] -/// pub struct Item { value: u32 } -/// -/// let mut store = MemoryHashStore::new(); -/// let item = Item { value: 42 }; -/// let hash = item.hash(&mut store).unwrap(); -/// assert!(store.contains(&hash)); -/// ``` -pub struct MemoryHashStore { - entries: Vec>, -} - -impl MemoryHashStore { - pub fn new() -> Self { - Self { entries: Vec::new() } - } -} - -impl Default for MemoryHashStore { - fn default() -> Self { - Self::new() - } -} - -impl HashStore for MemoryHashStore { - fn get(&self, hash: &T::Hash) -> Option<&T> { - trace!("memory store: get"); - self.entries.iter() - .find(|e| e.hash.as_bytes() == hash.as_bytes()) - .map(|e| &e.value) - } - - fn insert(&mut self, value: T) { - let hash = raw_hash(&value); - trace!("memory store: insert"); - if let Some(entry) = self.entries.iter_mut().find(|e| e.hash.as_bytes() == hash.as_bytes()) { - entry.value = value; - entry.hash = hash; - } else { - self.entries.push(Entry { hash, value }); - } - } - - fn min_prefix_len(&self) -> usize { - 2 - } - - fn resolve_prefix(&self, hex_prefix: &str) -> Vec<&T::Hash> { - let prefix_lower = hex_prefix.to_ascii_lowercase(); - self.entries.iter() - .filter(|e| bytes_to_hex(e.hash.as_bytes()).starts_with(&prefix_lower)) - .map(|e| &e.hash) - .collect() - } -} - -/// Checks multiple stores in sequence. -/// -/// `get` returns the first match. `resolve_prefix` collects from all (deduped). -/// `insert` delegates to the first store. `min_prefix_len` is the max across stores. -pub struct ChainStore<'a, T: TypedHashable> { - stores: Vec<&'a mut dyn HashStore>, -} - -impl<'a, T: TypedHashable> ChainStore<'a, T> { - pub fn new(stores: Vec<&'a mut dyn HashStore>) -> Self { - Self { stores } - } -} - -impl HashStore for ChainStore<'_, T> { - fn get(&self, hash: &T::Hash) -> Option<&T> { - self.stores.iter() - .find_map(|s| s.get(hash)) - } - - fn insert(&mut self, value: T) { - if let Some(first) = self.stores.first_mut() { - first.insert(value); - } - } - - fn min_prefix_len(&self) -> usize { - self.stores.iter().map(|s| s.min_prefix_len()).max().unwrap_or(2) - } - - fn resolve_prefix(&self, hex_prefix: &str) -> Vec<&T::Hash> { - let mut seen = std::collections::HashSet::new(); - let mut result = Vec::new(); - for store in &self.stores { - for hash in store.resolve_prefix(hex_prefix) { - if seen.insert(*hash.as_bytes()) { - result.push(hash); - } - } - } - result - } -} - -/// File-backed hash store. Values stored as `{hash_hex}.json` in a directory. -/// -/// Requires the `disk` feature. Values must impl `Facet`. -/// Scans the directory at construction to build an index. Values are lazily -/// loaded and cached on first access via interior mutability. -#[cfg(feature = "disk")] -pub struct DiskHashStore { - dir: std::path::PathBuf, - entries: std::cell::RefCell>>, -} - -#[cfg(feature = "disk")] -struct DiskEntry { - hash: T::Hash, - value: Option, -} - -#[cfg(feature = "disk")] -impl facet::Facet<'a>> DiskHashStore { - /// Create a store backed by `dir`. Scans existing `*.json` files to build the index. - pub fn new(dir: std::path::PathBuf) -> Self { - debug!(dir = %dir.display(), "creating disk hash store"); - let mut entries = Vec::new(); - if let Ok(read_dir) = std::fs::read_dir(&dir) { - for entry in read_dir.flatten() { - let name = entry.file_name(); - let name = name.to_string_lossy(); - if let Some(hex) = name.strip_suffix(".json") { - if let Ok(bytes) = crate::hex_to_bytes(hex) { - entries.push(DiskEntry { - hash: T::Hash::from_raw(bytes), - value: None, - }); - } - } - } - } - Self { dir, entries: std::cell::RefCell::new(entries) } - } - - fn hash_path(&self, hash: &T::Hash) -> std::path::PathBuf { - self.dir.join(format!("{}.json", bytes_to_hex(hash.as_bytes()))) - } -} - -#[cfg(feature = "disk")] -impl facet::Facet<'a>> HashStore for DiskHashStore { - fn get(&self, hash: &T::Hash) -> Option<&T> { - let mut entries = self.entries.borrow_mut(); - let idx = entries.iter().position(|e| e.hash.as_bytes() == hash.as_bytes())?; - if entries[idx].value.is_none() { - let path = self.hash_path(hash); - let data = std::fs::read_to_string(&path).ok()?; - let value: T = facet_json::from_str(&data).ok()?; - entries[idx].value = Some(value); - } - drop(entries); - // SAFETY: entry is populated above, RefCell borrow is released, - // and the Vec is only appended to (never removed), so the pointer is stable. - let entries = self.entries.borrow(); - entries[idx].value.as_ref().map(|v| unsafe { &*(v as *const T) }) - } - - fn insert(&mut self, value: T) { - let hash = raw_hash(&value); - std::fs::create_dir_all(&self.dir).expect("failed to create store directory"); - let json = facet_json::to_string(&value).expect("failed to serialize"); - std::fs::write(self.hash_path(&hash), json).expect("failed to write hash file"); - let mut entries = self.entries.borrow_mut(); - if let Some(entry) = entries.iter_mut().find(|e| e.hash.as_bytes() == hash.as_bytes()) { - entry.value = Some(value); - } else { - entries.push(DiskEntry { hash, value: Some(value) }); - } - } - - fn min_prefix_len(&self) -> usize { - 2 - } - - fn resolve_prefix(&self, hex_prefix: &str) -> Vec<&T::Hash> { - let prefix_lower = hex_prefix.to_ascii_lowercase(); - let entries = self.entries.borrow(); - entries.iter() - .enumerate() - .filter(|(_, e)| bytes_to_hex(e.hash.as_bytes()).starts_with(&prefix_lower)) - .map(|(_, e)| { - // SAFETY: entries vec is only appended to, so references to hash fields are stable - unsafe { &*(&e.hash as *const T::Hash) } - }) - .collect() - } -} - -pub(crate) fn bytes_to_hex(bytes: &[u8; 32]) -> String { - let mut hex = String::with_capacity(64); - for b in bytes { - use std::fmt::Write; - write!(hex, "{b:02x}").unwrap(); - } - hex -} diff --git a/crates/bough-typed-hash/src/tests.rs b/crates/bough-typed-hash/src/tests.rs index b840c27f..50212838 100644 --- a/crates/bough-typed-hash/src/tests.rs +++ b/crates/bough-typed-hash/src/tests.rs @@ -76,8 +76,7 @@ fn typed_hash_display_format() { #[test] fn typed_hashable_produces_hash() { let w = Widget { name: "gear".into(), count: 5 }; - let mut store = MemoryHashStore::new(); - let h = w.hash(&mut store).unwrap(); + let h = w.hash().unwrap(); assert_eq!(h.to_string().len(), 64); } @@ -85,24 +84,14 @@ fn typed_hashable_produces_hash() { fn typed_hashable_deterministic() { let a = Widget { name: "gear".into(), count: 5 }; let b = Widget { name: "gear".into(), count: 5 }; - assert_eq!(a.hash(&mut MemoryHashStore::new()).unwrap(), b.hash(&mut MemoryHashStore::new()).unwrap()); + assert_eq!(a.hash().unwrap(), b.hash().unwrap()); } #[test] fn typed_hashable_different_values_differ() { let a = Widget { name: "gear".into(), count: 5 }; let b = Widget { name: "gear".into(), count: 6 }; - assert_ne!(a.hash(&mut MemoryHashStore::new()).unwrap(), b.hash(&mut MemoryHashStore::new()).unwrap()); -} - -#[test] -fn typed_hashable_hash_inserts_into_store() { - let mut store = MemoryHashStore::new(); - let w = Widget { name: "auto".into(), count: 1 }; - let h = w.hash(&mut MemoryHashStore::new()).unwrap(); - assert!(!store.contains(&h)); - w.hash(&mut store).unwrap(); - assert!(store.contains(&h)); + assert_ne!(a.hash().unwrap(), b.hash().unwrap()); } #[test] @@ -110,8 +99,8 @@ fn hash_into_derive_nested() { let a = Assembly { part: Part { label: "bolt".into(), weight: 1.5 }, quantity: 10 }; let b = Assembly { part: Part { label: "bolt".into(), weight: 1.5 }, quantity: 10 }; let c = Assembly { part: Part { label: "nut".into(), weight: 0.5 }, quantity: 10 }; - assert_eq!(a.hash(&mut MemoryHashStore::new()).unwrap(), b.hash(&mut MemoryHashStore::new()).unwrap()); - assert_ne!(a.hash(&mut MemoryHashStore::new()).unwrap(), c.hash(&mut MemoryHashStore::new()).unwrap()); + assert_eq!(a.hash().unwrap(), b.hash().unwrap()); + assert_ne!(a.hash().unwrap(), c.hash().unwrap()); } #[test] @@ -138,142 +127,50 @@ fn hash_into_derive_enum() { } #[test] -fn memory_store_insert_get() { - let mut store = MemoryHashStore::new(); - let w = Widget { name: "sprocket".into(), count: 3 }; - let h = w.hash(&mut store).unwrap(); - assert!(store.contains(&h)); - assert_eq!(store.get(&h).unwrap().name, "sprocket"); -} - -#[test] -fn memory_store_resolve_prefix() { - let mut store = MemoryHashStore::new(); - let w = Widget { name: "a".into(), count: 1 }; - let h = w.hash(&mut store).unwrap(); - - let hex = h.to_string(); - let prefix = &hex[..4]; - let matches = store.resolve_prefix(prefix); - assert!(matches.iter().any(|m| m.as_bytes() == h.as_bytes())); -} - -#[test] -fn typed_hash_parse_full_hex() { - let mut store = MemoryHashStore::new(); - let w = Widget { name: "x".into(), count: 1 }; - let h = w.hash(&mut store).unwrap(); +fn unvalidated_hash_full_hex() { + let w = Widget { name: "q".into(), count: 7 }; + let h = w.hash().unwrap(); let hex = h.to_string(); - let parsed = WidgetHash::parse::(&hex, &store).unwrap(); - assert_eq!(parsed, h); + let unvalidated = UnvalidatedHash::new(hex); + let validated = unvalidated.validate(&[h]).unwrap(); + assert_eq!(validated, h); } #[test] -fn typed_hash_parse_prefix() { - let mut store = MemoryHashStore::new(); +fn unvalidated_hash_prefix() { let w = Widget { name: "y".into(), count: 2 }; - let h = w.hash(&mut store).unwrap(); + let h = w.hash().unwrap(); let hex = h.to_string(); - let parsed = WidgetHash::parse::(&hex[..6], &store).unwrap(); - assert_eq!(parsed, h); + let unvalidated = UnvalidatedHash::new(hex[..6].to_string()); + let validated = unvalidated.validate(&[h]).unwrap(); + assert_eq!(validated, h); } #[test] -fn typed_hash_parse_not_found() { - let store = MemoryHashStore::::new(); - let err = WidgetHash::parse::("aabbccdd", &store); +fn unvalidated_hash_not_found() { + let known: Vec = vec![]; + let err = UnvalidatedHash::new("aabbccdd".into()).validate(&known); assert!(matches!(err, Err(HashError::NotFound(_)))); } #[test] -fn typed_hash_parse_prefix_too_short() { - let store = MemoryHashStore::::new(); - let err = WidgetHash::parse::("a", &store); - assert!(matches!(err, Err(HashError::PrefixTooShort { .. }))); -} - -#[test] -fn typed_hash_parse_invalid_hex() { - let store = MemoryHashStore::::new(); - let err = WidgetHash::parse::("zzzz", &store); +fn unvalidated_hash_invalid_hex() { + let known: Vec = vec![]; + let err = UnvalidatedHash::new("zzzz".into()).validate(&known); assert!(matches!(err, Err(HashError::InvalidHex(_)))); } #[test] -fn typed_hash_from_bytes_validates() { - let mut store = MemoryHashStore::new(); - let w = Widget { name: "z".into(), count: 9 }; - let h = w.hash(&mut store).unwrap(); - - let ok = WidgetHash::from_bytes::(*h.as_bytes(), &store); - assert!(ok.is_ok()); - - let missing = WidgetHash::from_bytes::([0xff; 32], &store); - assert!(matches!(missing, Err(HashError::NotFound(_)))); -} - -#[test] -fn unvalidated_hash_roundtrip() { - let mut store = MemoryHashStore::new(); - let w = Widget { name: "q".into(), count: 7 }; - let h = w.hash(&mut store).unwrap(); - let hex = h.to_string(); - - let unvalidated = UnvalidatedHash::new(hex); - let validated = unvalidated.validate::(&store).unwrap(); - assert_eq!(validated, h); -} - -#[test] -fn chain_store_searches_all() { - let mut s1 = MemoryHashStore::new(); - let mut s2 = MemoryHashStore::new(); - - let w1 = Widget { name: "alpha".into(), count: 1 }; - let w2 = Widget { name: "beta".into(), count: 2 }; - let h1 = w1.hash(&mut s1).unwrap(); - let h2 = w2.hash(&mut s2).unwrap(); - - let chain = ChainStore::new(vec![&mut s1, &mut s2]); - assert!(chain.contains(&h1)); - assert!(chain.contains(&h2)); - assert_eq!(chain.get(&h1).unwrap().name, "alpha"); - assert_eq!(chain.get(&h2).unwrap().name, "beta"); -} - -#[test] -fn chain_store_inserts_into_first() { - let mut s1 = MemoryHashStore::new(); - let mut s2 = MemoryHashStore::new(); - - let w = Widget { name: "gamma".into(), count: 3 }; - let h = w.hash(&mut MemoryHashStore::new()).unwrap(); - - { - let mut chain = ChainStore::new(vec![&mut s1, &mut s2]); - chain.insert(w); - } - - assert!(s1.contains(&h)); - assert!(!s2.contains(&h)); -} - -#[test] -fn chain_store_dedupes_prefix() { - let mut s1 = MemoryHashStore::new(); - let mut s2 = MemoryHashStore::new(); - - let w = Widget { name: "delta".into(), count: 4 }; - let h = w.hash(&mut MemoryHashStore::new()).unwrap(); - let hex = h.to_string(); - s1.insert(Widget { name: "delta".into(), count: 4 }); - s2.insert(Widget { name: "delta".into(), count: 4 }); +fn unvalidated_hash_ambiguous() { + let h1 = WidgetHash::from_raw([0xaa; 32]); + let mut h2_bytes = [0xaa; 32]; + h2_bytes[31] = 0xbb; + let h2 = WidgetHash::from_raw(h2_bytes); - let chain = ChainStore::new(vec![&mut s1, &mut s2]); - let matches = chain.resolve_prefix(&hex[..4]); - assert_eq!(matches.len(), 1); + let err = UnvalidatedHash::new("aa".into()).validate(&[h1, h2]); + assert!(matches!(err, Err(HashError::Ambiguous { .. }))); } #[test] @@ -358,51 +255,11 @@ fn hash_std_trait_impls() { assert!(set.contains(&h1)); } -#[cfg(feature = "disk")] -mod disk_tests { - use super::*; - - #[derive(Clone, facet::Facet, TypedHashable)] - pub struct DiskItem { - pub val: u32, - } - - #[test] - fn disk_store_insert_and_resolve() { - let dir = tempfile::tempdir().unwrap(); - let mut store = DiskHashStore::::new(dir.path().to_path_buf()); - - let item = DiskItem { val: 42 }; - let h = item.hash(&mut store).unwrap(); - - let hex = h.to_string(); - let matches = store.resolve_prefix(&hex[..4]); - assert!(!matches.is_empty()); - } - - #[test] - fn disk_store_get_cached() { - let dir = tempfile::tempdir().unwrap(); - let mut store = DiskHashStore::::new(dir.path().to_path_buf()); - - let item = DiskItem { val: 99 }; - let h = item.hash(&mut store).unwrap(); - - assert_eq!(store.get(&h).unwrap().val, 99); - } - - #[test] - fn disk_store_reloads_from_disk() { - let dir = tempfile::tempdir().unwrap(); - let h = { - let mut store = DiskHashStore::::new(dir.path().to_path_buf()); - let item = DiskItem { val: 77 }; - let h = item.hash(&mut store).unwrap(); - h - }; - - let store = DiskHashStore::::new(dir.path().to_path_buf()); - assert!(store.contains(&h)); - assert_eq!(store.get(&h).unwrap().val, 77); - } +#[test] +fn bytes_to_hex_roundtrip() { + let bytes = [0xde; 32]; + let hex = bytes_to_hex(&bytes); + assert_eq!(hex.len(), 64); + let back = hex_to_bytes(&hex).unwrap(); + assert_eq!(back, bytes); } diff --git a/crates/bough-typed-hash/src/unvalidated.rs b/crates/bough-typed-hash/src/unvalidated.rs index 5f1e54e7..864ed4f8 100644 --- a/crates/bough-typed-hash/src/unvalidated.rs +++ b/crates/bough-typed-hash/src/unvalidated.rs @@ -1,27 +1,26 @@ -use crate::{HashError, HashStore, TypedHash, TypedHashable}; -use tracing::debug; +use crate::{HashError, TypedHash, bytes_to_hex}; +use tracing::{debug, warn}; -/// Intermediate type for deserializing hashes without store validation. +/// Intermediate type for deserializing hashes without validation. /// /// `TypedHash` does not implement deserialization — deserialized hashes would -/// bypass store validation. Use `UnvalidatedHash` as the target, then -/// call [`.validate()`](UnvalidatedHash::validate) with a store. +/// bypass validation. Use `UnvalidatedHash` as the target, then +/// call [`.validate()`](UnvalidatedHash::validate) with a slice of known hashes. /// /// # Example /// /// ``` -/// use bough_typed_hash::{UnvalidatedHash, TypedHash, TypedHashable, HashStore, MemoryHashStore}; +/// use bough_typed_hash::{UnvalidatedHash, TypedHash, TypedHashable}; /// /// #[derive(Clone, bough_typed_hash::TypedHashable)] /// pub struct Record { id: u32 } /// -/// let mut store = MemoryHashStore::new(); /// let record = Record { id: 1 }; -/// let hash = record.hash(&mut store).unwrap(); +/// let hash = record.hash().unwrap(); /// let hex = hash.to_string(); /// /// let unvalidated = UnvalidatedHash::new(hex); -/// let validated = unvalidated.validate::(&store).unwrap(); +/// let validated = unvalidated.validate(&[hash]).unwrap(); /// assert_eq!(validated.as_bytes(), hash.as_bytes()); /// ``` #[derive(Debug, Clone, facet::Facet)] @@ -33,12 +32,45 @@ impl UnvalidatedHash { Self(hex) } - /// Validate against a store, supporting both full hex and unique prefixes. - pub fn validate( + /// Validate against a set of known hashes, supporting both full hex and unique prefixes. + pub fn validate( self, - store: &dyn HashStore, - ) -> Result> { + known: &[H], + ) -> Result> { debug!(hex_len = self.0.len(), "validating unvalidated hash"); - T::Hash::parse::(&self.0, store) + let s = &self.0; + + if s.chars().any(|c| !c.is_ascii_hexdigit()) { + return Err(HashError::InvalidHex(s.clone())); + } + + if s.len() == 64 { + let bytes = crate::hex_to_bytes(s).map_err(HashError::InvalidHex)?; + let target = H::from_raw(bytes); + return if known.iter().any(|h| h.as_bytes() == target.as_bytes()) { + Ok(target) + } else { + Err(HashError::NotFound(s.clone())) + }; + } + + let prefix_lower = s.to_ascii_lowercase(); + let matches: Vec = known + .iter() + .filter(|h| bytes_to_hex(h.as_bytes()).starts_with(&prefix_lower)) + .map(|h| H::from_raw(*h.as_bytes())) + .collect(); + + match matches.len() { + 0 => Err(HashError::NotFound(s.clone())), + 1 => Ok(matches.into_iter().next().unwrap()), + _ => { + warn!(prefix = %s, count = matches.len(), "ambiguous hash prefix"); + Err(HashError::Ambiguous { + prefix: s.clone(), + matches, + }) + } + } } }