git_internal/internal/zlib/stream/
inflate.rs1use 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
15pub struct ReadBoxed<R> {
21 pub inner: R,
23 pub decompressor: Box<Decompress>,
25 count_hash: bool,
27 pub hash: HashAlgorithm,
30}
31impl<R> ReadBoxed<R>
32where
33 R: BufRead,
34{
35 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 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 pub fn new(inner: R, obj_type: ObjectType, size: usize) -> Self {
88 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 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 pub fn new_for_delta(inner: R) -> Self {
113 Self::new_for_delta_with_kind(inner, get_hash_kind())
114 }
115
116 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 if self.count_hash {
129 self.hash.update(&into[..o]);
130 }
131 Ok(o)
132 }
133}
134
135fn 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 Ok(Status::StreamEnd) => return Ok(total_written),
161 Ok(Status::Ok | Status::BufError) if eof || dst.is_empty() => return Ok(total_written),
163 Ok(Status::Ok | Status::BufError) if consumed != 0 || written != 0 => continue,
165 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 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 #[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 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 #[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 let empty_hash = Sha1::new().finalize();
232 assert_eq!(reader.hash.finalize(), empty_hash.to_vec());
233 }
234
235 #[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 #[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 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 #[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 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 #[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 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}