git_index/extension/tree/
write.rs

1use std::convert::TryFrom;
2
3use crate::extension::{tree, Tree};
4
5impl Tree {
6    /// Serialize this instance to `out`.
7    pub fn write_to(&self, mut out: impl std::io::Write) -> Result<(), std::io::Error> {
8        fn tree_entry(out: &mut impl std::io::Write, tree: &Tree) -> Result<(), std::io::Error> {
9            let mut buf = itoa::Buffer::new();
10            let num_entries = match tree.num_entries {
11                Some(num_entries) => buf.format(num_entries),
12                None => buf.format(-1),
13            };
14
15            out.write_all(tree.name.as_slice())?;
16            out.write_all(b"\0")?;
17            out.write_all(num_entries.as_bytes())?;
18            out.write_all(b" ")?;
19            let num_children = buf.format(tree.children.len());
20            out.write_all(num_children.as_bytes())?;
21            out.write_all(b"\n")?;
22            if tree.num_entries.is_some() {
23                out.write_all(tree.id.as_bytes())?;
24            }
25
26            for child in &tree.children {
27                tree_entry(out, child)?;
28            }
29
30            Ok(())
31        }
32
33        let signature = tree::SIGNATURE;
34
35        let estimated_size = self.num_entries.unwrap_or(0) * (300 + 3 + 1 + 3 + 1 + 20);
36        let mut entries: Vec<u8> = Vec::with_capacity(estimated_size as usize);
37        tree_entry(&mut entries, self)?;
38
39        out.write_all(&signature)?;
40        out.write_all(&(u32::try_from(entries.len()).expect("less than 4GB tree extension")).to_be_bytes())?;
41        out.write_all(&entries)?;
42
43        Ok(())
44    }
45}