Skip to main content

powerio_capi/
collection.rs

1//! Collection transport and metadata; electrical values keep typed module ownership.
2use super::*;
3
4fn limits(max_bytes: u64, max_files: usize) -> Result<powerio::CollectionLimits, *mut PioError> {
5    // The caller sets the totals; depth and ratio keep the facade defaults.
6    let mut limits = powerio::CollectionLimits::default();
7    limits.tree = powerio::SourceTreeLimits::new(
8        max_files,
9        max_bytes,
10        powerio::SourceTreeLimits::default().max_depth(),
11    )
12    .map_err(|e| error_from_core(&e))?;
13    limits.archive = powerio::collection::ArchiveLimits::new(
14        max_bytes,
15        max_files,
16        max_bytes,
17        powerio::collection::ArchiveLimits::default().max_ratio(),
18    )
19    .map_err(|e| error_from_core(&e))?;
20    Ok(limits)
21}
22fn invalid(message: &str) -> *mut PioError {
23    boundary_error(&codes::BIND_CAPI_INVALID_ARGUMENT, message)
24}
25unsafe fn collection<'a>(
26    raw: *const PioCollection,
27) -> Result<&'a powerio::Collection, *mut PioError> {
28    unsafe { PioCollection::get(raw) }.ok_or_else(|| {
29        boundary_error(
30            &codes::BIND_CAPI_NULL_HANDLE,
31            "PioCollection must not be NULL",
32        )
33    })
34}
35
36/// Acquire a folder or ZIP with explicit total byte and file limits.
37/// # Safety
38/// Pointers and handles must satisfy the crate-level safety requirements.
39#[unsafe(no_mangle)]
40pub unsafe extern "C" fn pio_collection_open(
41    path: *const c_char,
42    path_len: usize,
43    max_bytes: u64,
44    max_files: usize,
45    error: *mut *mut PioError,
46) -> *mut PioCollection {
47    unsafe {
48        entry(error, std::ptr::null_mut(), || {
49            let limits = limits(max_bytes, max_files)?;
50            powerio::Collection::open(required_str(path, path_len, "path")?, limits)
51                .map(PioCollection::new_raw)
52                .map_err(|e| error_from_core(&e))
53        })
54    }
55}
56
57/// Copy and verify a ZIP, bounding compressed input before copying.
58/// # Safety
59/// Pointers and handles must satisfy the crate-level safety requirements.
60#[unsafe(no_mangle)]
61pub unsafe extern "C" fn pio_collection_from_zip(
62    name: *const c_char,
63    name_len: usize,
64    data: *const u8,
65    data_len: usize,
66    max_bytes: u64,
67    max_files: usize,
68    error: *mut *mut PioError,
69) -> *mut PioCollection {
70    unsafe {
71        entry(error, std::ptr::null_mut(), || {
72            let limits = limits(max_bytes, max_files)?;
73            if data_len as u64 > max_bytes {
74                return Err(invalid("collection compressed byte limit exceeded"));
75            }
76            let name = required_str(name, name_len, "name")?;
77            let bytes = Arc::from(input_bytes(data, data_len, "data")?);
78            powerio::Collection::from_zip(name, bytes, limits)
79                .map(PioCollection::new_raw)
80                .map_err(|e| error_from_core(&e))
81        })
82    }
83}
84
85/// Copy named buffers once into a shared immutable inventory. Checks count and
86/// cumulative bytes before copying payloads. No host fallback is possible.
87/// # Safety
88/// Pointers and handles must satisfy the crate-level safety requirements.
89/// buffers addresses buffers_len views; NULL is valid only at zero length.
90#[unsafe(no_mangle)]
91pub unsafe extern "C" fn pio_collection_from_files(
92    name: *const c_char,
93    name_len: usize,
94    buffers: *const PioNamedBufferView,
95    buffers_len: usize,
96    max_bytes: u64,
97    max_files: usize,
98    error: *mut *mut PioError,
99) -> *mut PioCollection {
100    unsafe {
101        entry(error, std::ptr::null_mut(), || {
102            let limits = limits(max_bytes, max_files)?;
103            if buffers_len > max_files {
104                return Err(invalid("collection file limit exceeded"));
105            }
106            let name = required_str(name, name_len, "name")?;
107            let buffers = if buffers_len == 0 {
108                &[]
109            } else if buffers.is_null() {
110                return Err(invalid("buffers is NULL with a nonzero length"));
111            } else {
112                std::slice::from_raw_parts(buffers, buffers_len)
113            };
114            let total = buffers
115                .iter()
116                .try_fold(0u64, |n, b| n.checked_add(b.bytes.len as u64));
117            if total.is_none_or(|n| n > max_bytes) {
118                return Err(invalid("collection byte limit exceeded"));
119            }
120            let files = buffers
121                .iter()
122                .map(|b| {
123                    let path = powerio::ArtifactPath::new(required_str(
124                        b.name.data,
125                        b.name.len,
126                        "buffer name",
127                    )?)
128                    .map_err(|e| error_from_core(&e))?;
129                    let bytes = Arc::from(input_bytes(b.bytes.data, b.bytes.len, "buffer bytes")?);
130                    Ok((path, bytes))
131                })
132                .collect::<Result<Vec<_>, *mut PioError>>()?;
133            powerio::Collection::from_files(name, files, limits)
134                .map(PioCollection::new_raw)
135                .map_err(|e| error_from_core(&e))
136        })
137    }
138}
139
140/// Inspect metadata and suggested selections as JSON, without electrical parsing.
141/// Release the returned owned string with pio_string_release.
142/// # Safety
143/// Pointers and handles must satisfy the crate-level safety requirements.
144#[unsafe(no_mangle)]
145pub unsafe extern "C" fn pio_collection_inspect(
146    raw: *const PioCollection,
147    error: *mut *mut PioError,
148) -> *mut PioString {
149    unsafe {
150        entry(error, std::ptr::null_mut(), || {
151            let collection = collection(raw)?;
152            let candidates = collection.inspect().map_err(|e| error_from_core(&e))?;
153            Ok(PioString::new_raw(StringInner {
154                text: serde_json::json!({
155                    "entries":collection.entries(), "candidates":candidates,
156                })
157                .to_string(),
158            }))
159        })
160    }
161}
162
163/// Parse one JSON selection (at most 1 MiB) into an owned typed module. Optional
164/// options have the same semantics as pio_parse_with_options, but cannot acquire
165/// host files. If report is non-NULL, success also returns an owned JSON string
166/// containing observed dependencies and the incomplete flag. Release it with
167/// pio_string_release. False incomplete is not a completeness certificate.
168/// # Safety
169/// Pointers and handles must satisfy the crate-level safety requirements.
170/// Non-NULL options and report must be valid for their declared types. Report
171/// is cleared before work; its prior value must already have been released.
172#[unsafe(no_mangle)]
173pub unsafe extern "C" fn pio_collection_parse(
174    raw: *const PioCollection,
175    selection: *const c_char,
176    selection_len: usize,
177    options: *const PioParseOptions,
178    report: *mut *mut PioString,
179    error: *mut *mut PioError,
180) -> *mut PioModule {
181    unsafe {
182        if !report.is_null() {
183            *report = std::ptr::null_mut();
184        }
185        entry(error, std::ptr::null_mut(), || {
186            let collection = collection(raw)?;
187            if selection_len > 1 << 20 {
188                return Err(invalid("selection metadata exceeds 1 MiB"));
189            }
190            let selected =
191                serde_json::from_str(required_str(selection, selection_len, "selection")?)
192                    .map_err(|e| invalid(&format!("invalid collection selection: {e}")))?;
193            let mut parsed_options = powerio::ParseOptions::default();
194            apply_parse_selections(&mut parsed_options, options)?;
195            let result = collection
196                .parse(&selected, &parsed_options)
197                .map_err(|e| error_from_core(&e))?;
198            let metadata = serde_json::json!({"dependencies":result.dependencies,"incomplete":result.incomplete}).to_string();
199            let module = module_handle(result.module);
200            if !report.is_null() {
201                *report = PioString::new_raw(StringInner { text: metadata });
202            }
203            Ok(module)
204        })
205    }
206}
207
208/// Retain an independently releasable collection handle.
209/// # Safety
210/// Pointers and handles must satisfy the crate-level safety requirements.
211#[unsafe(no_mangle)]
212pub unsafe extern "C" fn pio_collection_retain(raw: *const PioCollection) -> *mut PioCollection {
213    unsafe { PioCollection::retain_raw(raw) }
214}
215/// Release one owned collection handle. Parsed modules retain their own source.
216/// # Safety
217/// Pointers and handles must satisfy the crate-level safety requirements.
218#[unsafe(no_mangle)]
219pub unsafe extern "C" fn pio_collection_release(raw: *mut PioCollection) {
220    unsafe { PioCollection::release_raw(raw) }
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226    #[test]
227    fn ownership_observations_and_failed_selection_are_independent() {
228        unsafe {
229            let primary =
230                b"New Circuit.day basekv=12.47 bus1=source\nRedirect ../shared/topology.inc\n";
231            let topology =
232                b"New Line.l bus1=source bus2=load phases=3 r1=0.1 x1=0.2 r0=0.3 x0=0.4 length=1\n";
233            let files = [
234                PioNamedBufferView {
235                    name: PioStringView::new("masters/day.dss"),
236                    bytes: PioByteView::new(primary),
237                },
238                PioNamedBufferView {
239                    name: PioStringView::new("masters/night.dss"),
240                    bytes: PioByteView::new(primary),
241                },
242                PioNamedBufferView {
243                    name: PioStringView::new("shared/topology.inc"),
244                    bytes: PioByteView::new(topology),
245                },
246            ];
247            let mut error = std::ptr::null_mut();
248            let collection = pio_collection_from_files(
249                b"study".as_ptr().cast(),
250                5,
251                files.as_ptr(),
252                files.len(),
253                4096,
254                10,
255                &mut error,
256            );
257            assert!(error.is_null());
258            assert!(!collection.is_null());
259            let retained = pio_collection_retain(collection);
260            pio_collection_release(collection);
261            let inventory = pio_collection_inspect(retained, &mut error);
262            assert!(error.is_null());
263            assert!(!inventory.is_null());
264            pio_string_release(inventory);
265            let mut report = std::ptr::null_mut();
266            let bad = br#"{"primary":"../escape.dss"}"#;
267            assert!(
268                pio_collection_parse(
269                    retained,
270                    bad.as_ptr().cast(),
271                    bad.len(),
272                    std::ptr::null(),
273                    &mut report,
274                    &mut error
275                )
276                .is_null()
277            );
278            assert!(!error.is_null());
279            assert!(report.is_null());
280            pio_error_release(error);
281            let selection = br#"{"primary":"masters/night.dss","format":"dss"}"#;
282            let module = pio_collection_parse(
283                retained,
284                selection.as_ptr().cast(),
285                selection.len(),
286                std::ptr::null(),
287                &mut report,
288                &mut error,
289            );
290            assert!(error.is_null());
291            assert!(!module.is_null());
292            let metadata: serde_json::Value =
293                serde_json::from_str(&PioString::get(report).unwrap().text).unwrap();
294            assert_eq!(
295                metadata["dependencies"],
296                serde_json::json!(["shared/topology.inc"])
297            );
298            assert_eq!(metadata["incomplete"], false);
299            pio_string_release(report);
300            pio_collection_release(retained);
301            let value = pio_module_value(module);
302            pio_module_release(module);
303            assert!(pio_value_is_type(
304                value,
305                b"powerio.MulticonductorNetwork".as_ptr().cast(),
306                29
307            ));
308            pio_value_release(value);
309        }
310    }
311    #[test]
312    fn rejects_null_and_oversize_inputs_before_copy() {
313        unsafe {
314            let mut error = std::ptr::null_mut();
315            assert!(
316                pio_collection_from_zip(
317                    b"x.zip".as_ptr().cast(),
318                    5,
319                    std::ptr::null(),
320                    100,
321                    10,
322                    10,
323                    &mut error
324                )
325                .is_null()
326            );
327            assert!(!error.is_null());
328            pio_error_release(error);
329            assert!(
330                pio_collection_from_files(
331                    b"x".as_ptr().cast(),
332                    1,
333                    std::ptr::null(),
334                    1,
335                    10,
336                    10,
337                    &mut error
338                )
339                .is_null()
340            );
341            assert!(!error.is_null());
342            pio_error_release(error);
343            assert!(pio_collection_inspect(std::ptr::null(), &mut error).is_null());
344            assert!(!error.is_null());
345            pio_error_release(error);
346            pio_collection_release(std::ptr::null_mut());
347        }
348    }
349}