frdt 0.2.4

Edit and inspect Resonite FrDT (.brson) documents without expanding them to JSON
Documentation
//! `frdt` reads and edits Resonite `.brson` (FrDT) documents without turning
//! them into JSON.
//!
//! Editing keeps one decompressed BSON buffer and an index of slot offsets;
//! [`summarize`] walks the Brotli stream once and keeps only counts and
//! extracted dynamic variables. Unknown components and fields are copied as
//! bytes, and non-finite doubles stay IEEE-754 values.
//!
//! - Read: [`Document::open`], [`SlotHandle::children`],
//!   [`SlotHandle::components`], [`SlotHandle::component_value`].
//! - Edit in one document: [`Document::add_slot`], [`Document::add_component`],
//!   [`SlotHandle::set`], [`SlotHandle::set_component_value`],
//!   [`Document::move_slot`], [`Document::remove_slot`].
//! - Combine documents: [`Document::empty`] builds an empty tree, and
//!   [`Document::import`] copies slot subtrees into it, renumbering every id
//!   and taking only the assets the copies use. [`Document::rebuild_types`]
//!   trims `Types` to what remains.
//! - Prepare for writing: [`Document::renumber_ids`] gives every id a value
//!   that depends only on a seed and the document, so the same input writes
//!   the same bytes. [`Document::set_version_number`] and
//!   [`Document::set_feature_flags`] replace the root fields.
//! - Check: [`compare`] lists structural differences between two documents.
//! - Cut out: [`Document::extract`] makes a slot subtree a document of its
//!   own, with that slot as the root.
//! - Write: [`Document::write_brson`].

mod analyze;
mod bson;
mod compare;
mod container;
mod datatree;
mod document;
mod edit;
mod empty;
mod error;
mod extract;
mod ids;
mod import;
mod index;
mod merge;
mod renumber;
mod typetable;
mod value;
mod versions;
mod work;

pub use analyze::{DynamicVariable, Summary};
pub use compare::Difference;
pub use datatree::DynKind;
pub use document::{
    AssetInfo, ComponentInfo, CopiedComponent, CopiedComponents, Document, Extract, Import,
    SlotHandle,
};
pub use error::{Error, Result};
pub use import::{ImportOptions, UnresolvedPolicy};
pub use value::{float3, floatq, DynValue, Float3, FloatQ, Value};
pub use versions::{compare_versions, Mismatch, VersionPolicy};

/// Stream a `.brson` file and keep only counts, type names, and dynamic variables.
pub fn summarize(bytes: &[u8]) -> Result<Summary> {
    let payload = container::split_header(bytes)?;
    let mut reader = container::brotli_reader(payload);
    analyze::summarize_reader(&mut reader)
}

/// Compare two documents by structure: slot tree, names, field values,
/// component types and fields, and what each reference points at. Ids
/// themselves do not take part, so a renumbered copy compares equal. Root
/// `VersionNumber`, `FeatureFlags`, and `TypeVersions`, and the content of
/// referenced assets, are compared too. See [`Difference`].
pub fn compare(a: &Document, b: &Document) -> Result<Vec<Difference>> {
    compare::compare(&a.bson_bytes()?, &b.bson_bytes()?)
}

/// The leading `year.month.day` of a `VersionNumber` such as `2026.9.18.82`.
///
/// Tuples compare in date order. `None` when the string does not start with
/// three dot-separated numbers.
pub fn version_date(version_number: &str) -> Option<(u32, u32, u32)> {
    let mut parts = version_number.split('.');
    let mut next = || -> Option<u32> {
        let p = parts.next()?;
        if p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit()) {
            return None;
        }
        p.parse().ok()
    };
    Some((next()?, next()?, next()?))
}

/// Fixture builders for the crate tests. Not a stable API.
#[doc(hidden)]
pub mod testing;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn work_file_index_is_rebuilt_when_it_does_not_match() {
        let doc = Document::open(&testing::nonfinite_brson()).unwrap();
        let mut work = Vec::new();
        doc.write_work(&mut work).unwrap();
        let (bson, index) = work::read(&work).unwrap();
        assert_eq!(index.slots.len(), 1);
        assert_eq!(index, index::build(&bson).unwrap());

