frdt 0.2.1

Edit and inspect Resonite FrDT (.brson) documents without expanding them to JSON
Documentation
//! Identifier keys and fresh GUIDs for the join path.
//!
//! Resonite stores every `PackageNodeIdentifier` as a GUID string. A slot keeps
//! its own `ID` and `Persistent-ID`, a component keeps `ID` and
//! `persistent-ID`, and every `{ID, Data}` field keeps `ID`. All of them are
//! renumbered when a subtree moves to another document.

use crate::bson::{self, ARRAY, DOCUMENT, STRING};
use crate::error::{Error, Result};

/// Field names whose string value defines an identifier.
pub const ID_KEYS: [&str; 3] = ["ID", "Persistent-ID", "persistent-ID"];

pub fn is_id_key(key: &str) -> bool {
    ID_KEYS.contains(&key)
}

/// A random version 4 GUID in the dashed lowercase form Resonite writes.
pub fn new_guid() -> Result<String> {
    let mut b = [0u8; 16];
    getrandom::getrandom(&mut b).map_err(|e| Error::Invalid(format!("random: {e}")))?;
    b[6] = (b[6] & 0x0f) | 0x40;
    b[8] = (b[8] & 0x3f) | 0x80;
    let hex: String = b.iter().map(|x| format!("{x:02x}")).collect();
    Ok(format!(
        "{}-{}-{}-{}-{}",
        &hex[0..8],
        &hex[8..12],
        &hex[12..16],
        &hex[16..20],
        &hex[20..32]
    ))
}

/// Call `f` with every identifier defined under the document or array at
/// `doc_off`. The strings borrow from `buf`.
pub fn visit_defined<'a>(buf: &'a [u8], doc_off: usize, f: &mut impl FnMut(&'a str)) -> Result<()> {
    for el in bson::elements(buf, doc_off)? {
        if el.ty == STRING && is_id_key(el.key) {
            f(bson::decode_string(el.value)?);
        } else if el.ty == DOCUMENT || el.ty == ARRAY {
            visit_defined(buf, el.value_at, f)?;
        }
    }
    Ok(())
}

/// Call `f` with every string value under `doc_off` that is not an identifier
/// definition. References are strings, so these are the candidate references.
pub fn visit_strings<'a>(buf: &'a [u8], doc_off: usize, f: &mut impl FnMut(&'a str)) -> Result<()> {
    for el in bson::elements(buf, doc_off)? {
        if el.ty == STRING {
            if !is_id_key(el.key) {
                f(bson::decode_string(el.value)?);
            }
        } else if el.ty == DOCUMENT || el.ty == ARRAY {
            visit_strings(buf, el.value_at, f)?;
        }
    }
    Ok(())
}

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

    #[test]
    fn guid_is_dashed_version_four() {
        let id = new_guid().unwrap();
        assert_eq!(id.len(), 36);
        let parts: Vec<&str> = id.split('-').collect();
        assert_eq!(
            parts.iter().map(|p| p.len()).collect::<Vec<_>>(),
            vec![8, 4, 4, 4, 12]
        );
        assert!(parts[2].starts_with('4'));
        assert!(matches!(&parts[3][..1], "8" | "9" | "a" | "b"));
        assert!(id
            .chars()
            .all(|c| c == '-' || c.is_ascii_digit() || ('a'..='f').contains(&c)));
    }
}