Skip to main content

git_internal/
hash.rs

1//! Hash utilities for Git objects with selectable algorithms (SHA-1, SHA-256 and
2//! BLAKE3-256).
3//!
4//! # Algorithms
5//!
6//! * `Sha1` (20 bytes / 40 hex) and `Sha256` (32 bytes / 64 hex) follow the
7//!   standard Git object formats.
8//! * `Blake3` (32 bytes / 64 hex) is a **git-internal / Libra extension**: a
9//!   repository created with it is a separate object namespace that standard
10//!   Git does not understand. Because SHA-256 and BLAKE3 IDs have the same
11//!   width, a 64-hex or 32-byte value can only be interpreted inside a known
12//!   repository [`HashKind`] context (see the explicit-kind API below) or when
13//!   it carries its algorithm tag (`blake3:HEX`); nothing in this module guesses
14//!   BLAKE3 from a length.
15//! * BLAKE3 here is the *repository object ID* algorithm only. It does not
16//!   change [`crate::internal::object::integrity::IntegrityHash`] (always
17//!   SHA-256) or any application-level digest (Buck manifests, policy digests,
18//!   HMACs).
19//!
20//! # Thread-local default versus explicit `HashKind`
21//!
22//! Two families of API live here:
23//!
24//! * **Thread-local compatibility wrappers** — [`ObjectHash::new`],
25//!   [`ObjectHash::from_type_and_data`], [`ObjectHash::from_bytes`],
26//!   [`ObjectHash::from_stream`] and [`crate::utils::HashAlgorithm::new`] read the
27//!   thread-local [`HashKind`] set by [`set_hash_kind`]. They exist for the
28//!   established single-repository workflow: configure the kind once at startup
29//!   on the thread that does the work, then call the parameterless API.
30//! * **Explicit-kind API** — [`ObjectHash::new_for_kind`],
31//!   [`ObjectHash::from_type_and_data_for_kind`], [`ObjectHash::from_hex_for_kind`],
32//!   [`ObjectHash::from_bytes_for_kind`], [`ObjectHash::from_stream_for_kind`],
33//!   [`ObjectHash::zero_for_kind`] and
34//!   [`crate::utils::HashAlgorithm::new_for_kind`] take the repository
35//!   [`HashKind`] as a parameter and never consult the thread-local. New code
36//!   that runs on worker threads, async tasks, streams, caches, object loaders or
37//!   protocol callbacks — anywhere the current thread may belong to another
38//!   repository — must use this family and pass the kind of the repository it
39//!   is operating on.
40//!
41//! Raw hex IDs (`Display`, [`FromStr`]) stay Git-like: no algorithm prefix. The
42//! legacy [`FromStr`] implementation infers SHA-1 for 40 hex characters and
43//! SHA-256 for 64 hex characters purely from the length; it does not consult
44//! the thread-local kind and must not be used where the repository format is
45//! known. When an ID has to travel across repositories, APIs, logs or indexes
46//! together with its algorithm, use the tagged representation
47//! (`sha1:HEX` / `sha256:HEX` / `blake3:HEX`) via
48//! [`ObjectHash::to_tagged_string`] and [`ObjectHash::from_tagged_str`].
49//!
50//! Every explicit-kind parser fails closed: a length, hex or kind mismatch is
51//! reported through [`HashError`] (carrying the operation, the expected/actual
52//! lengths and — whenever it can be determined — the requested kind) and never
53//! silently falls back to another algorithm.
54//!
55//! Hash kind is stored thread-locally; set once at startup to match your repository format.
56//! Defaults to SHA-1.
57
58use std::{cell::RefCell, fmt::Display, hash::Hash, io, str::FromStr};
59
60use colored::Colorize;
61
62use crate::{internal::object::types::ObjectType, utils::HashAlgorithm};
63
64/// Errors produced by the explicit-kind [`ObjectHash`] constructors and parsers.
65///
66/// Every variant records the operation that failed and the expected/actual
67/// lengths involved; the requested [`HashKind`] is recorded on every variant
68/// where it can be determined ([`HashError::UnknownKind`] is precisely the case
69/// where the tag did not resolve to one). None of these paths fall back to
70/// another algorithm.
71#[derive(Debug, Clone, PartialEq, thiserror::Error)]
72pub enum HashError {
73    /// The raw byte slice, hex string or stream does not have the length required by `kind`.
74    #[error("{operation}: invalid {kind} hash length: expected {expected}, got {actual}")]
75    InvalidLength {
76        /// Name of the API that rejected the input.
77        operation: &'static str,
78        /// Requested hash kind.
79        kind: HashKind,
80        /// Expected length (bytes for byte/stream input, characters for hex input).
81        expected: usize,
82        /// Actual length of the input (bytes actually read for stream input).
83        actual: usize,
84    },
85    /// The hex string has the right length but contains characters outside `[0-9a-fA-F]`.
86    #[error(
87        "{operation}: invalid {kind} hex string (expected {expected} hex chars, got {actual}): {source}"
88    )]
89    InvalidHex {
90        /// Name of the API that rejected the input.
91        operation: &'static str,
92        /// Requested hash kind.
93        kind: HashKind,
94        /// Expected hex length for `kind`.
95        expected: usize,
96        /// Actual length of the input.
97        actual: usize,
98        /// Underlying hex decoding error.
99        source: hex::FromHexError,
100    },
101    /// An [`ObjectHash`] of a different algorithm was supplied where `expected` was required.
102    #[error(
103        "{operation}: hash kind mismatch: expected {expected} ({expected_len} bytes), got {actual} ({actual_len} bytes)"
104    )]
105    KindMismatch {
106        /// Name of the API that rejected the input.
107        operation: &'static str,
108        /// Kind required by the caller / repository.
109        expected: HashKind,
110        /// Kind actually carried by the value.
111        actual: HashKind,
112        /// Byte length of `expected`.
113        expected_len: usize,
114        /// Byte length of `actual`.
115        actual_len: usize,
116    },
117    /// A tagged ID has a missing or unknown `<kind>:` prefix.
118    ///
119    /// No [`HashKind`] can be attached because the tag is exactly what failed to
120    /// resolve; the accepted tag set and the lengths that were seen are carried
121    /// instead so the caller can still diagnose the input.
122    #[error(
123        "{operation}: unknown hash kind tag {tag:?} (accepted: {expected_tags}; tag length {actual}, expected one of {expected_tag_lens}; id part {hex_len} hex chars)"
124    )]
125    UnknownKind {
126        /// Name of the API that rejected the input.
127        operation: &'static str,
128        /// The offending tag (or the whole input when no `:` separator exists).
129        tag: String,
130        /// Accepted tags.
131        expected_tags: &'static str,
132        /// Accepted tag lengths (characters).
133        expected_tag_lens: &'static str,
134        /// Length of the offending tag (characters).
135        actual: usize,
136        /// Length of the hex part after the separator (0 when no separator exists).
137        hex_len: usize,
138    },
139    /// `object_type` has no loose-object header (delta types) and therefore no canonical object ID.
140    #[error(
141        "{operation}: {kind} object hash requested for {object_type}, which has no loose-object header (expected a {expected}-byte digest, produced {actual}; payload {payload_len} bytes)"
142    )]
143    UnsupportedObjectType {
144        /// Name of the API that rejected the input.
145        operation: &'static str,
146        /// Requested hash kind.
147        kind: HashKind,
148        /// The object type without a header.
149        object_type: ObjectType,
150        /// Digest length `kind` would have produced.
151        expected: usize,
152        /// Digest bytes actually produced (always 0: nothing is hashed).
153        actual: usize,
154        /// Length of the payload that was offered.
155        payload_len: usize,
156    },
157    /// The underlying reader failed while reading a `kind`-sized ID.
158    #[error("{operation}: I/O error after {actual} of {expected} {kind} bytes: {message}")]
159    Io {
160        /// Name of the API that rejected the input.
161        operation: &'static str,
162        /// Requested hash kind.
163        kind: HashKind,
164        /// Bytes required.
165        expected: usize,
166        /// Bytes read before the error.
167        actual: usize,
168        /// [`io::ErrorKind`] of the underlying error.
169        error_kind: io::ErrorKind,
170        /// Display text of the underlying error.
171        message: String,
172    },
173}
174
175impl From<HashError> for io::Error {
176    /// Map a [`HashError`] onto the closest [`io::ErrorKind`]: short streams become
177    /// `UnexpectedEof` (matching `Read::read_exact`), transport errors keep their
178    /// original kind and every other diagnostic is `InvalidData`.
179    fn from(err: HashError) -> Self {
180        let kind = match &err {
181            HashError::InvalidLength {
182                operation: "from_stream_for_kind",
183                ..
184            } => io::ErrorKind::UnexpectedEof,
185            HashError::Io { error_kind, .. } => *error_kind,
186            _ => io::ErrorKind::InvalidData,
187        };
188        io::Error::new(kind, err)
189    }
190}
191
192/// Supported hash algorithms for object IDs (selector only, no data attached).
193/// Used to configure which hash algorithm to use globally (thread-local).
194/// Defaults to SHA-1.
195#[derive(
196    Clone,
197    Copy,
198    Debug,
199    PartialEq,
200    Eq,
201    Hash,
202    PartialOrd,
203    Ord,
204    Default,
205    serde::Deserialize,
206    serde::Serialize,
207    rkyv::Archive,
208    rkyv::Serialize,
209    rkyv::Deserialize,
210)]
211pub enum HashKind {
212    #[default]
213    Sha1,
214    Sha256,
215    /// BLAKE3-256 repository object IDs (git-internal / Libra extension; not a
216    /// standard Git object format).
217    Blake3,
218}
219impl HashKind {
220    /// Accepted lowercase tags for [`HashKind::from_str`] / tagged IDs, for diagnostics.
221    pub const ACCEPTED_TAGS: &'static str = "sha1|sha256|blake3";
222    /// Character lengths of [`HashKind::ACCEPTED_TAGS`], for diagnostics.
223    pub const ACCEPTED_TAG_LENS: &'static str = "4|6";
224
225    /// Byte length of the hash output.
226    pub const fn size(&self) -> usize {
227        match self {
228            HashKind::Sha1 => 20,
229            HashKind::Sha256 => 32,
230            HashKind::Blake3 => 32,
231        }
232    }
233    /// Hex string length of the hash output.
234    pub const fn hex_len(&self) -> usize {
235        self.size() * 2
236    }
237    /// Lowercase name of the hash algorithm (also the wire / tag spelling).
238    pub const fn as_str(&self) -> &'static str {
239        match self {
240            HashKind::Sha1 => "sha1",
241            HashKind::Sha256 => "sha256",
242            HashKind::Blake3 => "blake3",
243        }
244    }
245    /// Whether this kind is a standard Git object format (SHA-1, SHA-256) or a
246    /// git-internal / Libra extension (BLAKE3).
247    pub const fn is_git_standard(&self) -> bool {
248        match self {
249            HashKind::Sha1 | HashKind::Sha256 => true,
250            HashKind::Blake3 => false,
251        }
252    }
253}
254impl std::fmt::Display for HashKind {
255    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
256        f.write_str(self.as_str())
257    }
258}
259impl std::str::FromStr for HashKind {
260    type Err = String;
261
262    fn from_str(s: &str) -> Result<Self, Self::Err> {
263        match s.to_ascii_lowercase().as_str() {
264            "sha1" => Ok(HashKind::Sha1),
265            "sha256" => Ok(HashKind::Sha256),
266            "blake3" => Ok(HashKind::Blake3),
267            _ => Err("Invalid hash kind".to_string()),
268        }
269    }
270}
271
272#[derive(
273    Clone,
274    Copy,
275    Debug,
276    PartialEq,
277    Eq,
278    Hash,
279    PartialOrd,
280    Ord,
281    serde::Deserialize,
282    serde::Serialize,
283    rkyv::Archive,
284    rkyv::Serialize,
285    rkyv::Deserialize,
286)]
287/// Concrete object ID value carrying the bytes for the selected algorithm
288/// (SHA-1, SHA-256 or BLAKE3-256).
289/// Used for Git object hashes.
290/// Supports conversion to/from hex strings, byte slices, and stream reading.
291///
292/// `Sha256` and `Blake3` carry the same 32 bytes and print as the same 64-hex
293/// width; they are distinct variants and never compare equal, so the algorithm
294/// is always preserved as metadata.
295pub enum ObjectHash {
296    Sha1([u8; 20]),
297    Sha256([u8; 32]),
298    /// BLAKE3-256 repository object ID (git-internal / Libra extension).
299    Blake3([u8; 32]),
300}
301impl Default for ObjectHash {
302    fn default() -> Self {
303        ObjectHash::Sha1([0u8; 20])
304    }
305}
306impl Display for ObjectHash {
307    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
308        write!(f, "{}", hex::encode(self.as_ref()))
309    }
310}
311impl AsRef<[u8]> for ObjectHash {
312    fn as_ref(&self) -> &[u8] {
313        match self {
314            ObjectHash::Sha1(bytes) => bytes.as_slice(),
315            ObjectHash::Sha256(bytes) => bytes.as_slice(),
316            ObjectHash::Blake3(bytes) => bytes.as_slice(),
317        }
318    }
319}
320/// Parse hex (40 for SHA1, 64 for SHA-256) into `ObjectHash`.
321///
322/// **Legacy, length-inferring parser.** The algorithm is chosen from the hex
323/// length alone (40 → SHA-1, 64 → SHA-256); the thread-local [`HashKind`] is
324/// *not* consulted and **BLAKE3 is never produced** (a BLAKE3 ID has the same
325/// 64-hex width and would be mislabelled as SHA-256). Any other length is
326/// rejected. When the repository format is known, prefer
327/// [`ObjectHash::from_hex_for_kind`]; when the ID travels with its algorithm,
328/// prefer [`ObjectHash::from_tagged_str`].
329impl FromStr for ObjectHash {
330    type Err = String;
331
332    fn from_str(s: &str) -> Result<Self, Self::Err> {
333        // Error surface intentionally unchanged from the pre-refactor parser:
334        // `hex::FromHexError`'s own message for bad hex, "Invalid hash length" otherwise.
335        let kind = match s.len() {
336            40 => HashKind::Sha1,
337            64 => HashKind::Sha256,
338            _ => return Err("Invalid hash length".to_string()),
339        };
340        let bytes = hex::decode(s).map_err(|e| e.to_string())?;
341        ObjectHash::from_bytes_for_kind(kind, &bytes).map_err(|e| e.to_string())
342    }
343}
344
345impl ObjectHash {
346    /// Zero-filled ID (all bytes `0x00`) for a given hash kind.
347    pub fn zero_for_kind(kind: HashKind) -> ObjectHash {
348        match kind {
349            HashKind::Sha1 => ObjectHash::Sha1([0u8; 20]),
350            HashKind::Sha256 => ObjectHash::Sha256([0u8; 32]),
351            HashKind::Blake3 => ObjectHash::Blake3([0u8; 32]),
352        }
353    }
354
355    /// Zero-filled hex string for a given hash kind.
356    pub fn zero_str(kind: HashKind) -> String {
357        Self::zero_for_kind(kind).to_string()
358    }
359
360    /// Return the hash kind for this value.
361    pub fn kind(&self) -> HashKind {
362        match self {
363            ObjectHash::Sha1(_) => HashKind::Sha1,
364            ObjectHash::Sha256(_) => HashKind::Sha256,
365            ObjectHash::Blake3(_) => HashKind::Blake3,
366        }
367    }
368    /// Return the hash size in bytes.
369    pub fn size(&self) -> usize {
370        self.kind().size()
371    }
372
373    /// Fail closed unless this value carries `expected`.
374    ///
375    /// Use this at repository boundaries (pack trailers, ref-delta bases,
376    /// index entries, protocol IDs) to reject an ID of the wrong algorithm
377    /// instead of accepting a same-length value of another kind.
378    pub fn ensure_kind(&self, expected: HashKind) -> Result<(), HashError> {
379        let actual = self.kind();
380        if actual == expected {
381            Ok(())
382        } else {
383            Err(HashError::KindMismatch {
384                operation: "ensure_kind",
385                expected,
386                actual,
387                expected_len: expected.size(),
388                actual_len: actual.size(),
389            })
390        }
391    }
392
393    /// Compute the digest of `data` with an explicit `kind`.
394    ///
395    /// Streams `data` through [`HashAlgorithm::new_for_kind`]; no copy of the
396    /// input is made. Does not consult the thread-local [`HashKind`].
397    pub fn new_for_kind(kind: HashKind, data: &[u8]) -> ObjectHash {
398        let mut hasher = HashAlgorithm::new_for_kind(kind);
399        hasher.update(data);
400        hasher.finalize_object_hash()
401    }
402
403    /// Compute hash of data using current thread-local `HashKind`.
404    ///
405    /// Compatibility wrapper around [`ObjectHash::new_for_kind`].
406    pub fn new(data: &[u8]) -> ObjectHash {
407        Self::new_for_kind(get_hash_kind(), data)
408    }
409
410    /// Compute the canonical Git object ID `hash("<type> <size>\0" + data)` with an
411    /// explicit `kind`.
412    ///
413    /// The header and payload are streamed into the hasher, so `data` is never
414    /// copied (only the decimal size string is formatted). Does not consult the
415    /// thread-local [`HashKind`]. Delta object types have no loose-object header
416    /// and are rejected with [`HashError::UnsupportedObjectType`] instead of
417    /// panicking.
418    pub fn from_type_and_data_for_kind(
419        kind: HashKind,
420        object_type: ObjectType,
421        data: &[u8],
422    ) -> Result<ObjectHash, HashError> {
423        let type_bytes = object_type
424            .to_bytes()
425            .ok_or(HashError::UnsupportedObjectType {
426                operation: "from_type_and_data_for_kind",
427                kind,
428                object_type,
429                expected: kind.size(),
430                actual: 0,
431                payload_len: data.len(),
432            })?;
433        let mut hasher = HashAlgorithm::new_for_kind(kind);
434        hasher.update(type_bytes);
435        hasher.update(b" ");
436        hasher.update(data.len().to_string().as_bytes());
437        hasher.update(b"\x00");
438        hasher.update(data);
439        Ok(hasher.finalize_object_hash())
440    }
441
442    /// Create ObjectHash from object type and data using the thread-local `HashKind`.
443    ///
444    /// Legacy entry point; the header assembly below is the pre-refactor code
445    /// (including its behaviour for delta types, which have no loose-object
446    /// header and were never valid input here). Only the digest step was
447    /// redirected to [`ObjectHash::new_for_kind`]. New code should call
448    /// [`ObjectHash::from_type_and_data_for_kind`], which is fallible and
449    /// streams the header instead of copying the payload.
450    pub fn from_type_and_data(object_type: ObjectType, data: &[u8]) -> ObjectHash {
451        let mut d: Vec<u8> = Vec::new();
452        d.extend(object_type.to_data().unwrap());
453        d.push(b' ');
454        d.extend(data.len().to_string().as_bytes());
455        d.push(b'\x00');
456        d.extend(data);
457        Self::new_for_kind(get_hash_kind(), &d)
458    }
459
460    /// Create an `ObjectHash` of an explicit `kind` from raw digest bytes.
461    ///
462    /// Fails closed with [`HashError::InvalidLength`] when `bytes.len()` is not
463    /// `kind.size()`; it never re-interprets the bytes as another algorithm.
464    pub fn from_bytes_for_kind(kind: HashKind, bytes: &[u8]) -> Result<ObjectHash, HashError> {
465        let expected = kind.size();
466        if bytes.len() != expected {
467            return Err(HashError::InvalidLength {
468                operation: "from_bytes_for_kind",
469                kind,
470                expected,
471                actual: bytes.len(),
472            });
473        }
474        Ok(match kind {
475            HashKind::Sha1 => {
476                let mut h = [0u8; 20];
477                h.copy_from_slice(bytes);
478                ObjectHash::Sha1(h)
479            }
480            HashKind::Sha256 => {
481                let mut h = [0u8; 32];
482                h.copy_from_slice(bytes);
483                ObjectHash::Sha256(h)
484            }
485            HashKind::Blake3 => {
486                let mut h = [0u8; 32];
487                h.copy_from_slice(bytes);
488                ObjectHash::Blake3(h)
489            }
490        })
491    }
492
493    /// Create `ObjectHash` from raw bytes matching the current hash size.
494    ///
495    /// Compatibility wrapper around [`ObjectHash::from_bytes_for_kind`] using the
496    /// thread-local [`HashKind`].
497    pub fn from_bytes(bytes: &[u8]) -> Result<ObjectHash, String> {
498        // Error string intentionally unchanged from the pre-refactor implementation.
499        Self::from_bytes_for_kind(get_hash_kind(), bytes).map_err(|e| match e {
500            HashError::InvalidLength {
501                expected, actual, ..
502            } => format!("Invalid byte length: got {actual}, expected {expected}"),
503            other => other.to_string(),
504        })
505    }
506
507    /// Parse a raw (untagged) hex string as an ID of an explicit `kind`.
508    ///
509    /// The string must be exactly `kind.hex_len()` characters of hex; a
510    /// 64-character string is only accepted as the requested 32-byte kind and is
511    /// never guessed from its length. Fails closed with [`HashError`].
512    pub fn from_hex_for_kind(kind: HashKind, hex_str: &str) -> Result<ObjectHash, HashError> {
513        let expected = kind.hex_len();
514        if hex_str.len() != expected {
515            return Err(HashError::InvalidLength {
516                operation: "from_hex_for_kind",
517                kind,
518                expected,
519                actual: hex_str.len(),
520            });
521        }
522        let bytes = hex::decode(hex_str).map_err(|source| HashError::InvalidHex {
523            operation: "from_hex_for_kind",
524            kind,
525            expected,
526            actual: hex_str.len(),
527            source,
528        })?;
529        Self::from_bytes_for_kind(kind, &bytes)
530    }
531
532    /// Format as a tagged ID `<kind>:<hex>` (for example `sha256:ab12…`).
533    ///
534    /// Use this representation wherever an ID leaves its repository context
535    /// (APIs, indexes, logs). It must not be written into pack, tree/commit
536    /// payloads or pkt-lines, which carry raw hex only.
537    pub fn to_tagged_string(&self) -> String {
538        format!("{}:{}", self.kind(), self)
539    }
540
541    /// Parse a tagged ID `<kind>:<hex>` produced by [`ObjectHash::to_tagged_string`].
542    ///
543    /// The tag selects the algorithm; the hex part must match that algorithm's
544    /// length. Unknown tags, missing separators and length/hex errors fail
545    /// closed with [`HashError`].
546    pub fn from_tagged_str(tagged: &str) -> Result<ObjectHash, HashError> {
547        let (tag, hex_str) = tagged
548            .split_once(':')
549            .ok_or_else(|| HashError::UnknownKind {
550                operation: "from_tagged_str",
551                tag: tagged.to_string(),
552                expected_tags: HashKind::ACCEPTED_TAGS,
553                expected_tag_lens: HashKind::ACCEPTED_TAG_LENS,
554                actual: tagged.len(),
555                hex_len: 0,
556            })?;
557        let kind = tag
558            .parse::<HashKind>()
559            .map_err(|_| HashError::UnknownKind {
560                operation: "from_tagged_str",
561                tag: tag.to_string(),
562                expected_tags: HashKind::ACCEPTED_TAGS,
563                expected_tag_lens: HashKind::ACCEPTED_TAG_LENS,
564                actual: tag.len(),
565                hex_len: hex_str.len(),
566            })?;
567        Self::from_hex_for_kind(kind, hex_str)
568    }
569
570    /// Create `ObjectHash` from raw bytes, inferring the hash kind from the
571    /// byte length (20 → SHA-1, 32 → SHA-256).
572    ///
573    /// **Legacy contract (frozen):** 20 bytes are always SHA-1 and 32 bytes are
574    /// always SHA-256 — **never BLAKE3**, even though BLAKE3 digests are also
575    /// 32 bytes. This helper predates the explicit-kind API and will be
576    /// marked `#[deprecated]` once the remaining internal callers have moved to
577    /// [`ObjectHash::from_bytes_for_kind`] / [`HashAlgorithm::finalize_object_hash`].
578    /// It must not be used on any *new* repository, pack or protocol path,
579    /// because a 32-byte digest of another algorithm would be silently
580    /// mislabelled as SHA-256. The two remaining pack-encode callers
581    /// (`encode/mod.rs`, `encode/parallel.rs`) are migrated to
582    /// [`HashAlgorithm::finalize_object_hash`] in B3-05, after which the
583    /// attribute is added.
584    ///
585    /// Unlike [`ObjectHash::from_bytes`], this does not consult the
586    /// thread-local [`HashKind`], so it is safe on threads where
587    /// [`set_hash_kind`] was never called. The pack encoder finalizes its
588    /// running checksum on whichever async worker thread happens to run the
589    /// task; the checksum bytes already carry the correct length, while the
590    /// worker's thread-local may still hold the default SHA-1 kind — the
591    /// mismatch used to panic with "Invalid byte length: got 32, expected 20".
592    #[deprecated(
593        since = "0.9.0",
594        note = "infers SHA-256 from a 32-byte length and can never represent BLAKE3; use \
595                ObjectHash::from_bytes_for_kind or HashAlgorithm::finalize_object_hash"
596    )]
597    pub fn from_bytes_infer_kind(bytes: &[u8]) -> Result<ObjectHash, String> {
598        match bytes.len() {
599            20 => {
600                let mut h = [0u8; 20];
601                h.copy_from_slice(bytes);
602                Ok(ObjectHash::Sha1(h))
603            }
604            32 => {
605                let mut h = [0u8; 32];
606                h.copy_from_slice(bytes);
607                Ok(ObjectHash::Sha256(h))
608            }
609            other => Err(format!(
610                "Invalid byte length: got {other}, expected 20 (SHA-1) or 32 (SHA-256)"
611            )),
612        }
613    }
614
615    /// Read exactly `kind.size()` bytes from `data` as an ID of an explicit `kind`.
616    ///
617    /// Does not consult the thread-local [`HashKind`]. A short stream fails
618    /// closed with [`HashError::InvalidLength`] carrying the bytes actually
619    /// read; other reader failures surface as [`HashError::Io`].
620    pub fn from_stream_for_kind(
621        kind: HashKind,
622        data: &mut impl io::Read,
623    ) -> Result<ObjectHash, HashError> {
624        const OP: &str = "from_stream_for_kind";
625        let expected = kind.size();
626        let mut buf = [0u8; 32];
627        let mut filled = 0usize;
628        while filled < expected {
629            match data.read(&mut buf[filled..expected]) {
630                Ok(0) => break,
631                Ok(n) => filled += n,
632                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
633                Err(e) => {
634                    return Err(HashError::Io {
635                        operation: OP,
636                        kind,
637                        expected,
638                        actual: filled,
639                        error_kind: e.kind(),
640                        message: e.to_string(),
641                    });
642                }
643            }
644        }
645        if filled != expected {
646            return Err(HashError::InvalidLength {
647                operation: OP,
648                kind,
649                expected,
650                actual: filled,
651            });
652        }
653        Self::from_bytes_for_kind(kind, &buf[..expected])
654    }
655
656    /// Read hash bytes from a stream according to current hash size.
657    ///
658    /// Legacy entry point using the thread-local [`HashKind`]. The error
659    /// surface is unchanged from the pre-refactor implementation: the
660    /// [`io::Error`] returned by `Read::read_exact` (a short stream is
661    /// `UnexpectedEof`). Only the byte-to-variant step goes through
662    /// [`ObjectHash::from_bytes_for_kind`]. New code should call
663    /// [`ObjectHash::from_stream_for_kind`].
664    pub fn from_stream(data: &mut impl io::Read) -> io::Result<ObjectHash> {
665        let kind = get_hash_kind();
666        let mut buf = [0u8; 32];
667        let want = &mut buf[..kind.size()];
668        data.read_exact(want)?;
669        Self::from_bytes_for_kind(kind, want).map_err(io::Error::from)
670    }
671
672    /// Format hash as colored string (for terminal display).
673    pub fn to_color_str(self) -> String {
674        self.to_string().red().bold().to_string()
675    }
676
677    /// Return raw bytes of the hash.
678    pub fn to_data(self) -> Vec<u8> {
679        self.as_ref().to_vec()
680    }
681
682    /// Faster string conversion than `Display`.
683    pub fn _to_string(&self) -> String {
684        hex::encode(self.as_ref())
685    }
686
687    /// Get mutable access to inner byte slice.
688    pub fn as_mut_bytes(&mut self) -> &mut [u8] {
689        match self {
690            ObjectHash::Sha1(bytes) => bytes.as_mut_slice(),
691            ObjectHash::Sha256(bytes) => bytes.as_mut_slice(),
692            ObjectHash::Blake3(bytes) => bytes.as_mut_slice(),
693        }
694    }
695}
696
697thread_local! {
698    /// Thread-local variable to store the current hash kind.
699    /// This allows different threads to work with different hash algorithms concurrently
700    /// without interfering with each other.
701    static CURRENT_HASH_KIND: RefCell<HashKind> = RefCell::new(HashKind::default());
702}
703/// Set the thread-local hash kind (configure once at startup to match repo format).
704pub fn set_hash_kind(kind: HashKind) {
705    CURRENT_HASH_KIND.with(|h| {
706        *h.borrow_mut() = kind;
707    });
708}
709
710/// Retrieves the hash kind for the current thread.
711pub fn get_hash_kind() -> HashKind {
712    CURRENT_HASH_KIND.with(|h| *h.borrow())
713}
714/// A guard to reset the hash kind after the test
715pub struct HashKindGuard {
716    prev: HashKind,
717}
718/// Implementation of the `Drop` trait for the `HashKindGuard` struct.
719impl Drop for HashKindGuard {
720    fn drop(&mut self) {
721        set_hash_kind(self.prev);
722    }
723}
724/// Sets the hash kind for the current thread and returns a guard to reset it later.
725pub fn set_hash_kind_for_test(kind: HashKind) -> HashKindGuard {
726    let prev = get_hash_kind();
727    set_hash_kind(kind);
728    HashKindGuard { prev }
729}
730#[cfg(test)]
731mod tests {
732
733    use std::{
734        io::{BufReader, Read, Seek, SeekFrom},
735        str::FromStr,
736    };
737
738    use crate::{
739        hash::{HashError, HashKind, ObjectHash, set_hash_kind_for_test},
740        internal::{object::types::ObjectType, pack::test_pack_download::download_pack_file},
741        utils::HashAlgorithm,
742    };
743
744    /// Hashing "Hello, world!" with SHA1 should match known value.
745    #[test]
746    fn test_sha1_new() {
747        // Set hash kind to SHA1 for this test
748        let _guard = set_hash_kind_for_test(HashKind::Sha1);
749        // Example input
750        let data = "Hello, world!".as_bytes();
751
752        // Generate SHA1 hash from the input data
753        let sha1 = ObjectHash::new(data);
754
755        // Known SHA1 hash for "Hello, world!"
756        let expected_sha1_hash = "943a702d06f34599aee1f8da8ef9f7296031d699";
757
758        assert_eq!(sha1.to_string(), expected_sha1_hash);
759    }
760
761    /// Hashing "Hello, world!" with SHA256 should match known value.
762    #[test]
763    fn test_sha256_new() {
764        let _guard = set_hash_kind_for_test(HashKind::Sha256);
765        let data = "Hello, world!".as_bytes();
766        let sha256 = ObjectHash::new(data);
767        let expected_sha256_hash =
768            "315f5bdb76d078c43b8ac0064e4a0164612b1fce77c869345bfc94c75894edd3";
769        assert_eq!(sha256.to_string(), expected_sha256_hash);
770    }
771
772    /// Read pack trailer for SHA1 pack should yield SHA1 hash.
773    #[test]
774    fn test_signature_without_delta() {
775        let _guard = set_hash_kind_for_test(HashKind::Sha1);
776        let (source, _dl_guard) = download_pack_file("small-sha1.pack");
777
778        let f = std::fs::File::open(source).unwrap();
779        let mut buffered = BufReader::new(f);
780
781        buffered.seek(SeekFrom::End(-20)).unwrap();
782        let mut buffer = vec![0; 20];
783        buffered.read_exact(&mut buffer).unwrap();
784        let signature = ObjectHash::from_bytes(buffer.as_ref()).unwrap();
785        assert_eq!(signature.kind(), HashKind::Sha1);
786    }
787
788    /// Read pack trailer for SHA256 pack should yield SHA256 hash.
789    #[test]
790    fn test_signature_without_delta_sha256() {
791        let _guard = set_hash_kind_for_test(HashKind::Sha256);
792        let (source, _dl_guard) = download_pack_file("small-sha256.pack");
793
794        let f = std::fs::File::open(source).unwrap();
795        let mut buffered = BufReader::new(f);
796
797        buffered.seek(SeekFrom::End(-32)).unwrap();
798        let mut buffer = vec![0; 32];
799        buffered.read_exact(&mut buffer).unwrap();
800        let signature = ObjectHash::from_bytes(buffer.as_ref()).unwrap();
801        assert_eq!(signature.kind(), HashKind::Sha256);
802    }
803
804    /// Construct SHA1 from raw bytes.
805    #[test]
806    fn test_sha1_from_bytes() {
807        let _guard = set_hash_kind_for_test(HashKind::Sha1);
808        let sha1 = ObjectHash::from_bytes(&[
809            0x8a, 0xb6, 0x86, 0xea, 0xfe, 0xb1, 0xf4, 0x47, 0x02, 0x73, 0x8c, 0x8b, 0x0f, 0x24,
810            0xf2, 0x56, 0x7c, 0x36, 0xda, 0x6d,
811        ])
812        .unwrap();
813
814        assert_eq!(sha1.to_string(), "8ab686eafeb1f44702738c8b0f24f2567c36da6d");
815    }
816
817    /// Construct SHA256 from raw bytes.
818    #[test]
819    fn test_sha256_from_bytes() {
820        let _guard = set_hash_kind_for_test(HashKind::Sha256);
821        // Pre-calculated SHA256 hash for "abc"
822        let sha256 = ObjectHash::from_bytes(&[
823            0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae,
824            0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61,
825            0xf2, 0x00, 0x15, 0xad,
826        ])
827        .unwrap();
828
829        assert_eq!(
830            sha256.to_string(),
831            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
832        );
833    }
834
835    /// Read hash from stream for SHA1.
836    #[test]
837    fn test_from_stream() {
838        let _guard = set_hash_kind_for_test(HashKind::Sha1);
839        let source = [
840            0x8a, 0xb6, 0x86, 0xea, 0xfe, 0xb1, 0xf4, 0x47, 0x02, 0x73, 0x8c, 0x8b, 0x0f, 0x24,
841            0xf2, 0x56, 0x7c, 0x36, 0xda, 0x6d,
842        ];
843        let mut reader = std::io::Cursor::new(source);
844        let sha1 = ObjectHash::from_stream(&mut reader).unwrap();
845        assert_eq!(sha1.to_string(), "8ab686eafeb1f44702738c8b0f24f2567c36da6d");
846    }
847
848    /// Read hash from stream for SHA256.
849    #[test]
850    fn test_sha256_from_stream() {
851        let _guard = set_hash_kind_for_test(HashKind::Sha256);
852        let source = [
853            0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae,
854            0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61,
855            0xf2, 0x00, 0x15, 0xad,
856        ];
857        let mut reader = std::io::Cursor::new(source);
858        let sha256 = ObjectHash::from_stream(&mut reader).unwrap();
859        assert_eq!(
860            sha256.to_string(),
861            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
862        );
863    }
864
865    /// Parse SHA1 from hex string.
866    #[test]
867    fn test_sha1_from_str() {
868        let _guard = set_hash_kind_for_test(HashKind::Sha1);
869        let hash_str = "8ab686eafeb1f44702738c8b0f24f2567c36da6d";
870
871        match ObjectHash::from_str(hash_str) {
872            Ok(hash) => {
873                assert_eq!(hash.to_string(), "8ab686eafeb1f44702738c8b0f24f2567c36da6d");
874            }
875            Err(e) => println!("Error: {e}"),
876        }
877    }
878
879    /// Parse SHA256 from hex string.
880    #[test]
881    fn test_sha256_from_str() {
882        let _guard = set_hash_kind_for_test(HashKind::Sha256);
883        let hash_str = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
884
885        match ObjectHash::from_str(hash_str) {
886            Ok(hash) => {
887                assert_eq!(
888                    hash.to_string(),
889                    "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
890                );
891            }
892            Err(e) => println!("Error: {e}"),
893        }
894    }
895
896    /// SHA1 to_string should round-trip.
897    #[test]
898    fn test_sha1_to_string() {
899        let _guard = set_hash_kind_for_test(HashKind::Sha1);
900        let hash_str = "8ab686eafeb1f44702738c8b0f24f2567c36da6d";
901
902        match ObjectHash::from_str(hash_str) {
903            Ok(hash) => {
904                assert_eq!(hash.to_string(), "8ab686eafeb1f44702738c8b0f24f2567c36da6d");
905            }
906            Err(e) => println!("Error: {e}"),
907        }
908    }
909
910    /// SHA256 to_string should round-trip.
911    #[test]
912    fn test_sha256_to_string() {
913        let _guard = set_hash_kind_for_test(HashKind::Sha256);
914        let hash_str = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
915        match ObjectHash::from_str(hash_str) {
916            Ok(hash) => {
917                assert_eq!(
918                    hash.to_string(),
919                    "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
920                );
921            }
922            Err(e) => println!("Error: {e}"),
923        }
924    }
925
926    /// SHA1 to_data should produce expected bytes.
927    #[test]
928    fn test_sha1_to_data() {
929        let _guard = set_hash_kind_for_test(HashKind::Sha1);
930        let hash_str = "8ab686eafeb1f44702738c8b0f24f2567c36da6d";
931
932        match ObjectHash::from_str(hash_str) {
933            Ok(hash) => {
934                assert_eq!(
935                    hash.to_data(),
936                    vec![
937                        0x8a, 0xb6, 0x86, 0xea, 0xfe, 0xb1, 0xf4, 0x47, 0x02, 0x73, 0x8c, 0x8b,
938                        0x0f, 0x24, 0xf2, 0x56, 0x7c, 0x36, 0xda, 0x6d
939                    ]
940                );
941            }
942            Err(e) => println!("Error: {e}"),
943        }
944    }
945
946    /// SHA256 to_data should produce expected bytes.
947    #[test]
948    fn test_sha256_to_data() {
949        let _guard = set_hash_kind_for_test(HashKind::Sha256);
950        let hash_str = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
951        match ObjectHash::from_str(hash_str) {
952            Ok(hash) => {
953                assert_eq!(
954                    hash.to_data(),
955                    vec![
956                        0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde,
957                        0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c,
958                        0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad,
959                    ]
960                );
961            }
962            Err(e) => println!("Error: {e}"),
963        }
964    }
965    const HELLO_SHA1: &str = "943a702d06f34599aee1f8da8ef9f7296031d699";
966    const HELLO_SHA256: &str = "315f5bdb76d078c43b8ac0064e4a0164612b1fce77c869345bfc94c75894edd3";
967
968    /// Explicit-kind constructors must ignore the thread-local kind and agree with the
969    /// thread-local wrappers when the kinds coincide.
970    #[test]
971    fn object_hash_for_kind_ignores_thread_local() {
972        let data = b"Hello, world!";
973        for (kind, other, expected) in [
974            (HashKind::Sha1, HashKind::Sha256, HELLO_SHA1),
975            (HashKind::Sha256, HashKind::Sha1, HELLO_SHA256),
976        ] {
977            // Deliberately configure the *other* kind on this thread.
978            let _guard = set_hash_kind_for_test(other);
979
980            let digest = ObjectHash::new_for_kind(kind, data);
981            assert_eq!(digest.kind(), kind);
982            assert_eq!(digest.to_string(), expected);
983            assert_eq!(digest.size(), kind.size());
984            assert_eq!(digest.to_string().len(), kind.hex_len());
985
986            // Raw hex / bytes / stream round-trips under the explicit kind.
987            let from_hex = ObjectHash::from_hex_for_kind(kind, expected).unwrap();
988            assert_eq!(from_hex, digest);
989            let from_bytes = ObjectHash::from_bytes_for_kind(kind, digest.as_ref()).unwrap();
990            assert_eq!(from_bytes, digest);
991            let mut cursor = std::io::Cursor::new(digest.to_data());
992            let from_stream = ObjectHash::from_stream_for_kind(kind, &mut cursor).unwrap();
993            assert_eq!(from_stream, digest);
994
995            // Canonical Git object hash with header must match the thread-local path
996            // once the thread-local is switched to the same kind.
997            let explicit =
998                ObjectHash::from_type_and_data_for_kind(kind, ObjectType::Blob, data).unwrap();
999            assert_eq!(explicit.kind(), kind);
1000            {
1001                let _same = set_hash_kind_for_test(kind);
1002                assert_eq!(
1003                    ObjectHash::from_type_and_data(ObjectType::Blob, data),
1004                    explicit
1005                );
1006                assert_eq!(ObjectHash::new(data), digest);
1007                assert_eq!(ObjectHash::from_bytes(digest.as_ref()).unwrap(), digest);
1008            }
1009
1010            // Zero IDs.
1011            let zero = ObjectHash::zero_for_kind(kind);
1012            assert_eq!(zero.kind(), kind);
1013            assert!(zero.as_ref().iter().all(|b| *b == 0));
1014            assert_eq!(zero.to_string(), ObjectHash::zero_str(kind));
1015            assert_eq!(ObjectHash::zero_str(kind).len(), kind.hex_len());
1016        }
1017        assert_eq!(
1018            ObjectHash::default(),
1019            ObjectHash::zero_for_kind(HashKind::Sha1)
1020        );
1021    }
1022
1023    /// Length, hex and kind mismatches fail closed with diagnostic errors and never
1024    /// fall back to the other algorithm.
1025    #[test]
1026    fn object_hash_for_kind_errors_fail_closed() {
1027        // 64 hex chars requested as SHA-1: length error carrying kind + lengths.
1028        let err = ObjectHash::from_hex_for_kind(HashKind::Sha1, HELLO_SHA256).unwrap_err();
1029        assert_eq!(
1030            err,
1031            HashError::InvalidLength {
1032                operation: "from_hex_for_kind",
1033                kind: HashKind::Sha1,
1034                expected: 40,
1035                actual: 64,
1036            }
1037        );
1038        let msg = err.to_string();
1039        assert!(
1040            msg.contains("sha1") && msg.contains("40") && msg.contains("64"),
1041            "{msg}"
1042        );
1043
1044        // 40 hex chars requested as SHA-256: no silent SHA-1 fallback.
1045        let err = ObjectHash::from_hex_for_kind(HashKind::Sha256, HELLO_SHA1).unwrap_err();
1046        assert!(matches!(
1047            err,
1048            HashError::InvalidLength {
1049                kind: HashKind::Sha256,
1050                expected: 64,
1051                actual: 40,
1052                ..
1053            }
1054        ));
1055
1056        // Non-hex input of the right length.
1057        let bad = "zz".repeat(20);
1058        let err = ObjectHash::from_hex_for_kind(HashKind::Sha1, &bad).unwrap_err();
1059        assert!(matches!(
1060            err,
1061            HashError::InvalidHex {
1062                kind: HashKind::Sha1,
1063                expected: 40,
1064                actual: 40,
1065                ..
1066            }
1067        ));
1068        let msg = err.to_string();
1069        assert!(msg.contains("sha1") && msg.contains("40"), "{msg}");
1070
1071        // Delta types have no loose-object header: explicit API fails closed.
1072        let err =
1073            ObjectHash::from_type_and_data_for_kind(HashKind::Sha1, ObjectType::OffsetDelta, b"x")
1074                .unwrap_err();
1075        assert_eq!(
1076            err,
1077            HashError::UnsupportedObjectType {
1078                operation: "from_type_and_data_for_kind",
1079                kind: HashKind::Sha1,
1080                object_type: ObjectType::OffsetDelta,
1081                expected: 20,
1082                actual: 0,
1083                payload_len: 1,
1084            }
1085        );
1086
1087        // Raw bytes of the wrong width.
1088        let err = ObjectHash::from_bytes_for_kind(HashKind::Sha256, &[0u8; 20]).unwrap_err();
1089        assert!(matches!(
1090            err,
1091            HashError::InvalidLength {
1092                operation: "from_bytes_for_kind",
1093                kind: HashKind::Sha256,
1094                expected: 32,
1095                actual: 20,
1096            }
1097        ));
1098        // The thread-local wrapper keeps its legacy error string verbatim.
1099        let _guard = set_hash_kind_for_test(HashKind::Sha256);
1100        let msg = ObjectHash::from_bytes(&[0u8; 20]).unwrap_err();
1101        assert_eq!(msg, "Invalid byte length: got 20, expected 32");
1102
1103        // Reader failures surface as `HashError::Io` with the bytes read so far;
1104        // `Interrupted` is retried transparently.
1105        struct FlakyReader {
1106            chunks: Vec<std::io::Result<&'static [u8]>>,
1107        }
1108        impl std::io::Read for FlakyReader {
1109            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
1110                match self.chunks.remove(0) {
1111                    Ok(bytes) => {
1112                        buf[..bytes.len()].copy_from_slice(bytes);
1113                        Ok(bytes.len())
1114                    }
1115                    Err(e) => Err(e),
1116                }
1117            }
1118        }
1119        let mut broken = FlakyReader {
1120            chunks: vec![
1121                Ok(&[0u8; 8][..]),
1122                Err(std::io::Error::new(
1123                    std::io::ErrorKind::Interrupted,
1124                    "retry",
1125                )),
1126                Ok(&[0u8; 4][..]),
1127                Err(std::io::Error::other("disk gone")),
1128            ],
1129        };
1130        let err = ObjectHash::from_stream_for_kind(HashKind::Sha1, &mut broken).unwrap_err();
1131        assert_eq!(
1132            err,
1133            HashError::Io {
1134                operation: "from_stream_for_kind",
1135                kind: HashKind::Sha1,
1136                expected: 20,
1137                actual: 12,
1138                error_kind: std::io::ErrorKind::Other,
1139                message: "disk gone".to_string(),
1140            }
1141        );
1142        assert_eq!(std::io::Error::from(err).kind(), std::io::ErrorKind::Other);
1143        let mut healed = FlakyReader {
1144            chunks: vec![
1145                Ok(&[0xab; 8][..]),
1146                Err(std::io::Error::new(
1147                    std::io::ErrorKind::Interrupted,
1148                    "retry",
1149                )),
1150                Ok(&[0xab; 12][..]),
1151            ],
1152        };
1153        assert_eq!(
1154            ObjectHash::from_stream_for_kind(HashKind::Sha1, &mut healed).unwrap(),
1155            ObjectHash::Sha1([0xab; 20])
1156        );
1157
1158        // Short stream.
1159        let mut short = std::io::Cursor::new(vec![0u8; 10]);
1160        let err = ObjectHash::from_stream_for_kind(HashKind::Sha1, &mut short).unwrap_err();
1161        assert_eq!(
1162            err,
1163            HashError::InvalidLength {
1164                operation: "from_stream_for_kind",
1165                kind: HashKind::Sha1,
1166                expected: 20,
1167                actual: 10,
1168            }
1169        );
1170        assert_eq!(
1171            std::io::Error::from(err).kind(),
1172            std::io::ErrorKind::UnexpectedEof
1173        );
1174        let mut short = std::io::Cursor::new(vec![0u8; 10]);
1175        let err = ObjectHash::from_stream(&mut short).unwrap_err();
1176        assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof);
1177
1178        // Kind mismatch guard.
1179        let sha256 = ObjectHash::from_hex_for_kind(HashKind::Sha256, HELLO_SHA256).unwrap();
1180        assert_eq!(sha256.ensure_kind(HashKind::Sha256), Ok(()));
1181        assert_eq!(
1182            sha256.ensure_kind(HashKind::Sha1),
1183            Err(HashError::KindMismatch {
1184                operation: "ensure_kind",
1185                expected: HashKind::Sha1,
1186                actual: HashKind::Sha256,
1187                expected_len: 20,
1188                actual_len: 32,
1189            })
1190        );
1191    }
1192
1193    /// Tagged IDs carry the algorithm explicitly and round-trip for every kind.
1194    #[test]
1195    fn object_hash_for_kind_tagged_round_trip() {
1196        let _guard = set_hash_kind_for_test(HashKind::Sha1);
1197        let sha1 = ObjectHash::from_hex_for_kind(HashKind::Sha1, HELLO_SHA1).unwrap();
1198        let sha256 = ObjectHash::from_hex_for_kind(HashKind::Sha256, HELLO_SHA256).unwrap();
1199
1200        assert_eq!(sha1.to_tagged_string(), format!("sha1:{HELLO_SHA1}"));
1201        assert_eq!(sha256.to_tagged_string(), format!("sha256:{HELLO_SHA256}"));
1202        assert_eq!(
1203            ObjectHash::from_tagged_str(&sha1.to_tagged_string()).unwrap(),
1204            sha1
1205        );
1206        assert_eq!(
1207            ObjectHash::from_tagged_str(&sha256.to_tagged_string()).unwrap(),
1208            sha256
1209        );
1210
1211        // Raw Display is unchanged by the tagged API.
1212        assert_eq!(sha1.to_string(), HELLO_SHA1);
1213        assert_eq!(sha256.to_string(), HELLO_SHA256);
1214
1215        // Unknown / missing tags and tag-length mismatches fail closed.
1216        assert!(matches!(
1217            ObjectHash::from_tagged_str(&format!("md5:{HELLO_SHA1}")).unwrap_err(),
1218            HashError::UnknownKind { tag, expected_tags: "sha1|sha256|blake3", actual: 3, hex_len: 40, .. } if tag == "md5"
1219        ));
1220        assert!(matches!(
1221            ObjectHash::from_tagged_str(HELLO_SHA1).unwrap_err(),
1222            HashError::UnknownKind { .. }
1223        ));
1224        assert!(matches!(
1225            ObjectHash::from_tagged_str(&format!("sha1:{HELLO_SHA256}")).unwrap_err(),
1226            HashError::InvalidLength {
1227                kind: HashKind::Sha1,
1228                expected: 40,
1229                actual: 64,
1230                ..
1231            }
1232        ));
1233    }
1234
1235    /// The legacy length-inferring parsers keep their frozen contract regardless of the
1236    /// thread-local kind: 40 hex / 20 bytes → SHA-1, 64 hex / 32 bytes → SHA-256.
1237    #[test]
1238    #[allow(deprecated)]
1239    fn object_hash_for_kind_legacy_parsers_unchanged() {
1240        for other in [HashKind::Sha1, HashKind::Sha256] {
1241            let _guard = set_hash_kind_for_test(other);
1242            assert_eq!(
1243                ObjectHash::from_str(HELLO_SHA1).unwrap().kind(),
1244                HashKind::Sha1
1245            );
1246            assert_eq!(
1247                ObjectHash::from_str(HELLO_SHA256).unwrap().kind(),
1248                HashKind::Sha256
1249            );
1250            assert_eq!(
1251                ObjectHash::from_str("abc").unwrap_err(),
1252                "Invalid hash length".to_string()
1253            );
1254            assert!(ObjectHash::from_str(&"zz".repeat(20)).is_err());
1255            assert_eq!(
1256                ObjectHash::from_bytes_infer_kind(&[0u8; 20])
1257                    .unwrap()
1258                    .kind(),
1259                HashKind::Sha1
1260            );
1261            assert_eq!(
1262                ObjectHash::from_bytes_infer_kind(&[0u8; 32])
1263                    .unwrap()
1264                    .kind(),
1265                HashKind::Sha256
1266            );
1267            assert!(ObjectHash::from_bytes_infer_kind(&[0u8; 16]).is_err());
1268        }
1269    }
1270
1271    /// Official BLAKE3 test vectors (BLAKE3-team/BLAKE3 `test_vectors.json`, first 32 output
1272    /// bytes): input byte `i` is `i % 251`.
1273    const BLAKE3_VECTORS: &[(usize, &str)] = &[
1274        (
1275            0,
1276            "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262",
1277        ),
1278        (
1279            1,
1280            "2d3adedff11b61f14c886e35afa036736dcd87a74d27b5c1510225d0f592e213",
1281        ),
1282        (
1283            2,
1284            "7b7015bb92cf0b318037702a6cdd81dee41224f734684c2c122cd6359cb1ee63",
1285        ),
1286        (
1287            3,
1288            "e1be4d7a8ab5560aa4199eea339849ba8e293d55ca0a81006726d184519e647f",
1289        ),
1290        (
1291            4,
1292            "f30f5ab28fe047904037f77b6da4fea1e27241c5d132638d8bedce9d40494f32",
1293        ),
1294        (
1295            5,
1296            "b40b44dfd97e7a84a996a91af8b85188c66c126940ba7aad2e7ae6b385402aa2",
1297        ),
1298        (
1299            6,
1300            "06c4e8ffb6872fad96f9aaca5eee1553eb62aed0ad7198cef42e87f6a616c844",
1301        ),
1302        (
1303            7,
1304            "3f8770f387faad08faa9d8414e9f449ac68e6ff0417f673f602a646a891419fe",
1305        ),
1306        (
1307            8,
1308            "2351207d04fc16ade43ccab08600939c7c1fa70a5c0aaca76063d04c3228eaeb",
1309        ),
1310        (
1311            63,
1312            "e9bc37a594daad83be9470df7f7b3798297c3d834ce80ba85d6e207627b7db7b",
1313        ),
1314        (
1315            64,
1316            "4eed7141ea4a5cd4b788606bd23f46e212af9cacebacdc7d1f4c6dc7f2511b98",
1317        ),
1318        (
1319            65,
1320            "de1e5fa0be70df6d2be8fffd0e99ceaa8eb6e8c93a63f2d8d1c30ecb6b263dee",
1321        ),
1322        (
1323            127,
1324            "d81293fda863f008c09e92fc382a81f5a0b4a1251cba1634016a0f86a6bd640d",
1325        ),
1326        (
1327            128,
1328            "f17e570564b26578c33bb7f44643f539624b05df1a76c81f30acd548c44b45ef",
1329        ),
1330        (
1331            129,
1332            "683aaae9f3c5ba37eaaf072aed0f9e30bac0865137bae68b1fde4ca2aebdcb12",
1333        ),
1334        (
1335            1023,
1336            "10108970eeda3eb932baac1428c7a2163b0e924c9a9e25b35bba72b28f70bd11",
1337        ),
1338        (
1339            1024,
1340            "42214739f095a406f3fc83deb889744ac00df831c10daa55189b5d121c855af7",
1341        ),
1342        (
1343            1025,
1344            "d00278ae47eb27b34faecf67b4fe263f82d5412916c1ffd97c8cb7fb814b8444",
1345        ),
1346        (
1347            2048,
1348            "e776b6028c7cd22a4d0ba182a8bf62205d2ef576467e838ed6f2529b85fba24a",
1349        ),
1350        (
1351            3072,
1352            "b98cb0ff3623be03326b373de6b9095218513e64f1ee2edd2525c7ad1e5cffd2",
1353        ),
1354        (
1355            4096,
1356            "015094013f57a5277b59d8475c0501042c0b642e531b0a1c8f58d2163229e969",
1357        ),
1358        (
1359            8192,
1360            "aae792484c8efe4f19e2ca7d371d8c467ffb10748d8a5a1ae579948f718a2a63",
1361        ),
1362        (
1363            31744,
1364            "62b6960e1a44bcc1eb1a611a8d6235b6b4b78f32e7abc4fb4c6cdcce94895c47",
1365        ),
1366        (
1367            102400,
1368            "bc3e3d41a1146b069abffad3c0d44860cf664390afce4d9661f7902e7943e085",
1369        ),
1370    ];
1371
1372    /// BLAKE3 digests match the official vectors through every entry point (one-shot,
1373    /// chunked streaming, `Write` sink) and the Git canonical header path is consistent.
1374    #[test]
1375    fn blake3_known_vectors() {
1376        // Run under a SHA-1 thread-local to prove the explicit kind is what matters.
1377        let _guard = set_hash_kind_for_test(HashKind::Sha1);
1378        for &(len, expected) in BLAKE3_VECTORS {
1379            let input: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect();
1380
1381            let one_shot = ObjectHash::new_for_kind(HashKind::Blake3, &input);
1382            assert_eq!(one_shot.kind(), HashKind::Blake3);
1383            assert_eq!(one_shot.to_string(), expected, "len {len}");
1384            assert_eq!(one_shot.size(), 32);
1385
1386            // Chunked streaming through HashAlgorithm must agree.
1387            let mut hasher = HashAlgorithm::new_for_kind(HashKind::Blake3);
1388            assert_eq!(hasher.kind(), HashKind::Blake3);
1389            for chunk in input.chunks(97) {
1390                hasher.update(chunk);
1391            }
1392            assert_eq!(hasher.finalize_object_hash(), one_shot, "len {len}");
1393
1394            let mut sink = HashAlgorithm::new_for_kind(HashKind::Blake3);
1395            std::io::Write::write_all(&mut sink, &input).unwrap();
1396            assert_eq!(hex::encode(sink.finalize()), expected, "len {len}");
1397        }
1398
1399        // Git canonical header: hash("blob <size>\0" + data) via the crate directly.
1400        let data = b"Hello, world!";
1401        let object_id =
1402            ObjectHash::from_type_and_data_for_kind(HashKind::Blake3, ObjectType::Blob, data)
1403                .unwrap();
1404        let mut reference = blake3::Hasher::new();
1405        reference.update(b"blob 13\x00");
1406        reference.update(data);
1407        assert_eq!(
1408            object_id,
1409            ObjectHash::Blake3(*reference.finalize().as_bytes())
1410        );
1411        assert_eq!(object_id.to_string().len(), 64);
1412        // Same payload, same width, different algorithm: never equal to SHA-256.
1413        let sha256_id =
1414            ObjectHash::from_type_and_data_for_kind(HashKind::Sha256, ObjectType::Blob, data)
1415                .unwrap();
1416        assert_eq!(sha256_id.size(), object_id.size());
1417        assert_ne!(sha256_id, object_id);
1418        assert_ne!(sha256_id.as_ref(), object_id.as_ref());
1419        {
1420            let _b3 = set_hash_kind_for_test(HashKind::Blake3);
1421            assert_eq!(
1422                ObjectHash::from_type_and_data(ObjectType::Blob, data),
1423                object_id
1424            );
1425            assert_eq!(
1426                ObjectHash::new(data),
1427                ObjectHash::new_for_kind(HashKind::Blake3, data)
1428            );
1429            assert_eq!(HashAlgorithm::new().kind(), HashKind::Blake3);
1430        }
1431    }
1432
1433    /// BLAKE3 IDs are only produced under an explicit kind or a `blake3:` tag; a 64-hex /
1434    /// 32-byte value is never guessed to be BLAKE3, and SHA-256/BLAKE3 never alias.
1435    #[test]
1436    #[allow(deprecated)]
1437    fn blake3_context_and_tagged_id() {
1438        let _guard = set_hash_kind_for_test(HashKind::Sha256);
1439        let digest = ObjectHash::new_for_kind(HashKind::Blake3, b"payload");
1440        let hex_str = digest.to_string();
1441        assert_eq!(hex_str.len(), 64);
1442        assert_eq!(HashKind::Blake3.size(), 32);
1443        assert_eq!(HashKind::Blake3.hex_len(), 64);
1444        assert_eq!(HashKind::Blake3.as_str(), "blake3");
1445        assert_eq!(HashKind::Blake3.to_string(), "blake3");
1446        assert_eq!("blake3".parse::<HashKind>().unwrap(), HashKind::Blake3);
1447        assert!(!HashKind::Blake3.is_git_standard());
1448        assert!(HashKind::Sha1.is_git_standard() && HashKind::Sha256.is_git_standard());
1449
1450        // Explicit-kind parsers.
1451        assert_eq!(
1452            ObjectHash::from_hex_for_kind(HashKind::Blake3, &hex_str).unwrap(),
1453            digest
1454        );
1455        assert_eq!(
1456            ObjectHash::from_bytes_for_kind(HashKind::Blake3, digest.as_ref()).unwrap(),
1457            digest
1458        );
1459        let mut cursor = std::io::Cursor::new(digest.to_data());
1460        assert_eq!(
1461            ObjectHash::from_stream_for_kind(HashKind::Blake3, &mut cursor).unwrap(),
1462            digest
1463        );
1464        let zero = ObjectHash::zero_for_kind(HashKind::Blake3);
1465        assert_eq!(zero, ObjectHash::Blake3([0u8; 32]));
1466        assert_eq!(ObjectHash::zero_str(HashKind::Blake3), "0".repeat(64));
1467        assert_ne!(zero, ObjectHash::zero_for_kind(HashKind::Sha256));
1468
1469        // Same hex under the SHA-256 kind is a *different* value (distinct variant).
1470        let as_sha256 = ObjectHash::from_hex_for_kind(HashKind::Sha256, &hex_str).unwrap();
1471        assert_ne!(as_sha256, digest);
1472        assert_eq!(as_sha256.as_ref(), digest.as_ref());
1473        assert_eq!(as_sha256.kind(), HashKind::Sha256);
1474        assert_eq!(
1475            digest.ensure_kind(HashKind::Sha256),
1476            Err(HashError::KindMismatch {
1477                operation: "ensure_kind",
1478                expected: HashKind::Sha256,
1479                actual: HashKind::Blake3,
1480                expected_len: 32,
1481                actual_len: 32,
1482            })
1483        );
1484        assert!(
1485            as_sha256
1486                .ensure_kind(HashKind::Blake3)
1487                .unwrap_err()
1488                .to_string()
1489                .contains("blake3")
1490        );
1491
1492        // Tagged representation distinguishes the two 64-hex kinds.
1493        assert_eq!(digest.to_tagged_string(), format!("blake3:{hex_str}"));
1494        assert_eq!(as_sha256.to_tagged_string(), format!("sha256:{hex_str}"));
1495        assert_eq!(
1496            ObjectHash::from_tagged_str(&format!("blake3:{hex_str}")).unwrap(),
1497            digest
1498        );
1499        assert_eq!(
1500            ObjectHash::from_tagged_str(&format!("sha256:{hex_str}")).unwrap(),
1501            as_sha256
1502        );
1503        assert!(matches!(
1504            ObjectHash::from_tagged_str(&format!("blake3:{HELLO_SHA1}")).unwrap_err(),
1505            HashError::InvalidLength {
1506                kind: HashKind::Blake3,
1507                expected: 64,
1508                actual: 40,
1509                ..
1510            }
1511        ));
1512        assert!(matches!(
1513            ObjectHash::from_tagged_str(&format!("blake2:{hex_str}")).unwrap_err(),
1514            HashError::UnknownKind {
1515                expected_tags: "sha1|sha256|blake3",
1516                ..
1517            }
1518        ));
1519
1520        // Legacy inference never yields BLAKE3, regardless of the thread-local kind.
1521        for other in [HashKind::Sha1, HashKind::Sha256, HashKind::Blake3] {
1522            let _tl = set_hash_kind_for_test(other);
1523            assert_eq!(ObjectHash::from_str(&hex_str).unwrap(), as_sha256);
1524            assert_eq!(
1525                ObjectHash::from_str(&hex_str).unwrap().kind(),
1526                HashKind::Sha256
1527            );
1528            assert_eq!(
1529                ObjectHash::from_bytes_infer_kind(digest.as_ref())
1530                    .unwrap()
1531                    .kind(),
1532                HashKind::Sha256
1533            );
1534        }
1535        // Thread-local BLAKE3 drives the compatibility wrappers.
1536        {
1537            let _tl = set_hash_kind_for_test(HashKind::Blake3);
1538            assert_eq!(ObjectHash::from_bytes(digest.as_ref()).unwrap(), digest);
1539            let mut cursor = std::io::Cursor::new(digest.to_data());
1540            assert_eq!(ObjectHash::from_stream(&mut cursor).unwrap(), digest);
1541            assert_eq!(
1542                ObjectHash::from_bytes(&[0u8; 20]).unwrap_err(),
1543                "Invalid byte length: got 20, expected 32"
1544            );
1545        }
1546
1547        // serde: new variants round-trip and old SHA payloads still deserialize.
1548        let json = serde_json::to_string(&digest).unwrap();
1549        assert!(json.starts_with("{\"Blake3\":["), "{json}");
1550        assert_eq!(serde_json::from_str::<ObjectHash>(&json).unwrap(), digest);
1551        assert_eq!(
1552            serde_json::to_string(&HashKind::Blake3).unwrap(),
1553            "\"Blake3\""
1554        );
1555        assert_eq!(
1556            serde_json::from_str::<HashKind>("\"Blake3\"").unwrap(),
1557            HashKind::Blake3
1558        );
1559        let sha1 = ObjectHash::from_hex_for_kind(HashKind::Sha1, HELLO_SHA1).unwrap();
1560        let legacy_json = format!(
1561            "{{\"Sha1\":{}}}",
1562            serde_json::to_string(&sha1.to_data()).unwrap()
1563        );
1564        assert_eq!(
1565            serde_json::from_str::<ObjectHash>(&legacy_json).unwrap(),
1566            sha1
1567        );
1568        let legacy_json = format!(
1569            "{{\"Sha256\":{}}}",
1570            serde_json::to_string(&as_sha256.to_data()).unwrap()
1571        );
1572        assert_eq!(
1573            serde_json::from_str::<ObjectHash>(&legacy_json).unwrap(),
1574            as_sha256
1575        );
1576        assert_eq!(
1577            serde_json::from_str::<HashKind>("\"Sha256\"").unwrap(),
1578            HashKind::Sha256
1579        );
1580
1581        // Blake3 zero ID round-trips through serde and rkyv like any other value.
1582        let zero_json = serde_json::to_string(&zero).unwrap();
1583        assert_eq!(
1584            serde_json::from_str::<ObjectHash>(&zero_json).unwrap(),
1585            zero
1586        );
1587        let zero_rkyv = rkyv::to_bytes::<rkyv::rancor::Error>(&zero).unwrap();
1588        assert_eq!(
1589            rkyv::from_bytes::<ObjectHash, rkyv::rancor::Error>(&zero_rkyv).unwrap(),
1590            zero
1591        );
1592
1593        // rkyv: archived round-trip for every kind.
1594        for value in [sha1, as_sha256, digest, zero] {
1595            let bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&value).unwrap();
1596            let back = rkyv::from_bytes::<ObjectHash, rkyv::rancor::Error>(&bytes).unwrap();
1597            assert_eq!(back, value);
1598        }
1599        for kind in [HashKind::Sha1, HashKind::Sha256, HashKind::Blake3] {
1600            let bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&kind).unwrap();
1601            assert_eq!(
1602                rkyv::from_bytes::<HashKind, rkyv::rancor::Error>(&bytes).unwrap(),
1603                kind
1604            );
1605        }
1606    }
1607
1608    /// The AI IntegrityHash stays SHA-256 no matter which repository kind is active.
1609    #[test]
1610    fn blake3_does_not_change_integrity_hash() {
1611        use crate::internal::object::integrity::IntegrityHash;
1612        let content = b"integrity payload";
1613        let expected = {
1614            let _sha = set_hash_kind_for_test(HashKind::Sha256);
1615            IntegrityHash::compute(content)
1616        };
1617        for kind in [HashKind::Sha1, HashKind::Sha256, HashKind::Blake3] {
1618            let _tl = set_hash_kind_for_test(kind);
1619            let got = IntegrityHash::compute(content);
1620            assert_eq!(got, expected);
1621            assert_eq!(got.to_hex().len(), 64);
1622            assert_eq!(
1623                got.as_bytes(),
1624                ObjectHash::new_for_kind(HashKind::Sha256, content).as_ref()
1625            );
1626            assert_ne!(
1627                got.as_bytes(),
1628                ObjectHash::new_for_kind(HashKind::Blake3, content).as_ref()
1629            );
1630        }
1631    }
1632
1633    /// Archives written by the pre-BLAKE3 crate (captured from the 0.8.7 baseline build)
1634    /// still deserialize, and the new build emits byte-identical archives for SHA values:
1635    /// the Blake3 variant is appended, so existing discriminants and layouts are unchanged.
1636    #[test]
1637    fn blake3_legacy_archives_still_deserialize() {
1638        // rkyv bytes produced by git-internal 0.8.7 (before HashKind::Blake3 existed).
1639        const LEGACY_RKYV_SHA1: &str =
1640            "001111111111111111111111111111111111111111000000000000000000000000";
1641        const LEGACY_RKYV_SHA256: &str =
1642            "012222222222222222222222222222222222222222222222222222222222222222";
1643        const LEGACY_RKYV_KIND_SHA1: &str = "00";
1644        const LEGACY_RKYV_KIND_SHA256: &str = "01";
1645        const LEGACY_JSON_SHA1: &str =
1646            "{\"Sha1\":[17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17]}";
1647
1648        let sha1 = ObjectHash::Sha1([0x11; 20]);
1649        let sha256 = ObjectHash::Sha256([0x22; 32]);
1650        let decode = |hex_bytes: &str| hex::decode(hex_bytes).unwrap();
1651
1652        assert_eq!(
1653            rkyv::from_bytes::<ObjectHash, rkyv::rancor::Error>(&decode(LEGACY_RKYV_SHA1)).unwrap(),
1654            sha1
1655        );
1656        assert_eq!(
1657            rkyv::from_bytes::<ObjectHash, rkyv::rancor::Error>(&decode(LEGACY_RKYV_SHA256))
1658                .unwrap(),
1659            sha256
1660        );
1661        assert_eq!(
1662            rkyv::from_bytes::<HashKind, rkyv::rancor::Error>(&decode(LEGACY_RKYV_KIND_SHA1))
1663                .unwrap(),
1664            HashKind::Sha1
1665        );
1666        assert_eq!(
1667            rkyv::from_bytes::<HashKind, rkyv::rancor::Error>(&decode(LEGACY_RKYV_KIND_SHA256))
1668                .unwrap(),
1669            HashKind::Sha256
1670        );
1671        // Layout stability: the new crate writes the same bytes the old one did.
1672        assert_eq!(
1673            hex::encode(rkyv::to_bytes::<rkyv::rancor::Error>(&sha1).unwrap()),
1674            LEGACY_RKYV_SHA1
1675        );
1676        assert_eq!(
1677            hex::encode(rkyv::to_bytes::<rkyv::rancor::Error>(&sha256).unwrap()),
1678            LEGACY_RKYV_SHA256
1679        );
1680        assert_eq!(
1681            hex::encode(rkyv::to_bytes::<rkyv::rancor::Error>(&HashKind::Sha256).unwrap()),
1682            LEGACY_RKYV_KIND_SHA256
1683        );
1684        assert_eq!(
1685            serde_json::from_str::<ObjectHash>(LEGACY_JSON_SHA1).unwrap(),
1686            sha1
1687        );
1688        assert_eq!(serde_json::to_string(&sha1).unwrap(), LEGACY_JSON_SHA1);
1689        assert_eq!(
1690            serde_json::from_str::<HashKind>("\"Sha256\"").unwrap(),
1691            HashKind::Sha256
1692        );
1693    }
1694}