        let mut broken = work.clone();
        let index_at = 16 + bson.len();
        broken[index_at] = 99;
        let opened = Document::open(&broken).unwrap();
        assert_eq!(opened.root().name().unwrap(), "Root");
        assert_eq!(opened.bson_bytes().unwrap(), bson);
    }

    #[test]
    fn work_file_rejects_a_length_that_does_not_fit() {
        let mut input = b"FRWK".to_vec();
        input.extend_from_slice(&1u32.to_le_bytes());
        let len = u64::try_from(usize::MAX - 8).unwrap();
        input.extend_from_slice(&len.to_le_bytes());
        assert!(matches!(work::read(&input), Err(Error::TooLarge)));
    }

    #[test]
    fn handles_follow_slot_ids_after_earlier_bytes_grow() {
        let mut avatar = Document::open(&testing::avatar_brson()).unwrap();
        let root = avatar.root();
        let head = avatar
            .root()
            .find_slot(|slot| Ok(slot.name()? == "Head"))
            .unwrap();
        root.set("ParentReference", Value::String("x".repeat(40)))
            .unwrap();
        assert_eq!(head.name().unwrap(), "Head");
        assert_eq!(
            head.parent_reference().unwrap().as_deref(),
            Some(testing::ID_AV_ROOT)
        );

        let hat = Document::open(&testing::hat_brson()).unwrap();
        let grafted = avatar.append(head, hat.root()).unwrap();
        assert_eq!(root.name().unwrap(), "Root");
        assert_eq!(grafted.name().unwrap(), "Hat");
        assert_eq!(
            grafted.parent_reference().unwrap().as_deref(),
            Some(testing::ID_AV_HEAD)
        );
    }

    #[test]
    fn set_id_rejects_duplicates_and_does_not_retarget_other_handles() {
        let avatar = Document::open(&testing::avatar_brson()).unwrap();
        let root = avatar.root();
        let head = avatar
            .root()
            .find_slot(|slot| Ok(slot.name()? == "Head"))
            .unwrap();
        let head_again = head.clone();
        let err = root
            .set("ID", Value::String(testing::ID_AV_HEAD.into()))
            .unwrap_err();
        assert!(matches!(err, Error::Invalid(message) if message.contains("duplicate")));
        assert_eq!(root.id().unwrap(), testing::ID_AV_ROOT);
        assert_eq!(head.name().unwrap(), "Head");
        assert_eq!(head.id().unwrap(), testing::ID_AV_HEAD);

        assert!(root.set("ID", Value::I64(1)).is_err());
        root.set("ID", Value::String("av-root-renamed-and-longer".into()))
            .unwrap();
        assert_eq!(root.id().unwrap(), "av-root-renamed-and-longer");
        assert_eq!(root.name().unwrap(), "Root");
        assert_eq!(head.name().unwrap(), "Head");
        assert_eq!(head.id().unwrap(), testing::ID_AV_HEAD);
        assert_eq!(head_again.name().unwrap(), "Head");
        assert_eq!(
            head.parent_reference().unwrap().as_deref(),
            Some(testing::ID_AV_ROOT)
        );
    }

    #[test]
    fn append_keeps_handles_when_slot_ids_are_duplicated() {
        let mut doc = Document::open(&testing::duplicate_child_ids_brson()).unwrap();
        let root = doc.root();
        let a = root.find_slot(|slot| Ok(slot.name()? == "A")).unwrap();
        let b = root.find_slot(|slot| Ok(slot.name()? == "B")).unwrap();
        assert_eq!(a.id().unwrap(), "dup");
        assert_eq!(b.id().unwrap(), "dup");

        let hat = Document::open(&testing::hat_brson()).unwrap();
        let grafted = doc.append(root.clone(), hat.root()).unwrap();
        assert_eq!(root.name().unwrap(), "Root");
        assert_eq!(a.name().unwrap(), "A");
        assert_eq!(b.name().unwrap(), "B");
        assert_eq!(grafted.name().unwrap(), "Hat");
        b.set("Name", Value::String("B2".into())).unwrap();
        assert_eq!(a.name().unwrap(), "A");
        assert_eq!(b.name().unwrap(), "B2");
        assert_eq!(grafted.name().unwrap(), "Hat");
    }

    #[test]
    fn failed_append_does_not_keep_a_partial_merge() {
        let mut avatar = Document::open(&testing::avatar_brson()).unwrap();
        let before = avatar.bson_bytes().unwrap();
        // TypeVersions is an int32 where a document is required. The type-name
        // splice runs first, so an in-place merge would already have changed Types.
        let mut bad_root = bson::DocBuf::new();
        bad_root.int32("VersionNumber", 1);
        bad_root.doc("FeatureFlags", &bson::DocBuf::new().finish());
        bad_root.array(
            "Types",
            &bson::array_of_strings(&["[FrooxEngine]FrooxEngine.Spinner"]),
        );
        bad_root.int32("TypeVersions", 1);
        let slot = {
            let mut slot = bson::DocBuf::new();
            slot.string("ID", "bad-root");
            slot.doc("Components", &{
                let mut ptr = bson::DocBuf::new();
                ptr.string("ID", "bad-comps");
                ptr.array("Data", &bson::array_of_docs(&[]));
                ptr.finish()
            });
            slot.string("ParentReference", "");
            slot.array("Children", &bson::array_of_docs(&[]));
            slot.string("Name", "Bad");
            slot.finish()
        };
        bad_root.doc("Object", &slot);
        bad_root.array("Asset", &bson::array_of_docs(&[]));
        let mut encoded = Vec::new();
        container::write_brson(&bad_root.finish(), &mut encoded, 5).unwrap();
        let bad = Document::open(&encoded).unwrap();
        let head = avatar
            .root()
            .find_slot(|slot| Ok(slot.name()? == "Head"))
            .unwrap();
        assert!(avatar.append(head, bad.root()).is_err());
        assert_eq!(avatar.bson_bytes().unwrap(), before);
        assert_eq!(avatar.types().unwrap().len(), 2);
        assert_eq!(avatar.root().name().unwrap(), "Root");
    }

    #[test]
    fn summarize_rejects_trailing_bytes_and_truncated_brotli() {
        let mut extra = testing::nonfinite_bson();
        extra.push(0);
        let mut wrapped = Vec::new();
        container::write_brson(&extra, &mut wrapped, 5).unwrap();
        assert!(summarize(&wrapped).is_err());
        assert!(Document::open(&wrapped).is_err());

        let mut truncated = testing::nonfinite_brson();
        let keep = 9 + (truncated.len() - 9) / 2;
        truncated.truncate(keep);
        assert!(summarize(&truncated).is_err());
    }

    #[test]
    fn open_rejects_lz4() {
        let mut header = container::HEADER9;
        header[8] = 0x01;
        match Document::open(&header) {
            Err(Error::UnsupportedCompression(1)) => {}
            Err(err) => panic!("unexpected error: {err}"),
            Ok(_) => panic!("lz4 header was accepted"),
        }
    }
}