1use gix_error::{Error, Result};
2use std::{fs, io};
3
4use gix_error::{ErrorExt, ResultExt, bail, message};
5use gix_hash::{Hasher, ObjectId};
6use gix_zlib::stream::inflate;
7
8use crate::data::input;
9
10pub struct BytesToEntriesIter<BR> {
14 read: BR,
15 measure: inflate::Measure,
16 offset: u64,
17 had_error: bool,
18 version: crate::data::Version,
19 objects_left: u32,
20 hash: Option<Hasher>,
21 mode: input::Mode,
22 compressed: input::EntryDataMode,
23 compressed_buf: Option<Vec<u8>>,
24 hash_len: usize,
25 object_hash: gix_hash::Kind,
26}
27
28impl<BR> BytesToEntriesIter<BR> {
30 pub fn version(&self) -> crate::data::Version {
32 self.version
33 }
34
35 pub fn mode(&self) -> input::Mode {
37 self.mode
38 }
39}
40
41impl<BR> BytesToEntriesIter<BR>
43where
44 BR: io::BufRead,
45{
46 pub fn new_from_header(
51 mut read: BR,
52 mode: input::Mode,
53 compressed: input::EntryDataMode,
54 object_hash: gix_hash::Kind,
55 ) -> Result<BytesToEntriesIter<BR>> {
56 let mut header_data = [0u8; crate::data::header::SIZE];
57 read.read_exact(&mut header_data).map_err(io_error)?;
58
59 let (version, num_objects) = crate::data::header::decode(&header_data)?;
60 Ok(BytesToEntriesIter {
61 read,
62 measure: inflate::Measure::default(),
63 compressed,
64 offset: crate::data::header::SIZE as u64,
65 had_error: false,
66 version,
67 objects_left: num_objects,
68 hash: (mode != input::Mode::AsIs).then(|| {
69 let mut hash = gix_hash::hasher(object_hash);
70 hash.update(&header_data);
71 hash
72 }),
73 mode,
74 compressed_buf: None,
75 hash_len: object_hash.len_in_bytes(),
76 object_hash,
77 })
78 }
79
80 fn next_inner(&mut self) -> Result<input::Entry> {
81 self.objects_left -= 1; let entry = match self.hash.as_mut() {
85 Some(hash) => {
86 let mut read = read_and_pass_to(
87 &mut self.read,
88 HashWrite {
89 inner: io::sink(),
90 hash,
91 },
92 );
93 crate::data::Entry::from_read(&mut read, self.offset, self.hash_len)
94 }
95 None => crate::data::Entry::from_read(&mut self.read, self.offset, self.hash_len),
96 }
97 .map_err(io_error)?;
98
99 let compressed_buf = self.compressed_buf.take().unwrap_or_else(|| Vec::with_capacity(4096));
101 let mut compressed_reader = read_and_pass_to(
102 &mut self.read,
103 if self.compressed.keep() {
104 Vec::new()
108 } else {
109 compressed_buf
110 },
111 );
112
113 let (bytes_copied, compressed_size) = self.measure.read(&mut compressed_reader).map_err(io_error)?;
114 if bytes_copied != entry.decompressed_size {
115 bail!(gix_error::corruption(format!(
116 "pack is incomplete: it was decompressed into {bytes_copied} bytes but {} bytes where expected.",
117 entry.decompressed_size
118 )));
119 }
120
121 let pack_offset = self.offset;
122 self.offset += entry.header_size() as u64 + compressed_size;
123
124 let mut compressed = compressed_reader.write;
125 debug_assert_eq!(
126 compressed_size,
127 compressed.len() as u64,
128 "we must track exactly the same amount of bytes as read by the decompressor"
129 );
130 if let Some(hash) = self.hash.as_mut() {
131 hash.update(&compressed);
132 }
133
134 let crc32 = if self.compressed.crc32() {
135 let mut header_buf = [0u8; 12 + gix_hash::Kind::longest().len_in_bytes()];
136 let header_len = entry
137 .header
138 .write_to(bytes_copied, &mut header_buf.as_mut())
139 .map_err(io_error)?;
140 let mut crc32 = crc32fast::Hasher::new();
141 crc32.update(&header_buf[..header_len]);
142 crc32.update(&compressed);
143 Some(crc32.finalize())
144 } else {
145 None
146 };
147
148 let compressed = if self.compressed.keep() {
149 Some(compressed)
150 } else {
151 compressed.clear();
152 self.compressed_buf = Some(compressed);
153 None
154 };
155
156 let trailer = self.try_read_trailer()?;
158 Ok(input::Entry {
159 header: entry.header,
160 header_size: entry.header_size() as u16,
161 compressed,
162 compressed_size,
163 crc32,
164 pack_offset,
165 decompressed_size: bytes_copied,
166 trailer,
167 })
168 }
169
170 fn try_read_trailer(&mut self) -> Result<Option<ObjectId>> {
171 Ok(if self.objects_left == 0 {
172 let mut id = gix_hash::ObjectId::null(self.object_hash);
173 if let Err(err) = self.read.read_exact(id.as_mut_slice())
174 && self.mode != input::Mode::Restore
175 {
176 return Err(io_error(err));
177 }
178
179 if let Some(hash) = self.hash.take() {
180 let actual_id = hash.try_finalize().map_err(hash_io_error)?;
181 if self.mode == input::Mode::Restore {
182 id = actual_id;
183 } else {
184 actual_id
185 .verify(&id)
186 .or_raise(|| message("Failed to verify pack checksum in trailer"))?;
187 }
188 }
189 Some(id)
190 } else if self.mode == input::Mode::Restore {
191 let hash = self.hash.clone().expect("in restore mode a hash is set");
192 Some(hash.try_finalize().map_err(hash_io_error)?)
193 } else {
194 None
195 })
196 }
197}
198
199fn read_and_pass_to<R: io::Read, W: io::Write>(read: &mut R, to: W) -> PassThrough<&mut R, W> {
200 PassThrough { read, write: to }
201}
202
203impl<R> Iterator for BytesToEntriesIter<R>
204where
205 R: io::BufRead,
206{
207 type Item = Result<input::Entry>;
208
209 fn next(&mut self) -> Option<Self::Item> {
210 if self.had_error || self.objects_left == 0 {
211 return None;
212 }
213 let result = self.next_inner();
214 self.had_error = result.is_err();
215 if self.had_error {
216 self.objects_left = 0;
217 }
218 if self.mode == input::Mode::Restore && self.had_error {
219 None
220 } else {
221 Some(result)
222 }
223 }
224
225 fn size_hint(&self) -> (usize, Option<usize>) {
226 (self.objects_left as usize, Some(self.objects_left as usize))
227 }
228}
229
230impl<R> std::iter::ExactSizeIterator for BytesToEntriesIter<R> where R: io::BufRead {}
231
232struct PassThrough<R, W> {
233 read: R,
234 write: W,
235}
236
237impl<R, W> io::BufRead for PassThrough<R, W>
238where
239 Self: io::Read,
240 R: io::BufRead,
241 W: io::Write,
242{
243 fn fill_buf(&mut self) -> io::Result<&[u8]> {
244 self.read.fill_buf()
245 }
246
247 fn consume(&mut self, amt: usize) {
248 let buf = self
249 .read
250 .fill_buf()
251 .expect("never fail as we called fill-buf before and this does nothing");
252 self.write
253 .write_all(&buf[..amt])
254 .expect("a write to never fail - should be a memory buffer");
255 self.read.consume(amt);
256 }
257}
258
259impl<R, W> io::Read for PassThrough<R, W>
260where
261 W: io::Write,
262 R: io::Read,
263{
264 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
265 let bytes_read = self.read.read(buf)?;
266 self.write.write_all(&buf[..bytes_read])?;
267 Ok(bytes_read)
268 }
269}
270
271impl<T> crate::data::File<T>
272where
273 T: crate::FileData,
274{
275 pub fn streaming_iter(&self) -> Result<BytesToEntriesIter<impl io::BufRead>> {
277 let reader = io::BufReader::with_capacity(4096 * 8, fs::File::open(&self.path).map_err(io_error)?);
278 BytesToEntriesIter::new_from_header(
279 reader,
280 input::Mode::Verify,
281 input::EntryDataMode::KeepAndCrc32,
282 self.object_hash,
283 )
284 }
285}
286
287fn io_error(err: io::Error) -> Error {
288 err.and_raise(message("An IO operation failed while streaming an entry"))
289}
290
291fn hash_io_error(err: Error) -> Error {
292 err.and_raise(message("An IO operation failed while streaming an entry"))
293}
294
295pub struct HashWrite<'a, T> {
297 pub hash: &'a mut Hasher,
299 pub inner: T,
301}
302
303impl<T> std::io::Write for HashWrite<'_, T>
304where
305 T: std::io::Write,
306{
307 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
308 let written = self.inner.write(buf)?;
309 self.hash.update(&buf[..written]);
310 Ok(written)
311 }
312
313 fn flush(&mut self) -> std::io::Result<()> {
314 self.inner.flush()
315 }
316}