1use std::{
6 io,
7 io::{BufRead, Read},
8};
9
10use sha1::{Digest, Sha1};
11
12use crate::hash::{HashError, HashKind, ObjectHash, get_hash_kind};
13pub 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
20pub fn read_sha_for_kind(kind: HashKind, file: &mut impl Read) -> Result<ObjectHash, HashError> {
25 ObjectHash::from_stream_for_kind(kind, file)
26}
27
28pub fn read_sha(file: &mut impl Read) -> io::Result<ObjectHash> {
33 ObjectHash::from_stream(file)
34}
35
36pub struct CountingReader<R> {
39 pub inner: R,
40 pub bytes_read: u64,
41}
42
43impl<R> CountingReader<R> {
44 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 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 fn fill_buf(&mut self) -> io::Result<&[u8]> {
68 self.inner.fill_buf()
69 }
70
71 fn consume(&mut self, amt: usize) {
74 self.bytes_read += amt as u64;
75 self.inner.consume(amt);
76 }
77}
78#[derive(Clone)]
88pub enum HashAlgorithm {
89 Sha1(Sha1),
90 Sha256(sha2::Sha256),
91 Blake3(Box<blake3::Hasher>),
94}
95impl HashAlgorithm {
96 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 pub fn new() -> Self {
112 Self::new_for_kind(get_hash_kind())
113 }
114 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 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 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 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 #[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 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 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 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 #[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}