Skip to main content

git_internal/internal/pack/
wrapper.rs

1//! Reader wrapper that tracks how many bytes of a pack have been consumed while keeping a running
2//! hash (SHA-1, SHA-256 or BLAKE3-256, per the repository `HashKind`) for trailer verification.
3
4use std::io::{self, BufRead, Read};
5
6use crate::{
7    hash::{HashKind, ObjectHash, get_hash_kind},
8    utils::HashAlgorithm,
9};
10/// [`Wrapper`] is a wrapper around a reader that also computes the running hash (of the
11/// repository [`HashKind`]) of the data read.
12///
13/// It is designed to work with any reader that implements `BufRead`.
14///
15/// Fields:
16/// * `inner`: The inner reader.
17/// * `hash`: The optional hash state. `None` means only bytes read are counted.
18/// * `bytes_read`: The number of bytes consumed from the wrapped reader.
19///
20pub struct Wrapper<R> {
21    inner: R,
22    hash: Option<HashAlgorithm>,
23    bytes_read: usize,
24}
25
26impl<R> Wrapper<R>
27where
28    R: BufRead,
29{
30    /// Constructs a new [`Wrapper`] with hash tracking enabled for an explicit
31    /// repository `kind`.
32    ///
33    /// Does not consult the thread-local [`HashKind`]; use this on worker
34    /// threads and async tasks that may serve another repository.
35    pub fn new_with_kind(inner: R, kind: HashKind) -> Self {
36        Self {
37            inner,
38            hash: Some(HashAlgorithm::new_for_kind(kind)),
39            bytes_read: 0,
40        }
41    }
42
43    /// Constructs a new [`Wrapper`] with hash tracking enabled.
44    ///
45    /// Compatibility wrapper around [`Wrapper::new_with_kind`] using the
46    /// thread-local [`HashKind`].
47    ///
48    /// # Parameters
49    /// * `inner`: The reader to wrap.
50    pub fn new(inner: R) -> Self {
51        Self::new_with_kind(inner, get_hash_kind())
52    }
53
54    /// The [`HashKind`] of the running hash, or `None` when hash tracking is disabled.
55    pub fn hash_kind(&self) -> Option<HashKind> {
56        self.hash.as_ref().map(HashAlgorithm::kind)
57    }
58
59    /// Constructs a wrapper that only tracks bytes read, skipping the running hash.
60    pub fn new_without_hash(inner: R) -> Self {
61        Self {
62            inner,
63            hash: None,
64            bytes_read: 0,
65        }
66    }
67
68    /// Returns the number of bytes read so far.
69    pub fn bytes_read(&self) -> usize {
70        self.bytes_read
71    }
72
73    /// Returns the final hash of the data read so far, as an [`ObjectHash`] of the
74    /// wrapper's hash kind.
75    ///
76    /// This is a clone of the internal hash state finalized into an [`ObjectHash`].
77    pub fn final_hash(&self) -> ObjectHash {
78        self.hash
79            .clone()
80            .expect("Wrapper::final_hash called while hash tracking is disabled")
81            .finalize_object_hash()
82    }
83}
84
85impl<R> BufRead for Wrapper<R>
86where
87    R: BufRead,
88{
89    /// Provides access to the internal buffer of the wrapped reader without consuming it.
90    fn fill_buf(&mut self) -> io::Result<&[u8]> {
91        self.inner.fill_buf() // Delegate to the inner reader
92    }
93
94    /// Consumes data from the buffer and updates the hash when tracking is enabled.
95    ///
96    /// # Parameters
97    /// * `amt`: The amount of data to consume from the buffer.
98    fn consume(&mut self, amt: usize) {
99        let buffer = self.inner.fill_buf().expect("Failed to fill buffer");
100        if let Some(hash) = &mut self.hash {
101            hash.update(&buffer[..amt]); // Update the running hash with the data being consumed
102        }
103        self.inner.consume(amt); // Consume the data from the inner reader
104        self.bytes_read += amt;
105    }
106}
107
108impl<R> Read for Wrapper<R>
109where
110    R: BufRead,
111{
112    /// Reads data into the provided buffer and updates the hash when tracking is enabled.
113    /// <br> [Read::read_exact] calls it internally.
114    ///
115    /// # Parameters
116    /// * `buf`: The buffer to read data into.
117    ///
118    /// # Returns
119    /// Returns the number of bytes read.
120    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
121        let o = self.inner.read(buf)?; // Read data into the buffer
122        if let Some(hash) = &mut self.hash {
123            hash.update(&buf[..o]); // Update the running hash with the data being read
124        }
125        self.bytes_read += o;
126        Ok(o) // Return the number of bytes read
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use std::io::{self, BufRead, BufReader, Cursor, Read};
133
134    use crate::{
135        hash::{HashKind, ObjectHash, set_hash_kind_for_test},
136        internal::pack::wrapper::Wrapper,
137    };
138
139    /// Helper function to test wrapper read functionality for different hash kinds.
140    fn wrapper_read(kind: HashKind) {
141        let _guard = set_hash_kind_for_test(kind);
142        let data = b"Hello, world!"; // Sample data
143        let cursor = Cursor::new(data.as_ref());
144        let buf_reader = BufReader::new(cursor);
145        let mut wrapper = Wrapper::new(buf_reader);
146
147        let mut buffer = vec![0; data.len()];
148        wrapper.read_exact(&mut buffer).unwrap();
149
150        assert_eq!(buffer, data);
151    }
152
153    /// Verify Wrapper correctly reads data for both SHA-1 and SHA-256 hash modes.
154    #[test]
155    fn test_wrapper_read() {
156        wrapper_read(HashKind::Sha1);
157        wrapper_read(HashKind::Sha256);
158    }
159
160    /// Helper function to test wrapper hash functionality for different hash kinds.
161    fn wrapper_hash_with_kind(kind: HashKind) -> io::Result<()> {
162        let _guard = set_hash_kind_for_test(kind);
163        let data = b"Hello, world!";
164        let cursor = Cursor::new(data.as_ref());
165        let buf_reader = BufReader::new(cursor);
166        let mut wrapper = Wrapper::new(buf_reader);
167
168        let mut buffer = vec![0; data.len()];
169        wrapper.read_exact(&mut buffer)?;
170
171        let hash_result = wrapper.final_hash();
172        // Explicit-kind digest of the same bytes; no exhaustive `HashKind` match here so a
173        // future variant does not break this fixture.
174        let expected_hash = ObjectHash::new_for_kind(kind, data);
175
176        assert_eq!(hash_result, expected_hash);
177        assert_eq!(wrapper.hash_kind(), Some(kind));
178        Ok(())
179    }
180
181    /// `new_with_kind` hashes for the explicit kind regardless of the thread-local kind,
182    /// through both `read` and `consume` paths.
183    #[test]
184    fn test_wrapper_new_with_kind_ignores_thread_local() -> io::Result<()> {
185        for (kind, other) in [
186            (HashKind::Sha1, HashKind::Sha256),
187            (HashKind::Sha256, HashKind::Sha1),
188        ] {
189            let _guard = set_hash_kind_for_test(other);
190            let data = b"Hello, world!";
191            let expected = ObjectHash::new_for_kind(kind, data);
192
193            let mut wrapper =
194                Wrapper::new_with_kind(BufReader::new(Cursor::new(data.as_ref())), kind);
195            let mut buffer = vec![0; data.len()];
196            wrapper.read_exact(&mut buffer)?;
197            assert_eq!(wrapper.hash_kind(), Some(kind));
198            assert_eq!(wrapper.final_hash(), expected);
199            assert_eq!(wrapper.bytes_read(), data.len());
200
201            let mut wrapper =
202                Wrapper::new_with_kind(BufReader::new(Cursor::new(data.as_ref())), kind);
203            let n = wrapper.fill_buf()?.len();
204            wrapper.consume(n);
205            assert_eq!(wrapper.final_hash(), expected);
206
207            assert_eq!(
208                Wrapper::new(BufReader::new(Cursor::new(data.as_ref()))).hash_kind(),
209                Some(other)
210            );
211            assert_eq!(
212                Wrapper::new_without_hash(BufReader::new(Cursor::new(data.as_ref()))).hash_kind(),
213                None
214            );
215        }
216        Ok(())
217    }
218    #[test]
219    fn test_wrapper_hash() -> io::Result<()> {
220        wrapper_hash_with_kind(HashKind::Sha1)?;
221        wrapper_hash_with_kind(HashKind::Sha256)?;
222        Ok(())
223    }
224}