use std::{
io,
io::{BufRead, Read},
};
use sha1::{Digest, Sha1};
use crate::hash::{HashError, HashKind, ObjectHash, get_hash_kind};
pub fn read_bytes(file: &mut impl Read, len: usize) -> io::Result<Vec<u8>> {
let mut buf = vec![0; len];
file.read_exact(&mut buf)?;
Ok(buf)
}
pub fn read_sha_for_kind(kind: HashKind, file: &mut impl Read) -> Result<ObjectHash, HashError> {
ObjectHash::from_stream_for_kind(kind, file)
}
pub fn read_sha(file: &mut impl Read) -> io::Result<ObjectHash> {
ObjectHash::from_stream(file)
}
pub struct CountingReader<R> {
pub inner: R,
pub bytes_read: u64,
}
impl<R> CountingReader<R> {
pub fn new(inner: R) -> Self {
Self {
inner,
bytes_read: 0,
}
}
}
impl<R: Read> Read for CountingReader<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let n = self.inner.read(buf)?;
self.bytes_read += n as u64;
Ok(n)
}
}
impl<R: BufRead> BufRead for CountingReader<R> {
fn fill_buf(&mut self) -> io::Result<&[u8]> {
self.inner.fill_buf()
}
fn consume(&mut self, amt: usize) {
self.bytes_read += amt as u64;
self.inner.consume(amt);
}
}
#[derive(Clone)]
pub enum HashAlgorithm {
Sha1(Sha1),
Sha256(sha2::Sha256),
Blake3(Box<blake3::Hasher>),
}
impl HashAlgorithm {
pub fn new_for_kind(kind: HashKind) -> Self {
match kind {
HashKind::Sha1 => HashAlgorithm::Sha1(Sha1::new()),
HashKind::Sha256 => HashAlgorithm::Sha256(sha2::Sha256::new()),
HashKind::Blake3 => HashAlgorithm::Blake3(Box::new(blake3::Hasher::new())),
}
}
pub fn new() -> Self {
Self::new_for_kind(get_hash_kind())
}
pub fn kind(&self) -> HashKind {
match self {
HashAlgorithm::Sha1(_) => HashKind::Sha1,
HashAlgorithm::Sha256(_) => HashKind::Sha256,
HashAlgorithm::Blake3(_) => HashKind::Blake3,
}
}
pub fn update(&mut self, data: &[u8]) {
match self {
HashAlgorithm::Sha1(hasher) => hasher.update(data),
HashAlgorithm::Sha256(hasher) => hasher.update(data),
HashAlgorithm::Blake3(hasher) => {
hasher.update(data);
}
}
}
pub fn finalize(self) -> Vec<u8> {
match self {
HashAlgorithm::Sha1(hasher) => hasher.finalize().to_vec(),
HashAlgorithm::Sha256(hasher) => hasher.finalize().to_vec(),
HashAlgorithm::Blake3(hasher) => hasher.finalize().as_bytes().to_vec(),
}
}
pub fn finalize_object_hash(self) -> ObjectHash {
match self {
HashAlgorithm::Sha1(hasher) => ObjectHash::Sha1(hasher.finalize().into()),
HashAlgorithm::Sha256(hasher) => ObjectHash::Sha256(hasher.finalize().into()),
HashAlgorithm::Blake3(hasher) => ObjectHash::Blake3(*hasher.finalize().as_bytes()),
}
}
}
impl std::io::Write for HashAlgorithm {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.update(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl Default for HashAlgorithm {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use std::io::Cursor;
use super::*;
use crate::hash::set_hash_kind_for_test;
const HELLO_SHA1: &str = "943a702d06f34599aee1f8da8ef9f7296031d699";
const HELLO_SHA256: &str = "315f5bdb76d078c43b8ac0064e4a0164612b1fce77c869345bfc94c75894edd3";
#[test]
fn hash_algorithm_for_kind_ignores_thread_local() {
let data = b"Hello, world!";
for (kind, other, expected) in [
(HashKind::Sha1, HashKind::Sha256, HELLO_SHA1),
(HashKind::Sha256, HashKind::Sha1, HELLO_SHA256),
] {
let _guard = set_hash_kind_for_test(other);
let mut hasher = HashAlgorithm::new_for_kind(kind);
assert_eq!(hasher.kind(), kind);
hasher.update(&data[..5]);
hasher.update(&data[5..]);
let raw = hasher.clone().finalize();
assert_eq!(raw.len(), kind.size());
assert_eq!(hex::encode(&raw), expected);
let object_hash = hasher.finalize_object_hash();
assert_eq!(object_hash.kind(), kind);
assert_eq!(object_hash.to_string(), expected);
assert_eq!(object_hash, ObjectHash::new_for_kind(kind, data));
let mut sink = HashAlgorithm::new_for_kind(kind);
std::io::Write::write_all(&mut sink, data).unwrap();
assert_eq!(sink.finalize_object_hash(), object_hash);
let mut cursor = Cursor::new(object_hash.to_data());
assert_eq!(read_sha_for_kind(kind, &mut cursor).unwrap(), object_hash);
}
}
#[test]
fn hash_algorithm_for_kind_thread_local_wrappers() {
for kind in [HashKind::Sha1, HashKind::Sha256, HashKind::Blake3] {
let _guard = set_hash_kind_for_test(kind);
assert_eq!(HashAlgorithm::new().kind(), kind);
assert_eq!(HashAlgorithm::default().kind(), kind);
let digest = ObjectHash::new(b"x");
let mut cursor = Cursor::new(digest.to_data());
assert_eq!(read_sha(&mut cursor).unwrap(), digest);
}
}
}