Skip to main content

git_internal/internal/zlib/stream/
inflate.rs

1//! Buffered inflate reader that decodes Git's zlib-compressed objects while simultaneously tracking
2//! SHA digests for integrity verification.
3
4use std::{io, io::BufRead};
5
6use flate2::{Decompress, FlushDecompress, Status};
7
8use crate::{
9    errors::GitError,
10    hash::{HashError, HashKind, get_hash_kind},
11    internal::object::types::ObjectType,
12    utils::HashAlgorithm,
13};
14
15/// ReadBoxed is to unzip information from a  DEFLATE stream,
16/// which hash [`BufRead`] trait.
17/// For a continuous stream of DEFLATE information, the structure
18/// does not read too many bytes to affect subsequent information
19/// reads
20pub struct ReadBoxed<R> {
21    /// The reader from which bytes should be decompressed.
22    pub inner: R,
23    /// The decompressor doing all the work.
24    pub decompressor: Box<Decompress>,
25    /// the [`count_hash`] decide whether to calculate the hash value in the [`read`] method
26    count_hash: bool,
27    /// The current hash state for the decompressed data.
28    /// It is updated as data is read from the stream.
29    pub hash: HashAlgorithm,
30}
31impl<R> ReadBoxed<R>
32where
33    R: BufRead,
34{
35    /// Seed `hash` with the loose-object header `<type> <size>\0` and build the reader.
36    fn with_header(inner: R, mut hash: HashAlgorithm, type_bytes: &[u8], size: usize) -> Self {
37        hash.update(type_bytes);
38        hash.update(b" ");
39        hash.update(size.to_string().as_bytes());
40        hash.update(b"\0");
41        ReadBoxed {
42            inner,
43            hash,
44            count_hash: true,
45            decompressor: Box::new(Decompress::new(true)),
46        }
47    }
48
49    /// New a ReadBoxed for a common (non-delta) object whose ID must be computed
50    /// with an explicit repository `kind`.
51    ///
52    /// Does not consult the thread-local [`HashKind`]. Delta object types have no
53    /// loose-object header and are rejected with
54    /// [`HashError::UnsupportedObjectType`] (carrying the operation, `kind`,
55    /// the expected digest width and the offered payload size) wrapped in
56    /// [`GitError::InvalidHashValue`].
57    pub fn new_with_kind(
58        inner: R,
59        obj_type: ObjectType,
60        size: usize,
61        kind: HashKind,
62    ) -> Result<Self, GitError> {
63        let type_bytes = obj_type
64            .to_bytes()
65            .ok_or(HashError::UnsupportedObjectType {
66                operation: "ReadBoxed::new_with_kind",
67                kind,
68                object_type: obj_type,
69                expected: kind.size(),
70                actual: 0,
71                payload_len: size,
72            })?;
73        Ok(Self::with_header(
74            inner,
75            HashAlgorithm::new_for_kind(kind),
76            type_bytes,
77            size,
78        ))
79    }
80
81    /// New a ReadBoxed for zlib read, the Output ReadBoxed is for the Common Object,
82    /// but not for the Delta Object,if that ,see new_for_delta method below.
83    ///
84    /// Legacy entry point using the thread-local [`HashKind`]; keeps its
85    /// pre-existing panicking contract for delta types. Prefer
86    /// [`ReadBoxed::new_with_kind`].
87    pub fn new(inner: R, obj_type: ObjectType, size: usize) -> Self {
88        // Initialize the hash with the object header.
89        let hash = HashAlgorithm::new();
90        let type_bytes = obj_type
91            .to_bytes()
92            .expect("ReadBoxed::new called with a delta type");
93        Self::with_header(inner, hash, type_bytes, size)
94    }
95
96    /// New a ReadBoxed for a delta object with an explicit repository `kind`.
97    /// Delta payloads are not hashed, so the hasher is only carried for API symmetry.
98    pub fn new_for_delta_with_kind(inner: R, kind: HashKind) -> Self {
99        ReadBoxed {
100            inner,
101            hash: HashAlgorithm::new_for_kind(kind),
102            count_hash: false,
103            decompressor: Box::new(Decompress::new(true)),
104        }
105    }
106
107    /// New a ReadBoxed for zlib read, the Output ReadBoxed is for the Delta Object,
108    /// which does not need to calculate the hash value.
109    ///
110    /// Compatibility wrapper around [`ReadBoxed::new_for_delta_with_kind`] using
111    /// the thread-local [`HashKind`].
112    pub fn new_for_delta(inner: R) -> Self {
113        Self::new_for_delta_with_kind(inner, get_hash_kind())
114    }
115
116    /// The [`HashKind`] this reader's hasher produces.
117    pub fn hash_kind(&self) -> HashKind {
118        self.hash.kind()
119    }
120}
121impl<R> io::Read for ReadBoxed<R>
122where
123    R: BufRead,
124{
125    fn read(&mut self, into: &mut [u8]) -> io::Result<usize> {
126        let o = read(&mut self.inner, &mut self.decompressor, into)?;
127        //update the hash value
128        if self.count_hash {
129            self.hash.update(&into[..o]);
130        }
131        Ok(o)
132    }
133}
134
135/// Read bytes from `rd` and decompress them using `state` into a pre-allocated fitting buffer `dst`, returning the amount of bytes written.
136fn read(rd: &mut impl BufRead, state: &mut Decompress, mut dst: &mut [u8]) -> io::Result<usize> {
137    let mut total_written = 0;
138    loop {
139        let (written, consumed, ret, eof);
140        {
141            let input = rd.fill_buf()?;
142            eof = input.is_empty();
143            let before_out = state.total_out();
144            let before_in = state.total_in();
145            let flush = if eof {
146                FlushDecompress::Finish
147            } else {
148                FlushDecompress::None
149            };
150            ret = state.decompress(input, dst, flush);
151            written = (state.total_out() - before_out) as usize;
152            total_written += written;
153            dst = &mut dst[written..];
154            consumed = (state.total_in() - before_in) as usize;
155        }
156        rd.consume(consumed);
157
158        match ret {
159            // The stream has officially ended, nothing more to do here.
160            Ok(Status::StreamEnd) => return Ok(total_written),
161            // Either input our output are depleted even though the stream is not depleted yet.
162            Ok(Status::Ok | Status::BufError) if eof || dst.is_empty() => return Ok(total_written),
163            // Some progress was made in both the input and the output, it must continue to reach the end.
164            Ok(Status::Ok | Status::BufError) if consumed != 0 || written != 0 => continue,
165            // A strange state, where zlib makes no progress but isn't done either. Call it out.
166            Ok(Status::Ok | Status::BufError) => unreachable!("Definitely a bug somewhere"),
167            Err(..) => {
168                return Err(io::Error::new(
169                    io::ErrorKind::InvalidInput,
170                    "corrupt deflate stream",
171                ));
172            }
173        }
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    use std::io::{Read, Write};
180
181    use flate2::{Compression, write::ZlibEncoder};
182    use sha1::{Digest, Sha1};
183
184    use super::*;
185    use crate::hash::{HashKind, ObjectHash, set_hash_kind_for_test};
186
187    /// Helper to build zlib-compressed bytes from input data.
188    fn zlib_compress(data: &[u8]) -> Vec<u8> {
189        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
190        enc.write_all(data).unwrap();
191        enc.finish().unwrap()
192    }
193
194    /// ReadBoxed::new should inflate data and accumulate SHA-1 over the object header + body.
195    #[test]
196    fn inflate_object_counts_hash() {
197        let _guard = set_hash_kind_for_test(HashKind::Sha1);
198        let body = b"hello\n";
199        let compressed = zlib_compress(body);
200        let cursor = io::Cursor::new(compressed);
201
202        let mut reader = ReadBoxed::new(cursor, ObjectType::Blob, body.len());
203        let mut out = Vec::new();
204        reader.read_to_end(&mut out).unwrap();
205        assert_eq!(out, body);
206
207        // Expected hash: header "blob <len>\\0" + body
208        let mut expected = Sha1::new();
209        expected.update(ObjectType::Blob.to_bytes().unwrap());
210        expected.update(b" ");
211        expected.update(body.len().to_string());
212        expected.update(b"\0");
213        expected.update(body);
214        assert_eq!(reader.hash.finalize(), expected.finalize().to_vec());
215    }
216
217    /// ReadBoxed::new_for_delta should inflate data without touching the hash accumulator.
218    #[test]
219    fn inflate_delta_skips_hash() {
220        let _guard = set_hash_kind_for_test(HashKind::Sha1);
221        let body = b"delta bytes";
222        let compressed = zlib_compress(body);
223        let cursor = io::Cursor::new(compressed);
224
225        let mut reader = ReadBoxed::new_for_delta(cursor);
226        let mut out = Vec::new();
227        reader.read_to_end(&mut out).unwrap();
228        assert_eq!(out, body);
229
230        // Hash should remain the initial zero-state (Sha1 of empty string)
231        let empty_hash = Sha1::new().finalize();
232        assert_eq!(reader.hash.finalize(), empty_hash.to_vec());
233    }
234
235    /// Corrupt deflate stream should surface as InvalidInput.
236    #[test]
237    fn corrupt_stream_returns_error() {
238        let _guard = set_hash_kind_for_test(HashKind::Sha1);
239        let data = b"not a valid zlib stream";
240        let mut reader = ReadBoxed::new(io::Cursor::new(data), ObjectType::Blob, data.len());
241        let mut out = [0u8; 16];
242        let err = reader.read(&mut out).unwrap_err();
243        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
244    }
245
246    /// With SHA-256 configured, hash accumulation should match SHA-256 object ID.
247    #[test]
248    fn inflate_object_counts_hash_sha256() {
249        let _guard = set_hash_kind_for_test(HashKind::Sha256);
250        let body = b"content";
251        let compressed = zlib_compress(body);
252        let cursor = io::Cursor::new(compressed);
253
254        let mut reader = ReadBoxed::new(cursor, ObjectType::Blob, body.len());
255        let mut out = Vec::new();
256        reader.read_to_end(&mut out).unwrap();
257        assert_eq!(out, body);
258
259        // Reader uses repository hash kind (SHA-256) internally.
260        let reader_hash = reader.hash.finalize();
261        let expected = ObjectHash::from_type_and_data(ObjectType::Blob, body);
262
263        assert_eq!(reader_hash.len(), 32);
264        assert_eq!(expected.as_ref().len(), 32);
265        assert_eq!(reader_hash.as_slice(), expected.as_ref());
266    }
267
268    /// `new_with_kind` hashes with the explicit kind regardless of the thread-local kind.
269    #[test]
270    fn inflate_object_new_with_kind_ignores_thread_local() {
271        for (kind, other) in [
272            (HashKind::Sha1, HashKind::Sha256),
273            (HashKind::Sha256, HashKind::Sha1),
274        ] {
275            let _guard = set_hash_kind_for_test(other);
276            let body = b"content";
277            let compressed = zlib_compress(body);
278
279            let mut reader = ReadBoxed::new_with_kind(
280                io::Cursor::new(&compressed),
281                ObjectType::Blob,
282                body.len(),
283                kind,
284            )
285            .unwrap();
286            assert_eq!(reader.hash_kind(), kind);
287            let mut out = Vec::new();
288            reader.read_to_end(&mut out).unwrap();
289            assert_eq!(out, body);
290
291            let expected =
292                ObjectHash::from_type_and_data_for_kind(kind, ObjectType::Blob, body).unwrap();
293            assert_eq!(reader.hash.finalize_object_hash(), expected);
294
295            // Legacy constructors follow the thread-local kind.
296            assert_eq!(
297                ReadBoxed::new(io::Cursor::new(&compressed), ObjectType::Blob, body.len())
298                    .hash_kind(),
299                other
300            );
301            assert_eq!(
302                ReadBoxed::new_for_delta(io::Cursor::new(&compressed)).hash_kind(),
303                other
304            );
305            assert_eq!(
306                ReadBoxed::new_for_delta_with_kind(io::Cursor::new(&compressed), kind).hash_kind(),
307                kind
308            );
309        }
310    }
311
312    /// A BLAKE3 `ReadBoxed` streams the inflated object through a BLAKE3 hasher (no second
313    /// pass over the payload) and yields the canonical BLAKE3 object ID, distinct from the
314    /// same-width SHA-256 ID, while the thread-local kind is SHA-1.
315    #[test]
316    fn blake3_hash_kind() {
317        let _guard = set_hash_kind_for_test(HashKind::Sha1);
318        let body: Vec<u8> = (0..5000u32).map(|i| (i % 251) as u8).collect();
319        let compressed = zlib_compress(&body);
320
321        let mut reader = ReadBoxed::new_with_kind(
322            io::Cursor::new(&compressed),
323            ObjectType::Blob,
324            body.len(),
325            HashKind::Blake3,
326        )
327        .unwrap();
328        assert_eq!(reader.hash_kind(), HashKind::Blake3);
329        let mut out = Vec::new();
330        // Read in small chunks so the hash is accumulated incrementally, as in pack decode.
331        let mut chunk = [0u8; 97];
332        loop {
333            let n = reader.read(&mut chunk).unwrap();
334            if n == 0 {
335                break;
336            }
337            out.extend_from_slice(&chunk[..n]);
338        }
339        assert_eq!(out, body);
340        let id = reader.hash.finalize_object_hash();
341        assert_eq!(id.kind(), HashKind::Blake3);
342        assert_eq!(
343            id,
344            ObjectHash::from_type_and_data_for_kind(HashKind::Blake3, ObjectType::Blob, &body)
345                .unwrap()
346        );
347        assert_ne!(
348            id.as_ref(),
349            ObjectHash::from_type_and_data_for_kind(HashKind::Sha256, ObjectType::Blob, &body)
350                .unwrap()
351                .as_ref()
352        );
353        assert_eq!(
354            ReadBoxed::new_for_delta_with_kind(io::Cursor::new(&compressed), HashKind::Blake3)
355                .hash_kind(),
356            HashKind::Blake3
357        );
358    }
359}