Skip to main content

rustduck_core/
section_file.rs

1use std::path::Path;
2use std::rc::Rc;
3
4use rustduck_sys::bridge::ffi;
5
6use crate::buffer::{decode_utf16, encode_utf16};
7use crate::error::native_exception;
8use crate::{DuckContext, Error, Result};
9
10/// CRC handling mode used when loading binary sections.
11#[repr(i32)]
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum CrcValidation {
15    /// Do not validate CRC values.
16    Ignore = 0,
17    /// Validate existing CRC values.
18    Check = 1,
19    /// Compute missing CRC values.
20    Compute = 2,
21}
22
23/// In-memory TSDuck section-file container.
24///
25/// `SectionFile` is `!Send + !Sync`. Its native owner is dropped before the
26/// retained [`DuckContext`], preserving the native borrowed-context lifetime.
27pub struct SectionFile {
28    native: cxx::UniquePtr<ffi::RustDuckSectionFile>,
29    duck: Rc<DuckContext>,
30}
31
32impl SectionFile {
33    /// Creates an empty section-file container borrowing `duck`.
34    pub fn new(duck: Rc<DuckContext>) -> Result<Self> {
35        let native = ffi::rustduck_section_file_new(duck.native())
36            .map_err(|error| native_exception("SectionFile::new", error))?;
37        if native.is_null() {
38            return Err(Error::NativeFailure {
39                operation: "SectionFile::new",
40            });
41        }
42        Ok(Self { native, duck })
43    }
44
45    /// Returns the retained context.
46    pub fn duck_context(&self) -> &Rc<DuckContext> {
47        &self.duck
48    }
49
50    /// Clears all loaded sections.
51    pub fn clear(&mut self) -> Result<()> {
52        ffi::rustduck_section_file_clear(self.native.pin_mut())
53            .map_err(|error| native_exception("SectionFile::clear", error))
54    }
55
56    /// Returns serialized binary size in bytes.
57    pub fn binary_size(&self) -> Result<usize> {
58        ffi::rustduck_section_file_binary_size(self.native())
59            .map_err(|error| native_exception("SectionFile::binary_size", error))
60    }
61
62    /// Returns the number of sections.
63    pub fn sections_count(&self) -> Result<usize> {
64        ffi::rustduck_section_file_sections_count(self.native())
65            .map_err(|error| native_exception("SectionFile::sections_count", error))
66    }
67
68    /// Returns the number of tables.
69    pub fn tables_count(&self) -> Result<usize> {
70        ffi::rustduck_section_file_tables_count(self.native())
71            .map_err(|error| native_exception("SectionFile::tables_count", error))
72    }
73
74    /// Sets CRC handling for subsequent binary loads.
75    pub fn set_crc_validation(&mut self, mode: CrcValidation) -> Result<()> {
76        ffi::rustduck_section_file_set_crc_validation(self.native.pin_mut(), mode as i32)
77            .map_err(|error| native_exception("SectionFile::set_crc_validation", error))
78    }
79
80    /// Loads binary sections from memory.
81    pub fn load_binary_buffer(&mut self, data: &[u8]) -> Result<()> {
82        ffi::rustduck_section_file_load_binary_buffer(self.native.pin_mut(), data)
83            .map_err(|error| native_exception("SectionFile::load_binary_buffer", error))?
84            .then_some(())
85            .ok_or(Error::NativeFailure {
86                operation: "SectionFile::load_binary_buffer",
87            })
88    }
89
90    /// Serializes all sections as binary data.
91    pub fn to_binary(&self) -> Result<Vec<u8>> {
92        ffi::rustduck_section_file_to_binary(self.native())
93            .map_err(|error| native_exception("SectionFile::to_binary", error))
94    }
95
96    /// Loads binary sections from a filesystem path.
97    pub fn load_binary(&mut self, path: &Path) -> Result<()> {
98        let path = native_path(path)?;
99        ffi::rustduck_section_file_load_binary(self.native.pin_mut(), &path)
100            .map_err(|error| native_exception("SectionFile::load_binary", error))?
101            .then_some(())
102            .ok_or(Error::NativeFailure {
103                operation: "SectionFile::load_binary",
104            })
105    }
106
107    /// Saves binary sections to a filesystem path.
108    pub fn save_binary(&self, path: &Path) -> Result<()> {
109        self.save_path(
110            path,
111            "SectionFile::save_binary",
112            ffi::rustduck_section_file_save_binary,
113        )
114    }
115
116    /// Loads XML from a file path or inline XML document accepted by TSDuck.
117    pub fn load_xml(&mut self, source: &str) -> Result<()> {
118        let source = encode_utf16(source);
119        ffi::rustduck_section_file_load_xml(self.native.pin_mut(), &source)
120            .map_err(|error| native_exception("SectionFile::load_xml", error))?
121            .then_some(())
122            .ok_or(Error::NativeFailure {
123                operation: "SectionFile::load_xml",
124            })
125    }
126
127    /// Saves XML to a filesystem path.
128    pub fn save_xml(&self, path: &Path) -> Result<()> {
129        self.save_path(
130            path,
131            "SectionFile::save_xml",
132            ffi::rustduck_section_file_save_xml,
133        )
134    }
135
136    /// Saves JSON to a filesystem path.
137    pub fn save_json(&self, path: &Path) -> Result<()> {
138        self.save_path(
139            path,
140            "SectionFile::save_json",
141            ffi::rustduck_section_file_save_json,
142        )
143    }
144
145    /// Serializes the container as XML.
146    pub fn to_xml(&self) -> Result<String> {
147        let bytes = ffi::rustduck_section_file_to_xml_utf16(self.native())
148            .map_err(|error| native_exception("SectionFile::to_xml", error))?;
149        decode_utf16("SectionFile::to_xml", &bytes)
150    }
151
152    /// Serializes the container as JSON.
153    pub fn to_json(&self) -> Result<String> {
154        let bytes = ffi::rustduck_section_file_to_json_utf16(self.native())
155            .map_err(|error| native_exception("SectionFile::to_json", error))?;
156        decode_utf16("SectionFile::to_json", &bytes)
157    }
158
159    fn save_path(
160        &self,
161        path: &Path,
162        operation: &'static str,
163        save: fn(&ffi::RustDuckSectionFile, &[u8]) -> std::result::Result<bool, cxx::Exception>,
164    ) -> Result<()> {
165        let path = native_path(path)?;
166        save(self.native(), &path)
167            .map_err(|error| native_exception(operation, error))?
168            .then_some(())
169            .ok_or(Error::NativeFailure { operation })
170    }
171
172    fn native(&self) -> &ffi::RustDuckSectionFile {
173        self.native
174            .as_ref()
175            .expect("SectionFile construction rejects null owners")
176    }
177}
178
179fn native_path(path: &Path) -> Result<Vec<u8>> {
180    let path = path.to_str().ok_or_else(|| Error::InvalidArgument {
181        field: "path",
182        message: "must be valid UTF-8 for TSDuck's UTF-16 file API".to_owned(),
183    })?;
184    Ok(encode_utf16(path))
185}