Skip to main content

git_internal/
utils.rs

1//! Shared I/O utilities for Git-internal including buffered readers, the streaming hash
2//! abstraction over SHA-1 / SHA-256 / BLAKE3-256, and helpers for reading pack/file bytes while
3//! tracking stream progress.
4
5use std::{
6    io,
7    io::{BufRead, Read},
8};
9
10use sha1::{Digest, Sha1};
11
12use crate::hash::{HashError, HashKind, ObjectHash, get_hash_kind};
13/// Read exactly `len` bytes from the given reader.
14pub fn read_bytes(file: &mut impl Read, len: usize) -> io::Result<Vec<u8>> {
15    let mut buf = vec![0; len];
16    file.read_exact(&mut buf)?;
17    Ok(buf)
18}
19
20/// Read an object hash of an explicit `kind` from the given reader.
21///
22/// Does not consult the thread-local [`HashKind`]; a short or failing read
23/// surfaces as [`HashError`] with the expected/actual byte counts.
24pub fn read_sha_for_kind(kind: HashKind, file: &mut impl Read) -> Result<ObjectHash, HashError> {
25    ObjectHash::from_stream_for_kind(kind, file)
26}
27
28/// Read an object hash from the given reader using the thread-local [`HashKind`].
29///
30/// Legacy entry point; delegates to [`ObjectHash::from_stream`], whose
31/// `read_exact`-based error surface is unchanged.
32pub fn read_sha(file: &mut impl Read) -> io::Result<ObjectHash> {
33    ObjectHash::from_stream(file)
34}
35
36/// A lightweight wrapper that counts bytes read from the underlying reader.
37/// replace deflate.intotal() in decompress_data
38pub struct CountingReader<R> {
39    pub inner: R,
40    pub bytes_read: u64,
41}
42
43impl<R> CountingReader<R> {
44    /// Creates a new `CountingReader` wrapping the given reader.
45    pub fn new(inner: R) -> Self {
46        Self {
47            inner,
48            bytes_read: 0,
49        }
50    }
51}
52
53impl<R: Read> Read for CountingReader<R> {
54    /// Reads data into the provided buffer, updating the byte count.
55    /// Returns the number of bytes read.
56    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
57        let n = self.inner.read(buf)?;
58        self.bytes_read += n as u64;
59        Ok(n)
60    }
61}
62
63impl<R: BufRead> BufRead for CountingReader<R> {
64    /// Fills the internal buffer and returns a slice to it.
65    /// Updates the byte count.
66    /// Returns the number of bytes read.
67    fn fill_buf(&mut self) -> io::Result<&[u8]> {
68        self.inner.fill_buf()
69    }
70
71    /// Consumes `amt` bytes from the internal buffer, updating the byte count.
72    /// Returns the number of bytes consumed.
73    fn consume(&mut self, amt: usize) {
74        self.bytes_read += amt as u64;
75        self.inner.consume(amt);
76    }
77}
78/// A streaming hasher abstraction over the supported [`HashKind`]s.
79///
80/// This is the crate's digest factory (GC-02): callers obtain a hasher through
81/// [`HashAlgorithm::new_for_kind`] (explicit repository kind) or
82/// [`HashAlgorithm::new`] (thread-local compatibility default) instead of
83/// matching on the algorithm themselves. The remaining direct SHA dispatch in
84/// `internal/pack/utils.rs` and `internal/pack/wrapper.rs` is migrated onto
85/// this type in B3-03. It implements `std::io::Write` so it can be used as a
86/// sink while streaming.
87#[derive(Clone)]
88pub enum HashAlgorithm {
89    Sha1(Sha1),
90    Sha256(sha2::Sha256),
91    /// BLAKE3-256 (git-internal / Libra extension; 32-byte output). Boxed because the
92    /// BLAKE3 hasher state is much larger than the SHA states.
93    Blake3(Box<blake3::Hasher>),
94}
95impl HashAlgorithm {
96    /// Create a new streaming hasher for an explicit `kind`.
97    ///
98    /// Does not consult the thread-local [`HashKind`]; use this on worker
99    /// threads, async tasks and any code that may serve a repository other
100    /// than the one configured on the current thread.
101    pub fn new_for_kind(kind: HashKind) -> Self {
102        match kind {
103            HashKind::Sha1 => HashAlgorithm::Sha1(Sha1::new()),
104            HashKind::Sha256 => HashAlgorithm::Sha256(sha2::Sha256::new()),
105            HashKind::Blake3 => HashAlgorithm::Blake3(Box::new(blake3::Hasher::new())),
106        }
107    }
108    /// Create a new hash algorithm instance based on the current thread-local hash kind.
109    ///
110    /// Compatibility wrapper around [`HashAlgorithm::new_for_kind`].
111    pub fn new() -> Self {
112        Self::new_for_kind(get_hash_kind())
113    }
114    /// The [`HashKind`] this hasher produces.
115    pub fn kind(&self) -> HashKind {
116        match self {
117            HashAlgorithm::Sha1(_) => HashKind::Sha1,
118            HashAlgorithm::Sha256(_) => HashKind::Sha256,
119            HashAlgorithm::Blake3(_) => HashKind::Blake3,
120        }
121    }
122    /// Update hash with data
123    pub fn update(&mut self, data: &[u8]) {
124        match self {
125            HashAlgorithm::Sha1(hasher) => hasher.update(data),
126            HashAlgorithm::Sha256(hasher) => hasher.update(data),
127            HashAlgorithm::Blake3(hasher) => {
128                hasher.update(data);
129            }
130        }
131    }
132    /// Finalize and get the raw digest bytes.
133    pub fn finalize(self) -> Vec<u8> {
134        match self {
135            HashAlgorithm::Sha1(hasher) => hasher.finalize().to_vec(),
136            HashAlgorithm::Sha256(hasher) => hasher.finalize().to_vec(),
137            HashAlgorithm::Blake3(hasher) => hasher.finalize().as_bytes().to_vec(),
138        }
139    }
140    /// Finalize into an [`ObjectHash`] of the hasher's own kind.
141    ///
142    /// The kind is taken from the hasher itself, so this is correct on any
143    /// thread and is the preferred replacement for
144    /// `ObjectHash::from_bytes(&hasher.finalize())` and for the deprecated
145    /// length-inferring `ObjectHash::from_bytes_infer_kind` helper.
146    pub fn finalize_object_hash(self) -> ObjectHash {
147        match self {
148            HashAlgorithm::Sha1(hasher) => ObjectHash::Sha1(hasher.finalize().into()),
149            HashAlgorithm::Sha256(hasher) => ObjectHash::Sha256(hasher.finalize().into()),
150            HashAlgorithm::Blake3(hasher) => ObjectHash::Blake3(*hasher.finalize().as_bytes()),
151        }
152    }
153}
154impl std::io::Write for HashAlgorithm {
155    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
156        self.update(buf);
157        Ok(buf.len())
158    }
159    fn flush(&mut self) -> io::Result<()> {
160        Ok(())
161    }
162}
163impl Default for HashAlgorithm {
164    fn default() -> Self {
165        Self::new()
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use std::io::Cursor;
172
173    use super::*;
174    use crate::hash::set_hash_kind_for_test;
175
176    const HELLO_SHA1: &str = "943a702d06f34599aee1f8da8ef9f7296031d699";
177    const HELLO_SHA256: &str = "315f5bdb76d078c43b8ac0064e4a0164612b1fce77c869345bfc94c75894edd3";
178
179    /// `HashAlgorithm::new_for_kind` produces the requested algorithm regardless of the
180    /// thread-local kind, and `finalize_object_hash` tags the result with that kind.
181    #[test]
182    fn hash_algorithm_for_kind_ignores_thread_local() {
183        let data = b"Hello, world!";
184        for (kind, other, expected) in [
185            (HashKind::Sha1, HashKind::Sha256, HELLO_SHA1),
186            (HashKind::Sha256, HashKind::Sha1, HELLO_SHA256),
187        ] {
188            let _guard = set_hash_kind_for_test(other);
189
190            let mut hasher = HashAlgorithm::new_for_kind(kind);
191            assert_eq!(hasher.kind(), kind);
192            // Stream in two chunks to exercise incremental update.
193            hasher.update(&data[..5]);
194            hasher.update(&data[5..]);
195            let raw = hasher.clone().finalize();
196            assert_eq!(raw.len(), kind.size());
197            assert_eq!(hex::encode(&raw), expected);
198
199            let object_hash = hasher.finalize_object_hash();
200            assert_eq!(object_hash.kind(), kind);
201            assert_eq!(object_hash.to_string(), expected);
202            assert_eq!(object_hash, ObjectHash::new_for_kind(kind, data));
203
204            // `std::io::Write` sink path yields the same digest.
205            let mut sink = HashAlgorithm::new_for_kind(kind);
206            std::io::Write::write_all(&mut sink, data).unwrap();
207            assert_eq!(sink.finalize_object_hash(), object_hash);
208
209            // Explicit stream reader of the digest bytes.
210            let mut cursor = Cursor::new(object_hash.to_data());
211            assert_eq!(read_sha_for_kind(kind, &mut cursor).unwrap(), object_hash);
212        }
213    }
214
215    /// The parameterless constructors follow the thread-local kind (compatibility wrappers).
216    #[test]
217    fn hash_algorithm_for_kind_thread_local_wrappers() {
218        for kind in [HashKind::Sha1, HashKind::Sha256, HashKind::Blake3] {
219            let _guard = set_hash_kind_for_test(kind);
220            assert_eq!(HashAlgorithm::new().kind(), kind);
221            assert_eq!(HashAlgorithm::default().kind(), kind);
222            let digest = ObjectHash::new(b"x");
223            let mut cursor = Cursor::new(digest.to_data());
224            assert_eq!(read_sha(&mut cursor).unwrap(), digest);
225        }
226    }
227}