frdt 0.2.0

Edit and inspect Resonite FrDT (.brson) documents without expanding them to JSON
Documentation
//! FrDT header and Brotli payload.
//!
//! ```text
//! 46 72 44 54  00 00 00 00  03
//! F  r  D  T   reserved     compression (7-bit, Brotli = 0x03)
//! ```
//!
//! The compression code is a .NET 7-bit integer. `0x03` fits in one byte, so a
//! normal Brotli file is a 9-byte header plus the payload. Other methods are
//! rejected. Writes always emit the 9-byte form at Brotli quality 4, 5, or 6.

use std::io::{Cursor, Read, Write};

use crate::error::{Error, Result};

pub const MAGIC: &[u8; 4] = b"FrDT";
pub const RESERVED: [u8; 4] = [0, 0, 0, 0];
pub const BROTLI: u64 = 0x03;
pub const DEFAULT_QUALITY: u32 = 5;
pub const HEADER9: [u8; 9] = [0x46, 0x72, 0x44, 0x54, 0x00, 0x00, 0x00, 0x00, 0x03];

/// Split an FrDT header. Returns the compressed payload.
pub fn split_header(input: &[u8]) -> Result<&[u8]> {
    if input.len() < 9 {
        return Err(Error::Truncated);
    }
    if &input[0..4] != MAGIC {
        return Err(Error::BadMagic);
    }
    if input[4..8] != RESERVED {
        return Err(Error::BadReserved);
    }
    let (method, rest) = read_7bit(&input[8..])?;
    if method != BROTLI {
        return Err(Error::UnsupportedCompression(method));
    }
    Ok(rest)
}

pub fn decompress(input: &[u8]) -> Result<Vec<u8>> {
    let payload = split_header(input)?;
    decompress_brotli(payload)
}

pub fn decompress_brotli(payload: &[u8]) -> Result<Vec<u8>> {
    let mut out = Vec::new();
    brotli::Decompressor::new(Cursor::new(payload), 16 * 1024)
        .read_to_end(&mut out)
        .map_err(|e| Error::Invalid(format!("brotli: {e}")))?;
    Ok(out)
}

/// Streaming Brotli decoder over the payload that follows a valid FrDT header.
pub fn brotli_reader(payload: &[u8]) -> brotli::Decompressor<Cursor<&[u8]>> {
    brotli::Decompressor::new(Cursor::new(payload), 16 * 1024)
}

pub fn compress_brotli(bson: &[u8], quality: u32) -> Result<Vec<u8>> {
    if !(4..=6).contains(&quality) {
        return Err(Error::BadQuality);
    }
    // Node's brotli window is 22. Quality is the part we lower.
    let params = brotli::enc::BrotliEncoderParams {
        quality: quality as i32,
        lgwin: 22,
        ..Default::default()
    };
    let mut input = Cursor::new(bson);
    let mut output = Vec::new();
    brotli::BrotliCompress(&mut input, &mut output, &params).map_err(Error::Io)?;
    Ok(output)
}

pub fn write_brson<W: Write>(bson: &[u8], mut out: W, quality: u32) -> Result<()> {
    let compressed = compress_brotli(bson, quality)?;
    out.write_all(&HEADER9)?;
    out.write_all(&compressed)?;
    Ok(())
}

/// .NET `BinaryReader` 7-bit unsigned integer.
pub fn read_7bit(input: &[u8]) -> Result<(u64, &[u8])> {
    let mut result = 0u64;
    let mut shift = 0;
    for (i, byte) in input.iter().copied().enumerate() {
        if shift >= 64 {
            return Err(Error::Invalid("compression varint is too long".into()));
        }
        result |= u64::from(byte & 0x7f) << shift;
        if byte & 0x80 == 0 {
            return Ok((result, &input[i + 1..]));
        }
        shift += 7;
        if i == 9 {
            return Err(Error::Invalid("compression varint is too long".into()));
        }
    }
    Err(Error::Truncated)
}

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

    #[test]
    fn header_roundtrip_and_rejects_other_methods() {
        let bson = {
            let mut d = crate::bson::DocBuf::new();
            d.double("n", f64::INFINITY);
            d.finish()
        };
        let mut file = Vec::new();
        write_brson(&bson, &mut file, 5).unwrap();
        assert_eq!(&file[..9], &HEADER9);
        let back = decompress(&file).unwrap();
        assert_eq!(back, bson);

        let mut lz4 = HEADER9;
        lz4[8] = 0x01;
        assert!(matches!(
            split_header(&lz4),
            Err(Error::UnsupportedCompression(1))
        ));
    }

    #[test]
    fn seven_bit_three_may_use_two_bytes() {
        // 0x83 0x00 is still the integer 3.
        let mut input = vec![0x46, 0x72, 0x44, 0x54, 0, 0, 0, 0, 0x83, 0x00];
        let bson = {
            let mut d = crate::bson::DocBuf::new();
            d.int32("v", 1);
            d.finish()
        };
        input.extend(compress_brotli(&bson, 4).unwrap());
        assert_eq!(decompress(&input).unwrap(), bson);
    }
}