use std::{io, io::BufRead};
use flate2::{Decompress, FlushDecompress, Status};
use crate::{
errors::GitError,
hash::{HashError, HashKind, get_hash_kind},
internal::object::types::ObjectType,
utils::HashAlgorithm,
};
pub struct ReadBoxed<R> {
pub inner: R,
pub decompressor: Box<Decompress>,
count_hash: bool,
pub hash: HashAlgorithm,
}
impl<R> ReadBoxed<R>
where
R: BufRead,
{
fn with_header(inner: R, mut hash: HashAlgorithm, type_bytes: &[u8], size: usize) -> Self {
hash.update(type_bytes);
hash.update(b" ");
hash.update(size.to_string().as_bytes());
hash.update(b"\0");
ReadBoxed {
inner,
hash,
count_hash: true,
decompressor: Box::new(Decompress::new(true)),
}
}
pub fn new_with_kind(
inner: R,
obj_type: ObjectType,
size: usize,
kind: HashKind,
) -> Result<Self, GitError> {
let type_bytes = obj_type
.to_bytes()
.ok_or(HashError::UnsupportedObjectType {
operation: "ReadBoxed::new_with_kind",
kind,
object_type: obj_type,
expected: kind.size(),
actual: 0,
payload_len: size,
})?;
Ok(Self::with_header(
inner,
HashAlgorithm::new_for_kind(kind),
type_bytes,
size,
))
}
pub fn new(inner: R, obj_type: ObjectType, size: usize) -> Self {
let hash = HashAlgorithm::new();
let type_bytes = obj_type
.to_bytes()
.expect("ReadBoxed::new called with a delta type");
Self::with_header(inner, hash, type_bytes, size)
}
pub fn new_for_delta_with_kind(inner: R, kind: HashKind) -> Self {
ReadBoxed {
inner,
hash: HashAlgorithm::new_for_kind(kind),
count_hash: false,
decompressor: Box::new(Decompress::new(true)),
}
}
pub fn new_for_delta(inner: R) -> Self {
Self::new_for_delta_with_kind(inner, get_hash_kind())
}
pub fn hash_kind(&self) -> HashKind {
self.hash.kind()
}
}
impl<R> io::Read for ReadBoxed<R>
where
R: BufRead,
{
fn read(&mut self, into: &mut [u8]) -> io::Result<usize> {
let o = read(&mut self.inner, &mut self.decompressor, into)?;
if self.count_hash {
self.hash.update(&into[..o]);
}
Ok(o)
}
}
fn read(rd: &mut impl BufRead, state: &mut Decompress, mut dst: &mut [u8]) -> io::Result<usize> {
let mut total_written = 0;
loop {
let (written, consumed, ret, eof);
{
let input = rd.fill_buf()?;
eof = input.is_empty();
let before_out = state.total_out();
let before_in = state.total_in();
let flush = if eof {
FlushDecompress::Finish
} else {
FlushDecompress::None
};
ret = state.decompress(input, dst, flush);
written = (state.total_out() - before_out) as usize;
total_written += written;
dst = &mut dst[written..];
consumed = (state.total_in() - before_in) as usize;
}
rd.consume(consumed);
match ret {
Ok(Status::StreamEnd) => return Ok(total_written),
Ok(Status::Ok | Status::BufError) if eof || dst.is_empty() => return Ok(total_written),
Ok(Status::Ok | Status::BufError) if consumed != 0 || written != 0 => continue,
Ok(Status::Ok | Status::BufError) => unreachable!("Definitely a bug somewhere"),
Err(..) => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"corrupt deflate stream",
));
}
}
}
}
#[cfg(test)]
mod tests {
use std::io::{Read, Write};
use flate2::{Compression, write::ZlibEncoder};
use sha1::{Digest, Sha1};
use super::*;
use crate::hash::{HashKind, ObjectHash, set_hash_kind_for_test};
fn zlib_compress(data: &[u8]) -> Vec<u8> {
let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
enc.write_all(data).unwrap();
enc.finish().unwrap()
}
#[test]
fn inflate_object_counts_hash() {
let _guard = set_hash_kind_for_test(HashKind::Sha1);
let body = b"hello\n";
let compressed = zlib_compress(body);
let cursor = io::Cursor::new(compressed);
let mut reader = ReadBoxed::new(cursor, ObjectType::Blob, body.len());
let mut out = Vec::new();
reader.read_to_end(&mut out).unwrap();
assert_eq!(out, body);
let mut expected = Sha1::new();
expected.update(ObjectType::Blob.to_bytes().unwrap());
expected.update(b" ");
expected.update(body.len().to_string());
expected.update(b"\0");
expected.update(body);
assert_eq!(reader.hash.finalize(), expected.finalize().to_vec());
}
#[test]
fn inflate_delta_skips_hash() {
let _guard = set_hash_kind_for_test(HashKind::Sha1);
let body = b"delta bytes";
let compressed = zlib_compress(body);
let cursor = io::Cursor::new(compressed);
let mut reader = ReadBoxed::new_for_delta(cursor);
let mut out = Vec::new();
reader.read_to_end(&mut out).unwrap();
assert_eq!(out, body);
let empty_hash = Sha1::new().finalize();
assert_eq!(reader.hash.finalize(), empty_hash.to_vec());
}
#[test]
fn corrupt_stream_returns_error() {
let _guard = set_hash_kind_for_test(HashKind::Sha1);
let data = b"not a valid zlib stream";
let mut reader = ReadBoxed::new(io::Cursor::new(data), ObjectType::Blob, data.len());
let mut out = [0u8; 16];
let err = reader.read(&mut out).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
}
#[test]
fn inflate_object_counts_hash_sha256() {
let _guard = set_hash_kind_for_test(HashKind::Sha256);
let body = b"content";
let compressed = zlib_compress(body);
let cursor = io::Cursor::new(compressed);
let mut reader = ReadBoxed::new(cursor, ObjectType::Blob, body.len());
let mut out = Vec::new();
reader.read_to_end(&mut out).unwrap();
assert_eq!(out, body);
let reader_hash = reader.hash.finalize();
let expected = ObjectHash::from_type_and_data(ObjectType::Blob, body);
assert_eq!(reader_hash.len(), 32);
assert_eq!(expected.as_ref().len(), 32);
assert_eq!(reader_hash.as_slice(), expected.as_ref());
}
#[test]
fn inflate_object_new_with_kind_ignores_thread_local() {
for (kind, other) in [
(HashKind::Sha1, HashKind::Sha256),
(HashKind::Sha256, HashKind::Sha1),
] {
let _guard = set_hash_kind_for_test(other);
let body = b"content";
let compressed = zlib_compress(body);
let mut reader = ReadBoxed::new_with_kind(
io::Cursor::new(&compressed),
ObjectType::Blob,
body.len(),
kind,
)
.unwrap();
assert_eq!(reader.hash_kind(), kind);
let mut out = Vec::new();
reader.read_to_end(&mut out).unwrap();
assert_eq!(out, body);
let expected =
ObjectHash::from_type_and_data_for_kind(kind, ObjectType::Blob, body).unwrap();
assert_eq!(reader.hash.finalize_object_hash(), expected);
assert_eq!(
ReadBoxed::new(io::Cursor::new(&compressed), ObjectType::Blob, body.len())
.hash_kind(),
other
);
assert_eq!(
ReadBoxed::new_for_delta(io::Cursor::new(&compressed)).hash_kind(),
other
);
assert_eq!(
ReadBoxed::new_for_delta_with_kind(io::Cursor::new(&compressed), kind).hash_kind(),
kind
);
}
}
#[test]
fn blake3_hash_kind() {
let _guard = set_hash_kind_for_test(HashKind::Sha1);
let body: Vec<u8> = (0..5000u32).map(|i| (i % 251) as u8).collect();
let compressed = zlib_compress(&body);
let mut reader = ReadBoxed::new_with_kind(
io::Cursor::new(&compressed),
ObjectType::Blob,
body.len(),
HashKind::Blake3,
)
.unwrap();
assert_eq!(reader.hash_kind(), HashKind::Blake3);
let mut out = Vec::new();
let mut chunk = [0u8; 97];
loop {
let n = reader.read(&mut chunk).unwrap();
if n == 0 {
break;
}
out.extend_from_slice(&chunk[..n]);
}
assert_eq!(out, body);
let id = reader.hash.finalize_object_hash();
assert_eq!(id.kind(), HashKind::Blake3);
assert_eq!(
id,
ObjectHash::from_type_and_data_for_kind(HashKind::Blake3, ObjectType::Blob, &body)
.unwrap()
);
assert_ne!(
id.as_ref(),
ObjectHash::from_type_and_data_for_kind(HashKind::Sha256, ObjectType::Blob, &body)
.unwrap()
.as_ref()
);
assert_eq!(
ReadBoxed::new_for_delta_with_kind(io::Cursor::new(&compressed), HashKind::Blake3)
.hash_kind(),
HashKind::Blake3
);
}
}