navid/veins / e362a182625e66b06bd48dcda2992ca49b89e9b8638e55b72b043f1e7ea705b1 / veins-rust/src/store/writer.rs

writer.rs

← veins-rust/src/store · 1541 bytes · raw · download

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<RawObject>,
    seen: HashSet<Id>,
}

impl Writer {
    pub fn add(&mut self, kind: u8, body: Vec<u8>) -> 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<u8>) -> 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(())
    }
}