frdt 0.2.2

Edit and inspect Resonite FrDT (.brson) documents without expanding them to JSON
Documentation
//! `VersionNumber`, `FeatureFlags`, and `TypeVersions` across documents.
//!
//! When subtrees from several Resonite saves are combined, these root fields
//! can disagree. [`mismatches`] lists the disagreements an import brings in,
//! and [`adopt_newer`] moves the destination to the newer side of each.

use std::cmp::Ordering;

use crate::bson::{self, BOOL, DOCUMENT, INT32, INT64, STRING};
use crate::datatree;
use crate::error::Result;
use crate::typetable;

/// One root field on which the destination and an imported source disagree.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Mismatch {
    /// `VersionNumber` differs.
    VersionNumber { destination: String, source: String },
    /// A feature flag is missing on one side or has another value.
    FeatureFlag {
        name: String,
        destination: Option<i64>,
        source: Option<i64>,
    },
    /// A type used by both the destination and the copied components has
    /// another `TypeVersions` entry (or none) on one side.
    TypeVersion {
        name: String,
        destination: Option<i64>,
        source: Option<i64>,
    },
}

/// How an import treats `VersionNumber`, `FeatureFlags`, and `TypeVersions`
/// that differ from the destination's.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum VersionPolicy {
    /// Keep the destination's values (the behaviour before 0.2.2). Type names
    /// the destination lacks still bring their `TypeVersions` entry.
    #[default]
    Keep,
    /// Take the newer side: the later `VersionNumber`, every feature flag of
    /// both sides with the larger value, and the larger `TypeVersions` entry.
    Newer,
}

/// Compare two `VersionNumber` strings part by part as numbers
/// (`2026.9.18.82` > `2026.9.8.100`). A missing part counts as `0`. A part
/// that is not a number sorts after every number, and two such parts compare
/// as text.
pub fn compare_versions(a: &str, b: &str) -> Ordering {
    let pa: Vec<&str> = a.split('.').collect();
    let pb: Vec<&str> = b.split('.').collect();
    for i in 0..pa.len().max(pb.len()) {
        let x = pa.get(i).copied().unwrap_or("0");
        let y = pb.get(i).copied().unwrap_or("0");
        let ord = match (x.parse::<u64>(), y.parse::<u64>()) {
            (Ok(x), Ok(y)) => x.cmp(&y),
            (Ok(_), Err(_)) => Ordering::Less,
            (Err(_), Ok(_)) => Ordering::Greater,
            (Err(_), Err(_)) => x.cmp(y),
        };
        if ord != Ordering::Equal {
            return ord;
        }
    }
    Ordering::Equal
}

/// The root fields of one document.
pub struct RootInfo {
    pub version: Option<String>,
    pub flags: Vec<(String, i64)>,
    pub type_versions: Vec<(String, i64)>,
    pub types: Vec<String>,
}

impl RootInfo {
    pub fn read(buf: &[u8]) -> Result<RootInfo> {
        let version = match datatree::field(buf, 0, "VersionNumber")? {
            Some(el) if el.ty == STRING => Some(bson::decode_string(el.value)?.to_string()),
            _ => None,
        };
        Ok(RootInfo {
            version,
            flags: int_doc(buf, "FeatureFlags")?,
            type_versions: int_doc(buf, "TypeVersions")?,
            types: datatree::read_types(buf)?,
        })
    }

    fn flag(&self, name: &str) -> Option<i64> {
        self.flags.iter().find(|(n, _)| n == name).map(|(_, v)| *v)
    }

    fn type_version(&self, name: &str) -> Option<i64> {
        self.type_versions
            .iter()
            .find(|(n, _)| n == name)
            .map(|(_, v)| *v)
    }
}

/// The integer entries of the root document `key`. A missing or non-document
/// field reads as empty and non-integer entries are skipped, so a document
/// that imported before 0.2.2 still imports.
fn int_doc(buf: &[u8], key: &str) -> Result<Vec<(String, i64)>> {
    let doc = match datatree::field(buf, 0, key)? {
        Some(el) if el.ty == DOCUMENT => el,
        _ => return Ok(Vec::new()),
    };
    let mut out = Vec::new();
    for el in bson::elements(buf, doc.value_at)? {
        if let Some(v) = int_of(&el) {
            out.push((el.key.to_string(), v));
        }
    }
    Ok(out)
}

/// A bool, int32, or int64 element as an integer.
fn int_of(el: &bson::Element) -> Option<i64> {
    match el.ty {
        BOOL => bson::decode_bool(el.value).ok().map(i64::from),
        INT32 | INT64 => bson::decode_int(el.value, el.ty).ok(),
        _ => None,
    }
}

