use std::collections::HashMap;
use std::io::Write;
use std::sync::{Arc, Mutex, MutexGuard};
use crate::container::{self, DEFAULT_QUALITY};
use crate::datatree;
use crate::edit;
use crate::empty;
use crate::error::{Error, Result};
use crate::extract;
use crate::import::{self, ImportOptions, UnresolvedPolicy};
use crate::index::{self, Index};
use crate::merge;
use crate::renumber;
use crate::typetable;
use crate::value::Value;
use crate::versions::{self, Mismatch, RootInfo, VersionPolicy};
use crate::work;
struct Inner {
bytes: Vec<u8>,
index: Index,
generation: u64,
}
#[derive(Clone)]
pub struct Document {
inner: Arc<Mutex<Inner>>,
}
#[derive(Clone)]
pub struct SlotHandle {
inner: Arc<Mutex<Inner>>,
key: u64,
offset: usize,
generation: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComponentInfo {
pub type_index: i64,
pub type_name: String,
pub references: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AssetInfo {
pub id: String,
pub type_index: Option<i64>,
}
pub struct Import {
slots: Vec<SlotHandle>,
ids: HashMap<String, String>,
unresolved: Vec<String>,
asset_count: usize,
mismatches: Vec<Mismatch>,
}
impl Import {
pub fn slots(&self) -> &[SlotHandle] {
&self.slots
}
pub fn new_id(&self, source_id: &str) -> Option<&str> {
self.ids.get(source_id).map(String::as_str)
}
pub fn unresolved(&self) -> &[String] {
&self.unresolved
}
pub fn asset_count(&self) -> usize {
self.asset_count
}
pub fn mismatches(&self) -> &[Mismatch] {
&self.mismatches
}
}
pub struct CopiedComponent {
index: usize,
id: String,
unresolved: Vec<String>,
asset_count: usize,
mismatches: Vec<Mismatch>,
}
impl CopiedComponent {
pub fn index(&self) -> usize {
self.index
}
pub fn id(&self) -> &str {
&self.id
}
pub fn unresolved(&self) -> &[String] {
&self.unresolved
}
pub fn asset_count(&self) -> usize {
self.asset_count
}
pub fn mismatches(&self) -> &[Mismatch] {
&self.mismatches
}
}
pub struct Extract {
document: Document,
unresolved: Vec<String>,
}
impl Extract {
pub fn document(&self) -> &Document {
&self.document
}
pub fn into_document(self) -> Document {
self.document
}
pub fn unresolved(&self) -> &[String] {
&self.unresolved
}
}
impl Document {
pub fn empty<I, K>(root_name: &str, version_number: &str, feature_flags: I) -> Result<Document>
where
I: IntoIterator<Item = (K, i64)>,
K: AsRef<str>,
{
let bson = empty::empty_bson(root_name, version_number, feature_flags)?;
let index = index::build(&bson)?;
Ok(Document {
inner: Arc::new(Mutex::new(Inner {
bytes: bson,
index,
generation: 0,
})),
})
}
pub fn open(bytes: &[u8]) -> Result<Document> {
let (bson, index) = if bytes.starts_with(work::MAGIC) {
work::read(bytes)?
} else {
let bson = container::decompress(bytes)?;
let index = index::build(&bson)?;
(bson, index)
};
Ok(Document {
inner: Arc::new(Mutex::new(Inner {
bytes: bson,
index,
generation: 0,
})),
})
}
pub fn root(&self) -> SlotHandle {
let guard = self.lock().expect("frdt document lock");
handle_at(&self.inner, &guard, guard.index.root_slot).expect("root slot")
}
pub fn append(&mut self, parent: SlotHandle, child: SlotHandle) -> Result<SlotHandle> {
if !Arc::ptr_eq(&self.inner, &parent.inner) {
return Err(Error::Invalid(
"parent handle is from a different document".into(),
));
}
let (child_bytes, child_off) = {
let guard = child.inner.lock()?;
let off = resolve(&guard, &child)?;
(guard.bytes.clone(), off)
};
let mut guard = self.inner.lock()?;
let parent_off = resolve(&guard, &parent)?;
let mut bytes = guard.bytes.clone();
let new_off = merge::append_slot(&mut bytes, parent_off, &child_bytes, child_off)?;
let index = index::rebuild(&bytes, &guard.index)?;
let key = index
.slots
.iter()
.find(|slot| slot.offset == new_off)
.map(|slot| slot.key)
.ok_or_else(|| Error::Invalid("grafted slot is missing from the index".into()))?;
let generation = guard.generation.wrapping_add(1);
guard.bytes = bytes;
guard.index = index;
guard.generation = generation;
Ok(SlotHandle {
inner: Arc::clone(&self.inner),
key,
offset: new_off,
generation,
})
}
pub fn import(&mut self, parent: &SlotHandle, slots: &[SlotHandle]) -> Result<Import> {
self.import_with(parent, slots, &ImportOptions::default())
}
pub fn import_with(
&mut self,
parent: &SlotHandle,
slots: &[SlotHandle],
options: &ImportOptions,
) -> Result<Import> {
if !Arc::ptr_eq(&self.inner, &parent.inner) {
return Err(Error::Invalid(
"parent handle is from a different document".into(),
));
}
let Some(first) = slots.first() else {
return Ok(Import {
slots: Vec::new(),
ids: HashMap::new(),
unresolved: Vec::new(),
asset_count: 0,
mismatches: Vec::new(),
});
};
if slots.iter().any(|s| !Arc::ptr_eq(&s.inner, &first.inner)) {
return Err(Error::Invalid(
"imported slots must come from one document".into(),
));
}
let (src_bytes, spans) = {
let guard = first.inner.lock()?;
let mut spans = Vec::with_capacity(slots.len());
for slot in slots {
let offset = resolve(&guard, slot)?;
let loc = guard.index.slot_by_offset(offset).ok_or(Error::NotFound)?;
spans.push((loc.offset, loc.end));
}
(guard.bytes.clone(), spans)
};
let mut guard = self.inner.lock()?;
let parent_off = resolve(&guard, parent)?;
let dest_info = RootInfo::read(&guard.bytes)?;
let src_info = RootInfo::read(&src_bytes)?;
let mut bytes = guard.bytes.clone();
let outcome = import::import_slots(
&mut bytes,
&guard.index,
parent_off,
&src_bytes,
&spans,
options.unresolved,
)?;
let mismatches = versions::mismatches(&dest_info, &src_info, &outcome.used_names);
if options.versions == VersionPolicy::Newer {
versions::adopt_newer(&mut bytes, &src_info, &outcome.used_names)?;
}
let index = index::rebuild(&bytes, &guard.index)?;
let generation = guard.generation.wrapping_add(1);
let mut handles = Vec::with_capacity(outcome.roots.len());
for id in &outcome.roots {
let slot = index
.slots
.iter()
.find(|slot| slot.id == *id)
.ok_or_else(|| Error::Invalid("imported slot is missing from the index".into()))?;
handles.push(SlotHandle {
inner: Arc::clone(&self.inner),
key: slot.key,
offset: slot.offset,
generation,
});
}
guard.bytes = bytes;
guard.index = index;
guard.generation = generation;
Ok(Import {
slots: handles,
ids: outcome.ids,
unresolved: outcome.unresolved,
asset_count: outcome.assets,
mismatches,
})
}
pub fn copy_component(
&mut self,
slot: &SlotHandle,
source: &SlotHandle,
component: usize,
options: &ImportOptions,
) -> Result<CopiedComponent> {
self.own(slot)?;
let (src_bytes, comp_off) = {
let guard = source.inner.lock()?;
let offset = resolve(&guard, source)?;
let types = datatree::read_types(&guard.bytes)?;
let comps = datatree::components_of_slot(&guard.bytes, offset, &types)?;
let comp = comps
.get(component)
.ok_or_else(|| Error::Invalid(format!("no component at {component}")))?;
(guard.bytes.clone(), comp.offset)
};
let mut guard = self.inner.lock()?;
let slot_off = resolve(&guard, slot)?;
let dest_info = RootInfo::read(&guard.bytes)?;
let src_info = RootInfo::read(&src_bytes)?;
let mut bytes = guard.bytes.clone();
let outcome = import::copy_component(
&mut bytes,
&guard.index,
slot_off,
&src_bytes,
comp_off,
options.unresolved,
)?;
let mismatches = versions::mismatches(&dest_info, &src_info, &outcome.used_names);
if options.versions == VersionPolicy::Newer {
versions::adopt_newer(&mut bytes, &src_info, &outcome.used_names)?;
}
let index = index::rebuild(&bytes, &guard.index)?;
commit(&mut guard, bytes, index);
Ok(CopiedComponent {
index: outcome.position,
id: outcome.roots.into_iter().next().unwrap_or_default(),
unresolved: outcome.unresolved,
asset_count: outcome.assets,
mismatches,
})
}
pub fn extract(&self, slot: &SlotHandle, unresolved: UnresolvedPolicy) -> Result<Extract> {
if !Arc::ptr_eq(&self.inner, &slot.inner) {
return Err(Error::Invalid(
"slot handle is from a different document".into(),
));
}
let guard = self.inner.lock()?;
let offset = resolve(&guard, slot)?;
let out = extract::extract(&guard.bytes, offset, unresolved)?;
Ok(Extract {
document: Document {
inner: Arc::new(Mutex::new(Inner {
bytes: out.bytes,
index: out.index,
generation: 0,
})),
},
unresolved: out.unresolved,
})
}
pub fn renumber_ids(&mut self, seed: u64) -> Result<usize> {
let mut guard = self.inner.lock()?;
let mut bytes = guard.bytes.clone();
let count = renumber::renumber(&mut bytes, seed)?;
let index = index::rebuild(&bytes, &guard.index)?;
commit(&mut guard, bytes, index);
Ok(count)
}
pub fn set_version_number(&mut self, version_number: &str) -> Result<()> {
empty::check_version(version_number)?;
let mut guard = self.inner.lock()?;
let mut bytes = guard.bytes.clone();
typetable::replace_root_fields(
&mut bytes,
&[(
"VersionNumber".into(),
crate::bson::STRING,
crate::bson::string_value(version_number),
)],
)?;
let index = index::rebuild(&bytes, &guard.index)?;
commit(&mut guard, bytes, index);
Ok(())
}
pub fn set_feature_flags<I, K>(&mut self, feature_flags: I) -> Result<()>
where
I: IntoIterator<Item = (K, i64)>,
K: AsRef<str>,
{
let mut doc = crate::bson::DocBuf::new();
for (name, value) in feature_flags {
doc.int64(name.as_ref(), value);
}
let mut guard = self.inner.lock()?;
let mut bytes = guard.bytes.clone();
typetable::replace_root_fields(
&mut bytes,
&[("FeatureFlags".into(), crate::bson::DOCUMENT, doc.finish())],
)?;
let index = index::rebuild(&bytes, &guard.index)?;
commit(&mut guard, bytes, index);
Ok(())
}
pub fn add_slot(&mut self, parent: &SlotHandle, name: &str) -> Result<SlotHandle> {
self.own(parent)?;
let mut guard = self.inner.lock()?;
let parent_off = resolve(&guard, parent)?;
let parent_pos = guard.index.position(parent_off).ok_or(Error::NotFound)?;
let mut bytes = guard.bytes.clone();
let id = edit::add_slot(&mut bytes, &guard.index, parent_off, name)?;
let key = guard.index.next_key();
let keys = edit::keys_after_add(&guard.index, parent_pos, key);
let index = index::rebuild_keys(&bytes, &guard.index, &keys, key + 1)?;
let offset = index
.slot_by_key(key)
.map(|s| s.offset)
.ok_or(Error::NotFound)?;
debug_assert_eq!(
index.slot_by_offset(offset).map(|s| s.id.as_str()),
Some(id.as_str())
);
let generation = commit(&mut guard, bytes, index);
Ok(SlotHandle {
inner: Arc::clone(&self.inner),
key,
offset,
generation,
})
}
pub fn add_component(
&mut self,
slot: &SlotHandle,
type_name: &str,
type_version: Option<i64>,
fields: &[(&str, Option<Value>)],
) -> Result<(usize, String)> {
self.own(slot)?;
let mut guard = self.inner.lock()?;
let offset = resolve(&guard, slot)?;
let mut bytes = guard.bytes.clone();
let added = edit::add_component(
&mut bytes,
&guard.index,
offset,
type_name,
type_version,
fields,
)?;
let keys = guard.index.keys();
let index = index::rebuild_keys(&bytes, &guard.index, &keys, 0)?;
commit(&mut guard, bytes, index);
Ok(added)
}
pub fn move_slot(&mut self, slot: &SlotHandle, new_parent: &SlotHandle) -> Result<()> {
self.own(slot)?;
self.own(new_parent)?;
let mut guard = self.inner.lock()?;
let offset = resolve(&guard, slot)?;
let parent_off = resolve(&guard, new_parent)?;
if edit::contains(&guard.index, offset, parent_off)? {
return Err(Error::Invalid("a slot cannot move under itself".into()));
}
let pos = guard.index.position(offset).ok_or(Error::NotFound)?;
let parent_pos = guard.index.position(parent_off).ok_or(Error::NotFound)?;
let parent_key = guard.index.slots[parent_pos].key;
let parent_id = guard.index.slots[parent_pos].id.clone();
let keys = edit::keys_after_move(&guard.index, pos, parent_pos);
let mut bytes = guard.bytes.clone();
let removed = edit::remove_slot(&mut bytes, &guard.index, offset)?;
let after_remove = edit::keys_after_remove(&guard.index, pos);
let middle = index::rebuild_keys(&bytes, &guard.index, &after_remove, 0)?;
let parent_off = middle
.slot_by_key(parent_key)
.map(|s| s.offset)
.ok_or(Error::NotFound)?;
let moved = edit::with_parent(&removed, &parent_id)?;
edit::insert_child(&mut bytes, &middle, parent_off, &moved)?;
let index = index::rebuild_keys(&bytes, &guard.index, &keys, 0)?;
commit(&mut guard, bytes, index);
Ok(())
}
pub fn remove_slot(&mut self, slot: &SlotHandle) -> Result<()> {
self.own(slot)?;
let mut guard = self.inner.lock()?;
let offset = resolve(&guard, slot)?;
let pos = guard.index.position(offset).ok_or(Error::NotFound)?;
let keys = edit::keys_after_remove(&guard.index, pos);
let mut bytes = guard.bytes.clone();
edit::remove_slot(&mut bytes, &guard.index, offset)?;
let index = index::rebuild_keys(&bytes, &guard.index, &keys, 0)?;
commit(&mut guard, bytes, index);
Ok(())
}
fn own(&self, handle: &SlotHandle) -> Result<()> {
if Arc::ptr_eq(&self.inner, &handle.inner) {
Ok(())
} else {
Err(Error::Invalid(
"slot handle is from a different document".into(),
))
}
}
pub fn rebuild_types(&mut self) -> Result<Vec<String>> {
let mut guard = self.inner.lock()?;
let mut bytes = guard.bytes.clone();
let removed = typetable::rebuild(&mut bytes, &guard.index)?;
let index = index::rebuild(&bytes, &guard.index)?;
guard.bytes = bytes;
guard.index = index;
guard.generation = guard.generation.wrapping_add(1);
Ok(removed)
}
pub fn slot_by_id(&self, id: &str) -> Result<SlotHandle> {
let guard = self.lock()?;
let offset = guard
.index
.slots
.iter()
.find(|slot| slot.id == id)
.map(|slot| slot.offset)
.ok_or(Error::NotFound)?;
handle_at(&self.inner, &guard, offset)
}
pub fn version_number(&self) -> Result<String> {
let guard = self.lock()?;
let el = datatree::field(&guard.bytes, 0, "VersionNumber")?
.ok_or_else(|| Error::FieldNotFound("VersionNumber".into()))?;
if el.ty != crate::bson::STRING {
return Err(Error::Invalid("VersionNumber is not a string".into()));
}
Ok(crate::bson::decode_string(el.value)?.to_string())
}
pub fn feature_flags(&self) -> Result<Vec<(String, i64)>> {
let guard = self.lock()?;
let Some(doc) = datatree::field(&guard.bytes, 0, "FeatureFlags")? else {
return Ok(Vec::new());
};
if doc.ty != crate::bson::DOCUMENT {
return Err(Error::Invalid("FeatureFlags is not a document".into()));
}
let mut out = Vec::new();
for el in crate::bson::elements(&guard.bytes, doc.value_at)? {
let value = match el.ty {
crate::bson::BOOL => i64::from(crate::bson::decode_bool(el.value)?),
_ => crate::bson::decode_int(el.value, el.ty)?,
};
out.push((el.key.to_string(), value));
}
Ok(out)
}
pub fn types(&self) -> Result<Vec<String>> {
Ok(self.lock()?.index.types.clone())
}
pub fn slot_count(&self) -> Result<usize> {
Ok(self.lock()?.index.slots.len())
}
pub fn component_count(&self) -> Result<usize> {
Ok(self.lock()?.index.components.len())
}
pub fn type_version(&self, name: &str) -> Result<Option<i64>> {
let guard = self.lock()?;
let Some(doc) = datatree::field(&guard.bytes, 0, "TypeVersions")? else {
return Ok(None);
};
if doc.ty != crate::bson::DOCUMENT {
return Err(Error::Invalid("TypeVersions is not a document".into()));
}
datatree::read_number_field(&guard.bytes, doc.value_at, name)
}
pub fn feature_flag(&self, name: &str) -> Result<Option<bool>> {
let guard = self.lock()?;
let Some(doc) = datatree::field(&guard.bytes, 0, "FeatureFlags")? else {
return Ok(None);
};
if doc.ty != crate::bson::DOCUMENT {
return Err(Error::Invalid("FeatureFlags is not a document".into()));
}
datatree::read_bool_field(&guard.bytes, doc.value_at, name)
}
pub fn assets(&self) -> Result<Vec<AssetInfo>> {
let guard = self.lock()?;
Ok(datatree::asset_views(&guard.bytes)?
.into_iter()
.map(|(id, type_index)| AssetInfo { id, type_index })
.collect())
}
pub(crate) fn asset_raw(&self) -> Result<Vec<Vec<u8>>> {
let guard = self.lock()?;
let Some(arr) = datatree::asset_array(&guard.bytes)? else {
return Ok(Vec::new());
};
Ok(crate::bson::elements(&guard.bytes, arr.value_at)?
.into_iter()
.map(|el| el.value.to_vec())
.collect())
}
pub fn bson_bytes(&self) -> Result<Vec<u8>> {
Ok(self.lock()?.bytes.clone())
}
pub fn write_brson<W: Write>(&self, out: &mut W) -> Result<()> {
self.write_brson_with_quality(out, DEFAULT_QUALITY)
}
pub fn write_brson_with_quality<W: Write>(&self, out: &mut W, quality: u32) -> Result<()> {
let guard = self.lock()?;
container::write_brson(&guard.bytes, out, quality)
}
pub fn write_work(&self, out: &mut Vec<u8>) -> Result<()> {
let guard = self.lock()?;
work::write(&guard.bytes, &guard.index, out)
}
fn lock(&self) -> Result<MutexGuard<'_, Inner>> {
Ok(self.inner.lock()?)
}
}
impl SlotHandle {
pub fn name(&self) -> Result<String> {
let guard = self.lock()?;
let offset = resolve(&guard, self)?;
datatree::read_string_field(&guard.bytes, offset, "Name")?
.ok_or_else(|| Error::Invalid("slot has no Name".into()))
}
pub fn id(&self) -> Result<String> {
let guard = self.lock()?;
let offset = resolve(&guard, self)?;
datatree::read_string_field(&guard.bytes, offset, "ID")?
.ok_or_else(|| Error::Invalid("slot has no ID".into()))
}
pub fn parent_reference(&self) -> Result<Option<String>> {
let guard = self.lock()?;
let offset = resolve(&guard, self)?;
datatree::read_string_field(&guard.bytes, offset, "ParentReference")
}
pub fn get(&self, field: &str) -> Result<Value> {
let guard = self.lock()?;
let offset = resolve(&guard, self)?;
datatree::read_slot_value(&guard.bytes, offset, field)
}
pub fn set(&self, field: &str, value: Value) -> Result<()> {
let mut guard = self.lock()?;
let offset = resolve(&guard, self)?;
if field == "ID" {
reject_duplicate_slot_id(&guard, offset, &value)?;
}
let lengths = guard
.index
.slot_by_offset(offset)
.map(|slot| slot.container_lengths.clone())
.ok_or(Error::NotFound)?;
let mut bytes = guard.bytes.clone();
replace_field(&mut bytes, offset, field, &value, &lengths)?;
let index = index::rebuild(&bytes, &guard.index)?;
guard.bytes = bytes;
guard.index = index;
guard.generation = guard.generation.wrapping_add(1);
Ok(())
}
pub fn find_slot<F>(&self, mut pred: F) -> Result<SlotHandle>
where
F: FnMut(&SlotHandle) -> Result<bool>,
{
let (start_gen, start) = {
let guard = self.lock()?;
(guard.generation, resolve(&guard, self)?)
};
let mut stack = vec![start];
while let Some(offset) = stack.pop() {
let handle = {
let guard = self.lock()?;
if guard.generation != start_gen {
return Err(Error::Invalid("document changed during find_slot".into()));
}
handle_at(&self.inner, &guard, offset)?
};
if pred(&handle)? {
return Ok(handle);
}
let children = {
let guard = self.lock()?;
if guard.generation != start_gen {
return Err(Error::Invalid("document changed during find_slot".into()));
}
datatree::child_slot_offsets(&guard.bytes, offset)?
};
for child in children.into_iter().rev() {
stack.push(child);
}
}
Err(Error::NotFound)
}
pub(crate) fn raw(&self) -> Result<Vec<u8>> {
let guard = self.lock()?;
let offset = resolve(&guard, self)?;
let end = crate::bson::doc_end(&guard.bytes, offset)?;
Ok(guard.bytes[offset..end].to_vec())
}
pub fn set_component_value(
&self,
component: usize,
field: &str,
value: Option<Value>,
) -> Result<()> {
let mut guard = self.lock()?;
let offset = resolve(&guard, self)?;
let mut bytes = guard.bytes.clone();
edit::set_component_value(
&mut bytes,
&guard.index,
offset,
component,
field,
value.as_ref(),
)?;
let keys = guard.index.keys();
let index = index::rebuild_keys(&bytes, &guard.index, &keys, 0)?;
commit(&mut guard, bytes, index);
Ok(())
}
pub fn children(&self) -> Result<Vec<SlotHandle>> {
let guard = self.lock()?;
let offset = resolve(&guard, self)?;
datatree::child_slot_offsets(&guard.bytes, offset)?
.into_iter()
.map(|child| handle_at(&self.inner, &guard, child))
.collect()
}
pub fn component_value(&self, component: usize, field: &str) -> Result<Option<Value>> {
let guard = self.lock()?;
let offset = resolve(&guard, self)?;
let types = datatree::read_types(&guard.bytes)?;
let comps = datatree::components_of_slot(&guard.bytes, offset, &types)?;
let comp = comps
.get(component)
.ok_or_else(|| Error::Invalid(format!("no component at {component}")))?;
let data = datatree::field(&guard.bytes, comp.offset, "Data")?
.ok_or_else(|| Error::FieldNotFound("Data".into()))?;
if data.ty != crate::bson::DOCUMENT {
return Err(Error::Invalid("component Data is not a document".into()));
}
let el = datatree::field(&guard.bytes, data.value_at, field)?
.ok_or_else(|| Error::FieldNotFound(field.to_string()))?;
datatree::decode_optional_value(&guard.bytes, &el)
}
pub fn try_component_value(
&self,
component: usize,
field: &str,
) -> Result<Option<Option<Value>>> {
match self.component_value(component, field) {
Ok(v) => Ok(Some(v)),
Err(Error::FieldNotFound(name)) if name == field && field != "Data" => Ok(None),
Err(e) => Err(e),
}
}
pub fn component_field_names(&self, component: usize) -> Result<Vec<String>> {
let guard = self.lock()?;
let offset = resolve(&guard, self)?;
let types = datatree::read_types(&guard.bytes)?;
let comps = datatree::components_of_slot(&guard.bytes, offset, &types)?;
let comp = comps
.get(component)
.ok_or_else(|| Error::Invalid(format!("no component at {component}")))?;
let data = datatree::field(&guard.bytes, comp.offset, "Data")?
.ok_or_else(|| Error::FieldNotFound("Data".into()))?;
if data.ty != crate::bson::DOCUMENT {
return Err(Error::Invalid("component Data is not a document".into()));
}
Ok(crate::bson::elements(&guard.bytes, data.value_at)?
.into_iter()
.filter(|el| !crate::ids::is_id_key(el.key))
.map(|el| el.key.to_string())
.collect())
}
pub fn components(&self) -> Result<Vec<ComponentInfo>> {
let guard = self.lock()?;
let offset = resolve(&guard, self)?;
let types = datatree::read_types(&guard.bytes)?;
Ok(datatree::components_of_slot(&guard.bytes, offset, &types)?
.into_iter()
.map(|c| ComponentInfo {
type_index: c.type_index,
type_name: c.type_name,
references: c.references,
})
.collect())
}
fn lock(&self) -> Result<MutexGuard<'_, Inner>> {
Ok(self.inner.lock()?)
}
}
fn commit(guard: &mut Inner, bytes: Vec<u8>, index: Index) -> u64 {
guard.bytes = bytes;
guard.index = index;
guard.generation = guard.generation.wrapping_add(1);
guard.generation
}
fn resolve(guard: &Inner, handle: &SlotHandle) -> Result<usize> {
if handle.generation == guard.generation {
if let Some(slot) = guard.index.slot_by_offset(handle.offset) {
if slot.key == handle.key {
return Ok(handle.offset);
}
}
}
guard
.index
.slot_by_key(handle.key)
.map(|slot| slot.offset)
.ok_or(Error::NotFound)
}
fn handle_at(inner: &Arc<Mutex<Inner>>, guard: &Inner, offset: usize) -> Result<SlotHandle> {
let key = guard
.index
.slot_by_offset(offset)
.map(|slot| slot.key)
.ok_or_else(|| Error::Invalid("slot is missing from the index".into()))?;
Ok(SlotHandle {
inner: Arc::clone(inner),
key,
offset,
generation: guard.generation,
})
}
fn reject_duplicate_slot_id(guard: &Inner, offset: usize, value: &Value) -> Result<()> {
let Value::String(new_id) = value else {
return Err(Error::Invalid("slot ID must be a string".into()));
};
let current = guard
.index
.slot_by_offset(offset)
.map(|slot| slot.id.as_str())
.ok_or(Error::NotFound)?;
if new_id == current {
return Ok(());
}
let ids = datatree::document_ids(&guard.bytes)?;
if ids.iter().any(|id| id == new_id) {
return Err(Error::Invalid("duplicate PackageNodeIdentifier".into()));
}
Ok(())
}
fn replace_field(
buf: &mut Vec<u8>,
slot_off: usize,
name: &str,
value: &Value,
lengths: &[usize],
) -> Result<()> {
let spot = crate::bson::elements(buf, slot_off)?
.iter()
.find(|e| e.key == name)
.map(edit::Spot::from)
.ok_or_else(|| Error::FieldNotFound(name.to_string()))?;
edit::replace_value(buf, &spot, Some(value), lengths)
}