Skip to main content

gix_pack/data/input/
entries_to_bytes.rs

1use std::iter::Peekable;
2
3use crate::data::input;
4
5/// An implementation of [`Iterator`] to write [encoded entries][input::Entry] to an inner implementation each time
6/// `next()` is called.
7///
8/// It is able to deal with an unknown amount of objects as it will rewrite the pack header once the entries iterator
9/// is depleted and compute the hash in one go by re-reading the whole file.
10pub struct EntriesToBytesIter<I: Iterator, W> {
11    /// An iterator for input [`input::Entry`] instances
12    pub input: Peekable<I>,
13    /// A way of writing encoded bytes.
14    output: W,
15    /// Our trailing hash when done writing all input entries
16    trailer: Option<gix_hash::ObjectId>,
17    /// The amount of objects in the iteration and the version of the packfile to be written.
18    /// Will be `None` to signal the header was written already.
19    data_version: crate::data::Version,
20    /// The amount of entries seen so far
21    num_entries: u32,
22    /// If we are done, no additional writes will occur
23    is_done: bool,
24    /// The kind of hash to use for the digest
25    object_hash: gix_hash::Kind,
26}
27
28impl<I, W> EntriesToBytesIter<I, W>
29where
30    I: Iterator<Item = Result<input::Entry, input::Error>>,
31    W: std::io::Read + std::io::Write + std::io::Seek,
32{
33    /// Create a new instance reading [entries][input::Entry] from an `input` iterator and write pack data bytes to
34    /// `output` writer, resembling a pack of `version`. The amount of entries will be dynamically determined and
35    /// the pack is completed once the last entry was written.
36    /// `object_hash` is the kind of hash to use for the pack checksum and maybe other places, depending on the version.
37    ///
38    /// # Panics
39    ///
40    /// Only [Version::V2](crate::data::Version::V2) is allowed for `version.
41    pub fn new(input: I, output: W, version: crate::data::Version, object_hash: gix_hash::Kind) -> Self {
42        assert!(
43            matches!(version, crate::data::Version::V2),
44            "currently only pack version 2 can be written",
45        );
46        EntriesToBytesIter {
47            input: input.peekable(),
48            output,
49            object_hash,
50            num_entries: 0,
51            trailer: None,
52            data_version: version,
53            is_done: false,
54        }
55    }
56
57    /// Returns the trailing hash over all ~ entries once done.
58    /// It's `None` if we are not yet done writing.
59    pub fn digest(&self) -> Option<gix_hash::ObjectId> {
60        self.trailer
61    }
62
63    fn next_inner(&mut self, entry: input::Entry) -> Result<input::Entry, gix_hash::io::Error> {
64        if self.num_entries == 0 {
65            let header_bytes = crate::data::header::encode(self.data_version, 0);
66            self.output.write_all(&header_bytes[..])?;
67        }
68        self.num_entries += 1;
69        entry.header.write_to(entry.decompressed_size, &mut self.output)?;
70        self.output.write_all(
71            entry
72                .compressed
73                .as_deref()
74                .expect("caller must configure generator to keep compressed bytes"),
75        )?;
76        Ok(entry)
77    }
78
79    fn write_header_and_digest(&mut self, last_entry: Option<&mut input::Entry>) -> Result<(), gix_hash::io::Error> {
80        let header_bytes = crate::data::header::encode(self.data_version, self.num_entries);
81        let num_bytes_written = if last_entry.is_some() {
82            self.output.stream_position()?
83        } else {
84            header_bytes.len() as u64
85        };
86        self.output.rewind()?;
87        self.output.write_all(&header_bytes[..])?;
88        self.output.flush()?;
89
90        self.output.rewind()?;
91        let interrupt_never = std::sync::atomic::AtomicBool::new(false);
92        let digest = gix_hash::bytes(
93            &mut self.output,
94            num_bytes_written,
95            self.object_hash,
96            &mut gix_features::progress::Discard,
97            &interrupt_never,
98        )?;
99        self.output.write_all(digest.as_slice())?;
100        self.output.flush()?;
101
102        self.is_done = true;
103        if let Some(last_entry) = last_entry {
104            last_entry.trailer = Some(digest);
105        }
106        self.trailer = Some(digest);
107        Ok(())
108    }
109}
110
111impl<I, W> Iterator for EntriesToBytesIter<I, W>
112where
113    I: Iterator<Item = Result<input::Entry, input::Error>>,
114    W: std::io::Read + std::io::Write + std::io::Seek,
115{
116    /// The amount of bytes written to `out` if `Ok` or the error `E` received from the input.
117    type Item = Result<input::Entry, input::Error>;
118
119    fn next(&mut self) -> Option<Self::Item> {
120        if self.is_done {
121            return None;
122        }
123
124        match self.input.next() {
125            Some(res) => Some(match res {
126                Ok(entry) => self
127                    .next_inner(entry)
128                    .and_then(|mut entry| {
129                        if self.input.peek().is_none() {
130                            self.write_header_and_digest(Some(&mut entry)).map(|_| entry)
131                        } else {
132                            Ok(entry)
133                        }
134                    })
135                    .map_err(input::Error::from),
136                Err(err) => {
137                    self.is_done = true;
138                    Err(err)
139                }
140            }),
141            None => match self.write_header_and_digest(None) {
142                Ok(_) => None,
143                Err(err) => Some(Err(err.into())),
144            },
145        }
146    }
147
148    fn size_hint(&self) -> (usize, Option<usize>) {
149        self.input.size_hint()
150    }
151}