use std::collections::HashSet; use std::fs; use std::path::Path; use crate::error::Result; use crate::object::id::Id; use crate::object::RawObject; use crate::store::layout; use crate::store::pack; #[derive(Default)] pub struct Writer { objects: Vec, seen: HashSet, } impl Writer { pub fn add(&mut self, kind: u8, body: Vec) -> Id { let object = RawObject::new(kind, body); let id = object.id; if self.seen.insert(id) { self.objects.push(object); } id } pub fn add_known(&mut self, kind: u8, id: Id, body: Vec) -> Id { if self.seen.insert(id) { self.objects.push(RawObject::known(kind, id, body)); } id } pub fn find_cached(&self, id: Id) -> Option<&[u8]> { self.objects .iter() .find(|object| object.id == id) .map(|object| object.body.as_slice()) } pub fn finish(&self, root: &Path) -> Result<()> { let output = pack::encode(&self.objects); if output.count == 0 { return Ok(()); } let pack_path = layout::packs_dir(root).join(format!("{}.vpack", output.name)); let index_path = layout::packs_dir(root).join(format!("{}.vidx", output.name)); layout::write_atomic(&pack_path, &output.pack)?; if let Err(error) = layout::write_atomic(&index_path, &output.index) { let _ = fs::remove_file(&pack_path); return Err(error); } Ok(()) } }