rustduck-core 1.1.0

Safe typed TSDuck core bindings for rustduck
Documentation
use std::path::Path;
use std::rc::Rc;

use rustduck_sys::bridge::ffi;

use crate::buffer::{decode_utf16, encode_utf16};
use crate::error::native_exception;
use crate::{DuckContext, Error, Result};

/// CRC handling mode used when loading binary sections.
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CrcValidation {
    /// Do not validate CRC values.
    Ignore = 0,
    /// Validate existing CRC values.
    Check = 1,
    /// Compute missing CRC values.
    Compute = 2,
}

/// In-memory TSDuck section-file container.
///
/// `SectionFile` is `!Send + !Sync`. Its native owner is dropped before the
/// retained [`DuckContext`], preserving the native borrowed-context lifetime.
pub struct SectionFile {
    native: cxx::UniquePtr<ffi::RustDuckSectionFile>,
    duck: Rc<DuckContext>,
}

impl SectionFile {
    /// Creates an empty section-file container borrowing `duck`.
    pub fn new(duck: Rc<DuckContext>) -> Result<Self> {
        let native = ffi::rustduck_section_file_new(duck.native())
            .map_err(|error| native_exception("SectionFile::new", error))?;
        if native.is_null() {
            return Err(Error::NativeFailure {
                operation: "SectionFile::new",
            });
        }
        Ok(Self { native, duck })
    }

    /// Returns the retained context.
    pub fn duck_context(&self) -> &Rc<DuckContext> {
        &self.duck
    }

    /// Clears all loaded sections.
    pub fn clear(&mut self) -> Result<()> {
        ffi::rustduck_section_file_clear(self.native.pin_mut())
            .map_err(|error| native_exception("SectionFile::clear", error))
    }

    /// Returns serialized binary size in bytes.
    pub fn binary_size(&self) -> Result<usize> {
        ffi::rustduck_section_file_binary_size(self.native())
            .map_err(|error| native_exception("SectionFile::binary_size", error))
    }

    /// Returns the number of sections.
    pub fn sections_count(&self) -> Result<usize> {
        ffi::rustduck_section_file_sections_count(self.native())
            .map_err(|error| native_exception("SectionFile::sections_count", error))
    }

    /// Returns the number of tables.
    pub fn tables_count(&self) -> Result<usize> {
        ffi::rustduck_section_file_tables_count(self.native())
            .map_err(|error| native_exception("SectionFile::tables_count", error))
    }

    /// Sets CRC handling for subsequent binary loads.
    pub fn set_crc_validation(&mut self, mode: CrcValidation) -> Result<()> {
        ffi::rustduck_section_file_set_crc_validation(self.native.pin_mut(), mode as i32)
            .map_err(|error| native_exception("SectionFile::set_crc_validation", error))
    }

    /// Loads binary sections from memory.
    pub fn load_binary_buffer(&mut self, data: &[u8]) -> Result<()> {
        ffi::rustduck_section_file_load_binary_buffer(self.native.pin_mut(), data)
            .map_err(|error| native_exception("SectionFile::load_binary_buffer", error))?
            .then_some(())
            .ok_or(Error::NativeFailure {
                operation: "SectionFile::load_binary_buffer",
            })
    }

    /// Serializes all sections as binary data.
    pub fn to_binary(&self) -> Result<Vec<u8>> {
        ffi::rustduck_section_file_to_binary(self.native())
            .map_err(|error| native_exception("SectionFile::to_binary", error))
    }

    /// Loads binary sections from a filesystem path.
    pub fn load_binary(&mut self, path: &Path) -> Result<()> {
        let path = native_path(path)?;
        ffi::rustduck_section_file_load_binary(self.native.pin_mut(), &path)
            .map_err(|error| native_exception("SectionFile::load_binary", error))?
            .then_some(())
            .ok_or(Error::NativeFailure {
                operation: "SectionFile::load_binary",
            })
    }

    /// Saves binary sections to a filesystem path.
    pub fn save_binary(&self, path: &Path) -> Result<()> {
        self.save_path(
            path,
            "SectionFile::save_binary",
            ffi::rustduck_section_file_save_binary,
        )
    }

    /// Loads XML from a file path or inline XML document accepted by TSDuck.
    pub fn load_xml(&mut self, source: &str) -> Result<()> {
        let source = encode_utf16(source);
        ffi::rustduck_section_file_load_xml(self.native.pin_mut(), &source)
            .map_err(|error| native_exception("SectionFile::load_xml", error))?
            .then_some(())
            .ok_or(Error::NativeFailure {
                operation: "SectionFile::load_xml",
            })
    }

    /// Saves XML to a filesystem path.
    pub fn save_xml(&self, path: &Path) -> Result<()> {
        self.save_path(
            path,
            "SectionFile::save_xml",
            ffi::rustduck_section_file_save_xml,
        )
    }

    /// Saves JSON to a filesystem path.
    pub fn save_json(&self, path: &Path) -> Result<()> {
        self.save_path(
            path,
            "SectionFile::save_json",
            ffi::rustduck_section_file_save_json,
        )
    }

    /// Serializes the container as XML.
    pub fn to_xml(&self) -> Result<String> {
        let bytes = ffi::rustduck_section_file_to_xml_utf16(self.native())
            .map_err(|error| native_exception("SectionFile::to_xml", error))?;
        decode_utf16("SectionFile::to_xml", &bytes)
    }

    /// Serializes the container as JSON.
    pub fn to_json(&self) -> Result<String> {
        let bytes = ffi::rustduck_section_file_to_json_utf16(self.native())
            .map_err(|error| native_exception("SectionFile::to_json", error))?;
        decode_utf16("SectionFile::to_json", &bytes)
    }

    fn save_path(
        &self,
        path: &Path,
        operation: &'static str,
        save: fn(&ffi::RustDuckSectionFile, &[u8]) -> std::result::Result<bool, cxx::Exception>,
    ) -> Result<()> {
        let path = native_path(path)?;
        save(self.native(), &path)
            .map_err(|error| native_exception(operation, error))?
            .then_some(())
            .ok_or(Error::NativeFailure { operation })
    }

    fn native(&self) -> &ffi::RustDuckSectionFile {
        self.native
            .as_ref()
            .expect("SectionFile construction rejects null owners")
    }
}

fn native_path(path: &Path) -> Result<Vec<u8>> {
    let path = path.to_str().ok_or_else(|| Error::InvalidArgument {
        field: "path",
        message: "must be valid UTF-8 for TSDuck's UTF-16 file API".to_owned(),
    })?;
    Ok(encode_utf16(path))
}