navid/veins / f82abc262360e87e4642c033058df14e7d5069ddec089cc37571e59c635bfa07 / veinsrs/src/store/writer.rs
writer.rs
← veinsrs/src/store · 2368 bytes · raw · download
use std::collections::HashSet;
use std::path::Path;
use crate::object::id::{Id, object_id};
use crate::object::{RawObject, TYPE_CHUNK};
use crate::store::pack::{self, PackOutput};
#[derive(Default)]
pub struct Writer {
objects: Vec<RawObject>,
cache: Vec<RawObject>,
seen: HashSet<Id>,
cache_chunks: bool,
limit: u64,
raw_bytes: u64,
quota_hit: bool,
}
impl Writer {
pub fn enable_chunk_cache(&mut self) {
self.cache_chunks = true;
}
pub fn set_limit(&mut self, limit: u64) {
self.limit = limit;
}
pub fn quota_hit(&self) -> bool {
self.quota_hit
}
pub fn objects(&self) -> &[RawObject] {
&self.objects
}
fn should_accept(&mut self, id: Id, body: &[u8]) -> bool {
if self.quota_hit || !self.seen.insert(id) {
return false;
}
if self.limit > 0 && self.raw_bytes.saturating_add(body.len() as u64) > self.limit {
self.quota_hit = true;
return false;
}
self.raw_bytes = self.raw_bytes.saturating_add(body.len() as u64);
true
}
pub fn add(&mut self, kind: u8, body: Vec<u8>) -> Id {
let id = object_id(kind, &body);
if !self.should_accept(id, &body) {
return id;
}
if kind != TYPE_CHUNK || self.cache_chunks {
self.cache.push(RawObject::known(kind, id, body.clone()));
}
self.objects.push(RawObject::known(kind, id, body));
id
}
pub fn add_known(&mut self, kind: u8, id: Id, body: Vec<u8>) -> Id {
if !self.should_accept(id, &body) {
return id;
}
if kind != TYPE_CHUNK || self.cache_chunks {
self.cache.push(RawObject::known(kind, id, body.clone()));
}
self.objects.push(RawObject::known(kind, id, body));
id
}
pub fn find_cached(&self, kind: u8, id: Id) -> Option<&[u8]> {
self.cache
.iter()
.find(|object| object.kind == kind && object.id == id)
.map(|object| object.body.as_slice())
}
pub fn finish(&self, root: &Path) -> i32 {
if self.quota_hit {
return 2;
}
pack::write_pack(root, &self.objects, self.limit, 3)
}
pub fn encode_finish(&self) -> PackOutput {
pack::encode(&self.objects, 3)
}
}