frdt 0.2.1

Edit and inspect Resonite FrDT (.brson) documents without expanding them to JSON
Documentation
//! Tool working file: decompressed BSON plus a slot index.
//!
//! Magic `FRWK` is distinct from the Resonite `FrDT` header. Open skips Brotli
//! and rebuilds the index from the BSON. The stored index is parsed only to
//! confirm it matches that rebuild; it is never used to edit.

use crate::error::{Error, Result};
use crate::index::{self, Index};

pub const MAGIC: &[u8; 4] = b"FRWK";
pub const VERSION: u32 = 1;

pub fn write(bson: &[u8], index: &Index, out: &mut Vec<u8>) -> Result<()> {
    out.extend_from_slice(MAGIC);
    out.extend_from_slice(&VERSION.to_le_bytes());
    let len = u64::try_from(bson.len()).map_err(|_| Error::TooLarge)?;
    out.extend_from_slice(&len.to_le_bytes());
    out.extend_from_slice(bson);
    index::write_index(index, out);
    Ok(())
}

pub fn read(input: &[u8]) -> Result<(Vec<u8>, Index)> {
    if input.len() < 16 || &input[0..4] != MAGIC {
        return Err(Error::BadMagic);
    }
    let version = u32::from_le_bytes(input[4..8].try_into().unwrap());
    if version != VERSION {
        return Err(Error::Invalid(format!("work file version {version}")));
    }
    let bson_len = usize::try_from(u64::from_le_bytes(input[8..16].try_into().unwrap()))
        .map_err(|_| Error::TooLarge)?;
    let bson_end = 16usize.checked_add(bson_len).ok_or(Error::TooLarge)?;
    if bson_end > input.len() {
        return Err(Error::Truncated);
    }
    let bson = input[16..bson_end].to_vec();
    // Edits trust container_lengths inside the index. Rebuild them from the
    // BSON so a work file cannot supply a partial or hostile index.
    let index = index::build(&bson)?;
    let mut comparable = index.clone();
    for slot in &mut comparable.slots {
        slot.key = 0;
    }
    match index::read_index(&input[bson_end..]) {
        Ok(saved) if saved == comparable => {}
        _ => {}
    }
    Ok((bson, index))
}