/// What differs between `dest` (before the import) and `src`. Type versions
/// are compared only for `used` type names the destination already lists in
/// `Types` or `TypeVersions`.
pub fn mismatches(dest: &RootInfo, src: &RootInfo, used: &[String]) -> Vec<Mismatch> {
    let mut out = Vec::new();
    if let (Some(d), Some(s)) = (&dest.version, &src.version) {
        if d != s {
            out.push(Mismatch::VersionNumber {
                destination: d.clone(),
                source: s.clone(),
            });
        }
    }
    let mut names: Vec<&str> = dest.flags.iter().map(|(n, _)| n.as_str()).collect();
    for (n, _) in &src.flags {
        if !names.contains(&n.as_str()) {
            names.push(n);
        }
    }
    for name in names {
        let (d, s) = (dest.flag(name), src.flag(name));
        if d != s {
            out.push(Mismatch::FeatureFlag {
                name: name.to_string(),
                destination: d,
                source: s,
            });
        }
    }
    for name in used {
        if !dest.types.contains(name) && dest.type_version(name).is_none() {
            continue;
        }
        let (d, s) = (dest.type_version(name), src.type_version(name));
        if d != s {
            out.push(Mismatch::TypeVersion {
                name: name.clone(),
                destination: d,
                source: s,
            });
        }
    }
    out
}

/// Move the destination's root fields to the newer side of `src`.
/// `used` are the type names the import copied.
pub fn adopt_newer(buf: &mut Vec<u8>, src: &RootInfo, used: &[String]) -> Result<()> {
    let mut edits: Vec<(String, u8, Vec<u8>)> = Vec::new();

    let current = RootInfo::read(buf)?;
    if let (Some(d), Some(s)) = (&current.version, &src.version) {
        if compare_versions(s, d) == Ordering::Greater {
            edits.push(("VersionNumber".into(), STRING, bson::string_value(s)));
        }
    }

    let flags = merged(buf, "FeatureFlags", &src.flags, |_| true)?;
    if let Some(doc) = flags {
        edits.push(("FeatureFlags".into(), DOCUMENT, doc));
    }
    let versions = merged(buf, "TypeVersions", &src.type_versions, |n| {
        used.iter().any(|u| u == n)
    })?;
    if let Some(doc) = versions {
        edits.push(("TypeVersions".into(), DOCUMENT, doc));
    }
    if !edits.is_empty() {
        typetable::replace_root_fields(buf, &edits)?;
    }
    Ok(())
}

/// The root document `key` with each `(name, value)` of `src` that `take`
/// accepts merged in: a larger value replaces the existing one (keeping its
/// BSON type), a missing name is appended as int64. `None` when nothing
/// changes.
fn merged(
    buf: &[u8],
    key: &str,
    src: &[(String, i64)],
    take: impl Fn(&str) -> bool,
) -> Result<Option<Vec<u8>>> {
    let existing = match datatree::field(buf, 0, key)? {
        Some(el) if el.ty == DOCUMENT => bson::elements(buf, el.value_at)?,
        // Not a document: left as it is.
        Some(_) => return Ok(None),
        None => Vec::new(),
    };
    let mut changed = false;
    let mut body = Vec::new();
    for el in &existing {
        let Some(cur) = int_of(el) else {
            // Not an integer: kept as it is, and not replaced.
            body.extend_from_slice(el.raw);
            continue;
        };
        match src.iter().find(|(n, _)| n == el.key) {
            Some((_, v)) if take(el.key) && *v > cur => {
                changed = true;
                match el.ty {
                    BOOL if *v <= 1 => {
                        bson::push_element(&mut body, BOOL, el.key, &[u8::from(*v != 0)])
                    }
                    INT32 if i32::try_from(*v).is_ok() => bson::push_element(
                        &mut body,
                        INT32,
                        el.key,
                        &typetable::int_bytes(INT32, *v)?,
                    ),
                    // A value the existing type cannot hold is written as int64.
                    _ => bson::push_element(&mut body, INT64, el.key, &bson::i64_value(*v)),
                }
            }
            _ => body.extend_from_slice(el.raw),
        }
    }
    for (name, v) in src {
        if take(name) && !existing.iter().any(|e| e.key == name) {
            changed = true;
            bson::push_element(&mut body, INT64, name, &bson::i64_value(*v));
        }
    }
    if changed {
        Ok(Some(bson::finish_doc(&body)?))
    } else {
        Ok(None)
    }
}

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

    #[test]
    fn versions_compare_as_numbers() {
        assert_eq!(
            compare_versions("2026.9.18.82", "2026.9.8.100"),
            Ordering::Greater
        );
        assert_eq!(
            compare_versions("2024.7.25.1284", "2026.7.30.1243"),
            Ordering::Less
        );
        assert_eq!(
            compare_versions("2026.9.18", "2026.9.18.0"),
            Ordering::Equal
        );
        assert_eq!(
            compare_versions("2026.9.18.82", "2026.9.18.82"),
            Ordering::Equal
        );
        // A text part sorts after every number, so the order is consistent.
        assert_eq!(compare_versions("1.1.5", "1.1.10x"), Ordering::Less);
        assert_eq!(compare_versions("1.1.10", "1.1.10x"), Ordering::Less);
        assert_eq!(compare_versions("1.1.5", "1.1.10"), Ordering::Less);
        assert_eq!(compare_versions("1.1.b", "1.1.a"), Ordering::Greater);
    }
}