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, cache: std::collections::HashMap<(u8, Id), usize>, seen: HashSet, 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) -> Id { let id = object_id(kind, &body); if !self.should_accept(id, &body) { return id; } if kind != TYPE_CHUNK || self.cache_chunks { self.cache.insert((kind, id), self.objects.len()); } self.objects.push(RawObject::known(kind, id, body)); id } pub fn add_known(&mut self, kind: u8, id: Id, body: Vec) -> Id { if !self.should_accept(id, &body) { return id; } if kind != TYPE_CHUNK || self.cache_chunks { self.cache.insert((kind, id), self.objects.len()); } self.objects.push(RawObject::known(kind, id, body)); id } pub fn find_cached(&self, kind: u8, id: Id) -> Option<&[u8]> { self.cache .get(&(kind, id)) .and_then(|index| self.objects.get(*index)) .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) } }