Skip to main content

readcon_core/
ffi.rs

1use crate::correspondence::{self, IdentityCheck};
2use crate::helpers::symbol_to_atomic_number;
3use crate::iterators::{self, ConFrameIterator};
4use crate::types::{ConFrame, ConFrameBuilder, meta};
5use crate::writer::{ConFrameWriter, binding_rewrite_frame};
6use std::cell::RefCell;
7use std::ffi::{CStr, CString, c_char};
8use std::fs::File;
9use std::path::Path;
10use std::ptr;
11//=============================================================================
12// Version & Spec Constants (exported as #define by cbindgen)
13//=============================================================================
14/// Breaking-change major for the public C ABI.
15pub const RKR_ABI_VERSION_MAJOR: u32 = 1;
16/// Additive-change minor for the public C ABI.
17pub const RKR_ABI_VERSION_MINOR: u32 = 1;
18/// Layout revision for opaque handles and exported records.
19pub const RKR_ABI_LAYOUT_REVISION: u32 = 1;
20
21/// Returns the breaking-change major for the public C ABI.
22#[unsafe(no_mangle)]
23pub extern "C" fn rkr_abi_version_major() -> u32 {
24    RKR_ABI_VERSION_MAJOR
25}
26
27/// Returns the additive-change minor for the public C ABI.
28#[unsafe(no_mangle)]
29pub extern "C" fn rkr_abi_version_minor() -> u32 {
30    RKR_ABI_VERSION_MINOR
31}
32
33/// Returns the opaque-handle and exported-record layout revision.
34#[unsafe(no_mangle)]
35pub extern "C" fn rkr_abi_layout_revision() -> u32 {
36    RKR_ABI_LAYOUT_REVISION
37}
38
39/// Returns the stable human-readable ABI negotiation stamp.
40#[unsafe(no_mangle)]
41pub extern "C" fn rkr_abi_stamp() -> *const c_char {
42    const STAMP: &[u8] = b"readcon-core/abi-1.1/layout-1\0";
43    STAMP.as_ptr() as *const c_char
44}
45
46/// CON/convel format spec version. Use `#if RKR_CON_SPEC_VERSION >= 2` in C/C++
47/// to gate code that depends on atom_index semantics.
48///
49/// Tracks `crate::CON_SPEC_VERSION` (which the Rust API exposes as
50/// `CON_SPEC_VERSION`). Both macros are emitted into the C header for
51/// the convenience of either naming convention; they always carry the
52/// same value.
53pub const RKR_CON_SPEC_VERSION: u32 = 3;
54/// Returns the spec version at runtime (for dynamically linked consumers).
55#[unsafe(no_mangle)]
56pub extern "C" fn rkr_con_spec_version() -> u32 {
57    crate::CON_SPEC_VERSION
58}
59/// Returns a pointer to a static, null-terminated library version string.
60/// The returned pointer is valid for the lifetime of the process. Do NOT free it.
61#[unsafe(no_mangle)]
62pub extern "C" fn rkr_library_version() -> *const c_char {
63    // concat! produces a &'static str with a trailing NUL byte
64    const VERSION_NUL: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes();
65    VERSION_NUL.as_ptr() as *const c_char
66}
67/// Returns the position of an atom inside the frame's `atom_data` array
68/// matching the given `atom_id`. Returns `UINT64_MAX` if no atom with
69/// that id exists or `frame_handle` is NULL.
70///
71/// O(N) per call. C/C++ consumers performing many lookups should cache
72/// a `std::unordered_map<uint64_t, size_t>` from a single sweep over
73/// the frame.
74///
75/// # Safety
76///
77/// `frame_handle` must point to a valid `RKRConFrame` allocation.
78#[unsafe(no_mangle)]
79pub unsafe extern "C" fn rkr_frame_atom_index_by_id(
80    frame_handle: *const RKRConFrame,
81    atom_id: u64,
82) -> u64 {
83    let frame = match unsafe { (frame_handle as *const ConFrame).as_ref() } {
84        Some(f) => f,
85        None => return u64::MAX,
86    };
87    match frame.atom_index_by_id(atom_id) {
88        Some(idx) => idx as u64,
89        None => u64::MAX,
90    }
91}
92
93fn identity_check(strict: u8) -> IdentityCheck {
94    if strict == 0 {
95        IdentityCheck::Lenient
96    } else {
97        IdentityCheck::Strict
98    }
99}
100
101fn correspondence_fail(err: &correspondence::CorrespondenceError) -> RKRStatus {
102    let frame = err.frame_index().unwrap_or(0) as u64;
103    set_last_error(
104        RKRStatus::RKR_STATUS_VALIDATION_ERROR as i32,
105        &err.to_string(),
106        0,
107        frame,
108    );
109    RKRStatus::RKR_STATUS_VALIDATION_ERROR
110}
111
112fn frame_ref<'a>(handle: *const RKRConFrame) -> Option<&'a ConFrame> {
113    unsafe { (handle as *const ConFrame).as_ref() }
114}
115
116/// `perm[i]` is the index in `frame_b` of the atom whose `atom_id` equals
117/// `frame_a`'s atom `i`. `strict == 0` allows mass and fixed-mask
118/// differences. Symbol mismatches, duplicate ids, and missing or extra
119/// ids fail either way. The detail is `rkr_last_error_message`.
120///
121/// # Safety
122/// Both handles are valid. `out_perm` has room for `out_len` `uint64_t`
123/// values when it is non-null. An empty map may pass a null `out_perm`.
124#[unsafe(no_mangle)]
125pub unsafe extern "C" fn rkr_frame_atom_id_permutation(
126    frame_a: *const RKRConFrame,
127    frame_b: *const RKRConFrame,
128    strict: u8,
129    out_perm: *mut u64,
130    out_len: usize,
131) -> RKRStatus {
132    let (Some(reference), Some(other)) = (frame_ref(frame_a), frame_ref(frame_b)) else {
133        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
134    };
135    let perm = match correspondence::atom_id_permutation(reference, other, identity_check(strict)) {
136        Ok(perm) => perm,
137        Err(err) => return correspondence_fail(&err),
138    };
139    if perm.is_empty() {
140        return RKRStatus::RKR_STATUS_SUCCESS;
141    }
142    if out_perm.is_null() {
143        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
144    }
145    if out_len < perm.len() {
146        return note(RKRStatus::RKR_STATUS_BUFFER_TOO_SMALL);
147    }
148    for (i, index) in perm.iter().enumerate() {
149        unsafe { *out_perm.add(i) = *index as u64 };
150    }
151    RKRStatus::RKR_STATUS_SUCCESS
152}
153
154/// Frame B stored in frame A's atom order. The caller owns the handle
155/// and frees it with `free_rkr_frame`. NULL on error; the detail is
156/// `rkr_last_error_message`.
157///
158/// # Safety
159/// Both handles are valid or null.
160#[unsafe(no_mangle)]
161pub unsafe extern "C" fn rkr_frame_reorder_like(
162    frame_a: *const RKRConFrame,
163    frame_b: *const RKRConFrame,
164    strict: u8,
165) -> *mut RKRConFrame {
166    let (Some(reference), Some(other)) = (frame_ref(frame_a), frame_ref(frame_b)) else {
167        return null_err(RKRStatus::RKR_STATUS_NULL_POINTER);
168    };
169    match correspondence::reorder_like(reference, other, identity_check(strict)) {
170        Ok(frame) => Box::into_raw(Box::new(frame)) as *mut RKRConFrame,
171        Err(err) => {
172            correspondence_fail(&err);
173            ptr::null_mut()
174        }
175    }
176}
177
178/// Compare `frames[1..]` with `frames[0]`. On failure writes the first
179/// offending frame index and atom id when the out pointers are non-null,
180/// and returns `RKR_STATUS_VALIDATION_ERROR`. On success those outputs
181/// are `UINT64_MAX` when the pointers are non-null.
182///
183/// # Safety
184/// `frames` points at `nframes` valid frame handles. Out pointers are
185/// null or writable.
186#[unsafe(no_mangle)]
187pub unsafe extern "C" fn rkr_frames_check_atom_ids(
188    frames: *const *const RKRConFrame,
189    nframes: usize,
190    strict: u8,
191    out_frame_index: *mut u64,
192    out_atom_id: *mut u64,
193) -> RKRStatus {
194    if nframes == 0 {
195        write_correspondence_outs(
196            &correspondence::CorrespondenceError::EmptySequence,
197            out_frame_index,
198            out_atom_id,
199        );
200        return correspondence_fail(&correspondence::CorrespondenceError::EmptySequence);
201    }
202    if frames.is_null() {
203        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
204    }
205    let mut refs = Vec::with_capacity(nframes);
206    for i in 0..nframes {
207        let handle = unsafe { *frames.add(i) };
208        let Some(frame) = frame_ref(handle) else {
209            return note(RKRStatus::RKR_STATUS_NULL_POINTER);
210        };
211        refs.push(frame);
212    }
213    match correspondence::check_atom_id_consistency_refs(&refs, identity_check(strict)) {
214        Ok(()) => {
215            if !out_frame_index.is_null() {
216                unsafe { *out_frame_index = u64::MAX };
217            }
218            if !out_atom_id.is_null() {
219                unsafe { *out_atom_id = u64::MAX };
220            }
221            RKRStatus::RKR_STATUS_SUCCESS
222        }
223        Err(err) => {
224            write_correspondence_outs(&err, out_frame_index, out_atom_id);
225            correspondence_fail(&err)
226        }
227    }
228}
229
230fn write_correspondence_outs(
231    err: &correspondence::CorrespondenceError,
232    out_frame_index: *mut u64,
233    out_atom_id: *mut u64,
234) {
235    if !out_frame_index.is_null() {
236        unsafe { *out_frame_index = err.frame_index().unwrap_or(0) as u64 };
237    }
238    if !out_atom_id.is_null() {
239        unsafe { *out_atom_id = err.atom_id().unwrap_or(u64::MAX) };
240    }
241}
242
243/// Row-major `(N, 3)` minimum-image displacements of frame A's atoms
244/// toward the same `atom_id` in frame B. The cell is frame A's.
245/// `out_len` counts doubles and must be at least `3 * N`.
246///
247/// # Safety
248/// Both handles are valid. `out_disp` is writable for `out_len` doubles
249/// when N is not zero.
250#[unsafe(no_mangle)]
251pub unsafe extern "C" fn rkr_frame_minimum_image_displacements(
252    frame_a: *const RKRConFrame,
253    frame_b: *const RKRConFrame,
254    strict: u8,
255    out_disp: *mut f64,
256    out_len: usize,
257) -> RKRStatus {
258    let (Some(reference), Some(other)) = (frame_ref(frame_a), frame_ref(frame_b)) else {
259        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
260    };
261    let rows =
262        match correspondence::minimum_image_displacements(reference, other, identity_check(strict))
263        {
264            Ok(rows) => rows,
265            Err(err) => return correspondence_fail(&err),
266        };
267    if rows.is_empty() {
268        return RKRStatus::RKR_STATUS_SUCCESS;
269    }
270    if out_disp.is_null() {
271        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
272    }
273    if out_len < rows.len().saturating_mul(3) {
274        return note(RKRStatus::RKR_STATUS_BUFFER_TOO_SMALL);
275    }
276    for (i, row) in rows.iter().enumerate() {
277        unsafe {
278            *out_disp.add(i * 3) = row[0];
279            *out_disp.add(i * 3 + 1) = row[1];
280            *out_disp.add(i * 3 + 2) = row[2];
281        }
282    }
283    RKRStatus::RKR_STATUS_SUCCESS
284}
285/// Returns the atomic number for a chemical symbol, or 0 if the symbol
286/// is unknown or `symbol` is NULL. Lookup covers H..U (Z = 1..=92) and
287/// is case-sensitive: "Fe" works, "fe" does not.
288///
289/// # Safety
290///
291/// `symbol` must be either NULL or a pointer to a NUL-terminated UTF-8
292/// C string valid for reads up to the terminating NUL byte.
293#[unsafe(no_mangle)]
294pub unsafe extern "C" fn rkr_symbol_to_z(symbol: *const c_char) -> u64 {
295    if symbol.is_null() {
296        return 0;
297    }
298    match unsafe { CStr::from_ptr(symbol) }.to_str() {
299        Ok(s) => symbol_to_atomic_number(s),
300        Err(_) => 0,
301    }
302}
303/// Returns a pointer to a static, NUL-terminated chemical symbol for an
304/// atomic number, or "X" for unknown values. Coverage is H..U
305/// (Z = 1..=92). The returned pointer is valid for the lifetime of the
306/// process; do NOT free it.
307#[unsafe(no_mangle)]
308pub extern "C" fn rkr_z_to_symbol(z: u64) -> *const c_char {
309    // The static &str returned by helpers::atomic_number_to_symbol is
310    // not NUL-terminated, so the FFI mirrors the table with literals
311    // that have a trailing NUL. Index 0 holds "X" for unknown Z; indices
312    // 1..=92 hold H..U in order.
313    macro_rules! cstrs {
314        ($($lit:literal),* $(,)?) => {
315            [$(concat!($lit, "\0").as_bytes()),*]
316        };
317    }
318    const TABLE: [&[u8]; 93] = cstrs![
319        "X", "H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", "Al", "Si", "P",
320        "S", "Cl", "Ar", "K", "Ca", "Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn",
321        "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb", "Mo", "Tc", "Ru", "Rh",
322        "Pd", "Ag", "Cd", "In", "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "La", "Ce", "Pr", "Nd",
323        "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm", "Yb", "Lu", "Hf", "Ta", "W", "Re",
324        "Os", "Ir", "Pt", "Au", "Hg", "Tl", "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "Ac", "Th",
325        "Pa", "U",
326    ];
327    let idx = if (1..=92).contains(&z) { z as usize } else { 0 };
328    TABLE[idx].as_ptr() as *const c_char
329}
330/// Returns the spec version stored in a parsed frame's header.
331/// Returns 0 on error (null handle).
332#[unsafe(no_mangle)]
333pub extern "C" fn rkr_frame_spec_version(frame_handle: *const RKRConFrame) -> u32 {
334    match unsafe { (frame_handle as *const ConFrame).as_ref() } {
335        Some(f) => f.header.spec_version,
336        None => 0,
337    }
338}
339/// Returns the JSON metadata line from a parsed frame as a heap-allocated
340/// null-terminated C string. The caller MUST free with `rkr_free_string`.
341/// Returns NULL on error.
342///
343/// # Safety
344/// frame_handle must be valid. The caller takes ownership of the returned string.
345#[unsafe(no_mangle)]
346pub unsafe extern "C" fn rkr_frame_metadata_json(frame_handle: *const RKRConFrame) -> *mut c_char {
347    let frame = match unsafe { (frame_handle as *const ConFrame).as_ref() } {
348        Some(f) => f,
349        None => return null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
350    };
351    let mut obj = serde_json::Map::new();
352    obj.insert(
353        meta::CON_SPEC_VERSION.into(),
354        serde_json::Value::from(frame.header.spec_version),
355    );
356    for (k, v) in &frame.header.metadata {
357        obj.insert(k.clone(), v.clone());
358    }
359    let json_str = serde_json::Value::Object(obj).to_string();
360    match CString::new(json_str) {
361        Ok(cs) => cs.into_raw(),
362        Err(_) => null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
363    }
364}
365/// Returns the per-frame energy from metadata, or NaN if absent.
366#[unsafe(no_mangle)]
367pub extern "C" fn rkr_frame_energy(frame_handle: *const RKRConFrame) -> f64 {
368    match unsafe { (frame_handle as *const ConFrame).as_ref() } {
369        Some(f) => f.header.energy().unwrap_or(f64::NAN),
370        None => f64::NAN,
371    }
372}
373
374/// Campaign **finite** energy ([`crate::index_proj::finite_energy`]): NaN if missing or non-finite.
375/// Prefer this over [`rkr_frame_energy`] when mirroring `readcon-db` indexes.
376#[unsafe(no_mangle)]
377pub extern "C" fn rkr_frame_index_energy(frame_handle: *const RKRConFrame) -> f64 {
378    match unsafe { (frame_handle as *const ConFrame).as_ref() } {
379        Some(f) => crate::index_proj::finite_energy(f).unwrap_or(f64::NAN),
380        None => f64::NAN,
381    }
382}
383
384/// Canonical multiset formula (`Cu:2|H:2`) for campaign `idx_formula`. Free with `rkr_free_string`.
385/// # Safety
386///
387/// A non-null pointer argument must point at a live value of its declared
388/// type for this call. A null pointer is handled inside the function.
389#[unsafe(no_mangle)]
390pub unsafe extern "C" fn rkr_frame_composition_formula(
391    frame_handle: *const RKRConFrame,
392) -> *mut c_char {
393    let frame = match unsafe { (frame_handle as *const ConFrame).as_ref() } {
394        Some(f) => f,
395        None => return null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
396    };
397    let s = crate::index_proj::frame_composition_formula(frame);
398    match CString::new(s) {
399        Ok(cs) => cs.into_raw(),
400        Err(_) => null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
401    }
402}
403
404/// Total mass from type masses × counts; NaN if not all finite.
405#[unsafe(no_mangle)]
406pub extern "C" fn rkr_frame_total_mass(frame_handle: *const RKRConFrame) -> f64 {
407    match unsafe { (frame_handle as *const ConFrame).as_ref() } {
408        Some(f) => crate::index_proj::frame_total_mass(f).unwrap_or(f64::NAN),
409        None => f64::NAN,
410    }
411}
412
413/// Cell volume (lattice det or triclinic); NaN if unavailable.
414#[unsafe(no_mangle)]
415pub extern "C" fn rkr_frame_cell_volume(frame_handle: *const RKRConFrame) -> f64 {
416    match unsafe { (frame_handle as *const ConFrame).as_ref() } {
417        Some(f) => crate::index_proj::frame_cell_volume(f).unwrap_or(f64::NAN),
418        None => f64::NAN,
419    }
420}
421
422/// Max \(\|F_i\|\); NaN if no finite forces.
423#[unsafe(no_mangle)]
424pub extern "C" fn rkr_frame_fmax(frame_handle: *const RKRConFrame) -> f64 {
425    match unsafe { (frame_handle as *const ConFrame).as_ref() } {
426        Some(f) => crate::index_proj::frame_fmax(f).unwrap_or(f64::NAN),
427        None => f64::NAN,
428    }
429}
430
431/// Sections presence bitmask: bit0 forces, bit1 velocities, bit2 energies (see `index_proj`).
432#[unsafe(no_mangle)]
433pub extern "C" fn rkr_frame_sections_mask(frame_handle: *const RKRConFrame) -> u8 {
434    match unsafe { (frame_handle as *const ConFrame).as_ref() } {
435        Some(f) => crate::index_proj::sections_present_mask(f),
436        None => 0,
437    }
438}
439
440/// Atom count used for campaign `idx_natoms` (same as `atom_data.len()`).
441#[unsafe(no_mangle)]
442pub extern "C" fn rkr_frame_index_natoms(frame_handle: *const RKRConFrame) -> u32 {
443    match unsafe { (frame_handle as *const ConFrame).as_ref() } {
444        Some(f) => f.atom_data.len() as u32,
445        None => 0,
446    }
447}
448
449/// Compact JSON of [`crate::index_proj::FrameIndexProjection`] (campaign screening fields).
450/// Free with `rkr_free_string`. NULL on error.
451/// # Safety
452///
453/// A non-null pointer argument must point at a live value of its declared
454/// type for this call. A null pointer is handled inside the function.
455#[unsafe(no_mangle)]
456pub unsafe extern "C" fn rkr_frame_index_projection_json(
457    frame_handle: *const RKRConFrame,
458) -> *mut c_char {
459    let frame = match unsafe { (frame_handle as *const ConFrame).as_ref() } {
460        Some(f) => f,
461        None => return null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
462    };
463    let p = crate::index_proj::FrameIndexProjection::from_frame(frame);
464    let v = serde_json::json!({
465        "n_atoms": p.n_atoms,
466        "formula": p.formula,
467        "energy": p.energy,
468        "fmax": p.fmax,
469        "total_mass": p.total_mass,
470        "cell_volume": p.cell_volume,
471        "sections_mask": p.sections_mask,
472        "has_forces": p.has_forces,
473        "has_velocities": p.has_velocities,
474        "has_energy": p.has_energy,
475        "symbols": p.symbols,
476        "species_counts": p.species_counts.iter().map(|(s,c)| serde_json::json!([s, c])).collect::<Vec<_>>(),
477        "time": p.time,
478        "timestep": p.timestep,
479        "frame_index": p.frame_index,
480        "neb_bead": p.neb_bead,
481        "neb_band": p.neb_band,
482        "charge": p.charge,
483        "magmom": p.magmom,
484    });
485    match CString::new(v.to_string()) {
486        Ok(cs) => cs.into_raw(),
487        Err(_) => null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
488    }
489}
490/// Returns the potential type string from metadata as a heap-allocated
491/// null-terminated C string. The caller MUST free with `rkr_free_string`.
492/// Returns NULL if absent or on error.
493///
494/// # Safety
495/// frame_handle must be valid. The caller takes ownership of the returned string.
496#[unsafe(no_mangle)]
497pub unsafe extern "C" fn rkr_frame_potential_type(frame_handle: *const RKRConFrame) -> *mut c_char {
498    let frame = match unsafe { (frame_handle as *const ConFrame).as_ref() } {
499        Some(f) => f,
500        None => return null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
501    };
502    match frame.header.potential_type() {
503        Some(pot_type) => match CString::new(pot_type) {
504            Ok(cs) => cs.into_raw(),
505            Err(_) => null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
506        },
507        None => null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
508    }
509}
510/// Returns the zero-based frame index from metadata, or UINT64_MAX if absent.
511#[unsafe(no_mangle)]
512pub extern "C" fn rkr_frame_frame_index(frame_handle: *const RKRConFrame) -> u64 {
513    match unsafe { (frame_handle as *const ConFrame).as_ref() } {
514        Some(f) => f.header.frame_index().unwrap_or(u64::MAX),
515        None => u64::MAX,
516    }
517}
518/// Returns the simulation time from metadata, or NaN if absent.
519#[unsafe(no_mangle)]
520pub extern "C" fn rkr_frame_time(frame_handle: *const RKRConFrame) -> f64 {
521    match unsafe { (frame_handle as *const ConFrame).as_ref() } {
522        Some(f) => f.header.time().unwrap_or(f64::NAN),
523        None => f64::NAN,
524    }
525}
526/// Returns the integration timestep from metadata, or NaN if absent.
527#[unsafe(no_mangle)]
528pub extern "C" fn rkr_frame_timestep(frame_handle: *const RKRConFrame) -> f64 {
529    match unsafe { (frame_handle as *const ConFrame).as_ref() } {
530        Some(f) => f.header.timestep().unwrap_or(f64::NAN),
531        None => f64::NAN,
532    }
533}
534/// Returns the NEB bead index from metadata, or UINT64_MAX if absent.
535#[unsafe(no_mangle)]
536pub extern "C" fn rkr_frame_neb_bead(frame_handle: *const RKRConFrame) -> u64 {
537    match unsafe { (frame_handle as *const ConFrame).as_ref() } {
538        Some(f) => f.header.neb_bead().unwrap_or(u64::MAX),
539        None => u64::MAX,
540    }
541}
542/// Returns the NEB band index from metadata, or UINT64_MAX if absent.
543#[unsafe(no_mangle)]
544pub extern "C" fn rkr_frame_neb_band(frame_handle: *const RKRConFrame) -> u64 {
545    match unsafe { (frame_handle as *const ConFrame).as_ref() } {
546        Some(f) => f.header.neb_band().unwrap_or(u64::MAX),
547        None => u64::MAX,
548    }
549}
550//=============================================================================
551// C-Compatible Structs & Handles
552//=============================================================================
553/// Error codes for RKR functions.
554#[repr(C)]
555#[allow(non_camel_case_types)]
556#[derive(Debug, Clone, Copy, PartialEq, Eq)]
557pub enum RKRStatus {
558    /// Function completed successfully.
559    RKR_STATUS_SUCCESS = 0,
560    /// A null pointer was passed for a required argument.
561    RKR_STATUS_NULL_POINTER = -1,
562    /// An input string was not valid UTF-8.
563    RKR_STATUS_INVALID_UTF8 = -2,
564    /// JSON parsing or serialization failed.
565    RKR_STATUS_INVALID_JSON = -3,
566    /// File I/O error.
567    RKR_STATUS_IO_ERROR = -4,
568    /// Index out of bounds.
569    RKR_STATUS_INDEX_OUT_OF_BOUNDS = -5,
570    /// The destination buffer cannot hold a null-terminated string.
571    RKR_STATUS_BUFFER_TOO_SMALL = -6,
572    /// An internal logic error or unhandled state.
573    RKR_STATUS_INTERNAL_ERROR = -7,
574    /// An optional section (velocities, forces, atom_energies) was
575    /// requested but is not declared on the builder.
576    RKR_STATUS_SECTION_ABSENT = -8,
577    /// DLPack export or another validation step failed.
578    RKR_STATUS_VALIDATION_ERROR = -9,
579    /// Chemfiles selection parse/evaluate failed (requires chemfiles-enabled build).
580    RKR_STATUS_SELECTION_ERROR = -10,
581    /// Requested API is not in this build (Cargo feature off / symbols omitted).
582    /// Never use `-7` for this — that is [`RKR_STATUS_INTERNAL_ERROR`].
583    RKR_STATUS_FEATURE_DISABLED = -11,
584    /// Requested DLPack device does not match the array's residency.
585    RKR_STATUS_DEVICE_MISMATCH = -12,
586    /// Build cannot allocate on the requested non-CPU device (use caller-supplied buffers).
587    RKR_STATUS_DEVICE_ALLOC_UNSUPPORTED = -13,
588    /// A CON text parse failed. The thread-local [`rkr_last_error`] message
589    /// names the class (`NonFiniteValue`, `InvalidCount`, ...).
590    RKR_STATUS_PARSE_ERROR = -14,
591}
592/// Number of optional frame topology bonds (`metadata["bonds"]`), or 0 if absent.
593///
594/// # Safety
595/// `frame_handle` must be a valid handle or NULL.
596#[unsafe(no_mangle)]
597pub unsafe extern "C" fn rkr_frame_bond_count(frame_handle: *const RKRConFrame) -> u64 {
598    match unsafe { (frame_handle as *const ConFrame).as_ref() } {
599        Some(f) => f.bonds().len() as u64,
600        None => 0,
601    }
602}
603/// Read one bond at `index` (0-based into the `bonds` metadata array).
604///
605/// Writes 0-based `atom_data` indices into `out_i` / `out_j`. When the bond
606/// has an explicit order, sets `out_has_order` to 1 and `out_order` to that
607/// integer; otherwise `out_has_order` is 0.
608///
609/// # Safety
610/// `frame_handle` must be valid. Output pointers must be non-null.
611#[unsafe(no_mangle)]
612pub unsafe extern "C" fn rkr_frame_bond_at(
613    frame_handle: *const RKRConFrame,
614    index: u64,
615    out_i: *mut u32,
616    out_j: *mut u32,
617    out_has_order: *mut u8,
618    out_order: *mut i32,
619) -> RKRStatus {
620    if frame_handle.is_null()
621        || out_i.is_null()
622        || out_j.is_null()
623        || out_has_order.is_null()
624        || out_order.is_null()
625    {
626        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
627    }
628    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
629        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
630    };
631    let bonds = frame.bonds();
632    let Some(bond) = bonds.get(index as usize) else {
633        return note(RKRStatus::RKR_STATUS_INDEX_OUT_OF_BOUNDS);
634    };
635    unsafe {
636        *out_i = bond.i;
637        *out_j = bond.j;
638        if let Some(order) = bond.order {
639            *out_has_order = 1;
640            *out_order = order;
641        } else {
642            *out_has_order = 0;
643            *out_order = 0;
644        }
645    }
646    note(RKRStatus::RKR_STATUS_SUCCESS)
647}
648/// Returns a stable, static message for a status code.
649/// The returned pointer is valid for the lifetime of the process. Do NOT free it.
650#[unsafe(no_mangle)]
651pub extern "C" fn rkr_status_message(status: RKRStatus) -> *const c_char {
652    match status {
653        RKRStatus::RKR_STATUS_SUCCESS => c"success".as_ptr(),
654        RKRStatus::RKR_STATUS_NULL_POINTER => c"null pointer".as_ptr(),
655        RKRStatus::RKR_STATUS_INVALID_UTF8 => c"invalid UTF-8".as_ptr(),
656        RKRStatus::RKR_STATUS_INVALID_JSON => c"invalid JSON".as_ptr(),
657        RKRStatus::RKR_STATUS_IO_ERROR => c"I/O error".as_ptr(),
658        RKRStatus::RKR_STATUS_INDEX_OUT_OF_BOUNDS => c"index out of bounds".as_ptr(),
659        RKRStatus::RKR_STATUS_BUFFER_TOO_SMALL => c"buffer too small".as_ptr(),
660        RKRStatus::RKR_STATUS_INTERNAL_ERROR => c"internal error".as_ptr(),
661        RKRStatus::RKR_STATUS_SECTION_ABSENT => c"section absent".as_ptr(),
662        RKRStatus::RKR_STATUS_VALIDATION_ERROR => c"validation error".as_ptr(),
663        RKRStatus::RKR_STATUS_SELECTION_ERROR => c"selection error".as_ptr(),
664        RKRStatus::RKR_STATUS_FEATURE_DISABLED => c"feature disabled in this build".as_ptr(),
665        RKRStatus::RKR_STATUS_DEVICE_MISMATCH => c"DLPack device mismatch".as_ptr(),
666        RKRStatus::RKR_STATUS_DEVICE_ALLOC_UNSUPPORTED => {
667            c"device allocation unsupported in this build".as_ptr()
668        }
669        RKRStatus::RKR_STATUS_PARSE_ERROR => c"parse error".as_ptr(),
670    }
671}
672
673/// Thread-local parse or status failure. `message` is valid until the next
674/// error on this thread or until [`rkr_clear_error`].
675#[repr(C)]
676pub struct rkr_error {
677    pub code: i32,
678    pub message: *const c_char,
679    pub line: u32,
680    pub frame_index: u64,
681}
682
683struct LastErrorSlot {
684    message: CString,
685    view: rkr_error,
686}
687
688thread_local! {
689    static LAST_ERROR: RefCell<Option<LastErrorSlot>> = const { RefCell::new(None) };
690}
691
692fn set_last_error(code: i32, message: &str, line: u32, frame_index: u64) {
693    let cleaned = message.replace('\0', "");
694    let message = CString::new(cleaned).unwrap_or_else(|_| CString::new("error").unwrap());
695    LAST_ERROR.with(|cell| {
696        let mut slot = cell.borrow_mut();
697        *slot = Some(LastErrorSlot {
698            message,
699            view: rkr_error {
700                code,
701                message: std::ptr::null(),
702                line,
703                frame_index,
704            },
705        });
706        if let Some(stored) = slot.as_mut() {
707            stored.view.message = stored.message.as_ptr();
708        }
709    });
710}
711
712fn clear_last_error() {
713    LAST_ERROR.with(|cell| {
714        *cell.borrow_mut() = None;
715    });
716}
717
718fn static_status_message(status: RKRStatus) -> String {
719    let ptr = rkr_status_message(status);
720    if ptr.is_null() {
721        return "error".to_string();
722    }
723    unsafe { CStr::from_ptr(ptr) }
724        .to_string_lossy()
725        .into_owned()
726}
727
728/// Record a negative status. Success leaves the previous error in place.
729fn note(status: RKRStatus) -> RKRStatus {
730    let code = status as i32;
731    if code < 0 {
732        let message = static_status_message(status);
733        set_last_error(code, &message, 0, 0);
734    }
735    status
736}
737
738fn null_err<T>(status: RKRStatus) -> *mut T {
739    note(status);
740    ptr::null_mut()
741}
742
743fn status_for_parse(err: &crate::error::ParseError) -> RKRStatus {
744    use crate::error::ParseError;
745    match err {
746        ParseError::IndexOutOfBounds { .. } => note(RKRStatus::RKR_STATUS_INDEX_OUT_OF_BOUNDS),
747        ParseError::InvalidMetadataJson(_) | ParseError::MissingSpecVersion => {
748            note(RKRStatus::RKR_STATUS_INVALID_JSON)
749        }
750        _ => note(RKRStatus::RKR_STATUS_PARSE_ERROR),
751    }
752}
753
754fn note_located(err: &crate::error::LocatedParseError) -> RKRStatus {
755    let status = status_for_parse(&err.error);
756    let message = format!("{}: {}", err.error.class_name(), err.error);
757    set_last_error(status as i32, &message, err.line, err.frame_index);
758    status
759}
760
761/// Store a collective read failure for `rkr_last_error`.
762///
763/// A located parse keeps its file line and frame index. Any other failure
764/// is I/O, including a peer rank's parse and a path that could not be read.
765#[cfg(any(test, feature = "mpi"))]
766pub(crate) fn record_mpi_failure(err: &(dyn std::error::Error + 'static)) {
767    if let Some(located) = err.downcast_ref::<crate::error::LocatedParseError>() {
768        note_located(located);
769        return;
770    }
771    set_last_error(
772        RKRStatus::RKR_STATUS_IO_ERROR as i32,
773        &err.to_string(),
774        0,
775        0,
776    );
777}
778
779/// Store a status whose message is not the fixed `rkr_status_message` text.
780#[cfg(feature = "mpi")]
781pub(crate) fn record_status_message(status: RKRStatus, message: &str) {
782    set_last_error(status as i32, message, 0, 0);
783}
784
785fn null_located<T>(err: &crate::error::LocatedParseError) -> *mut T {
786    note_located(err);
787    ptr::null_mut()
788}
789
790fn note_load(err: crate::iterators::LoadError) {
791    match err {
792        crate::iterators::LoadError::Io(e) => {
793            set_last_error(RKRStatus::RKR_STATUS_IO_ERROR as i32, &e.to_string(), 0, 0);
794        }
795        crate::iterators::LoadError::Utf8(e) => {
796            set_last_error(
797                RKRStatus::RKR_STATUS_INVALID_UTF8 as i32,
798                &e.to_string(),
799                0,
800                0,
801            );
802        }
803        crate::iterators::LoadError::Parse(located) => {
804            note_located(&located);
805        }
806        crate::iterators::LoadError::Empty => {
807            let located = crate::error::LocatedParseError::new(
808                crate::error::ParseError::IncompleteHeader,
809                1,
810                0,
811            );
812            note_located(&located);
813        }
814    }
815}
816
817fn null_load<T>(err: crate::iterators::LoadError) -> *mut T {
818    note_load(err);
819    ptr::null_mut()
820}
821
822fn note_boxed(err: Box<dyn std::error::Error>) {
823    if let Some(io) = err.downcast_ref::<std::io::Error>() {
824        set_last_error(RKRStatus::RKR_STATUS_IO_ERROR as i32, &io.to_string(), 0, 0);
825        return;
826    }
827    let err = match err.downcast::<crate::iterators::LoadError>() {
828        Ok(load) => {
829            note_load(*load);
830            return;
831        }
832        Err(err) => err,
833    };
834    let err = match err.downcast::<crate::error::LocatedParseError>() {
835        Ok(located) => {
836            note_located(&located);
837            return;
838        }
839        Err(err) => err,
840    };
841    if let Some(parse) = err.downcast_ref::<crate::error::ParseError>() {
842        let located = crate::error::LocatedParseError::new(parse.clone(), parse.line(), 0);
843        note_located(&located);
844        return;
845    }
846    set_last_error(
847        RKRStatus::RKR_STATUS_INTERNAL_ERROR as i32,
848        &err.to_string(),
849        0,
850        0,
851    );
852}
853
854/// Detailed message from the most recent failure on this thread.
855///
856/// That includes a failing `rkr_writer_extend`, `rkr_writer_flush`,
857/// `rkr_trajectory_open` or `rkr_trajectory_read_frame`, and
858/// `rkr_trajectory_len` on a NULL handle.
859///
860/// This is the `message` field of [`rkr_last_error`]. Writer failures store
861/// the underlying I/O or format text. Returns NULL when nothing is stored.
862/// Do NOT free it.
863#[unsafe(no_mangle)]
864pub extern "C" fn rkr_last_error_message() -> *const c_char {
865    LAST_ERROR.with(|cell| {
866        cell.borrow()
867            .as_ref()
868            .map(|slot| slot.view.message)
869            .unwrap_or(std::ptr::null())
870    })
871}
872
873/// The error most recently set on this thread, or NULL if none is set.
874///
875/// The pointer and its `message` stay valid until the next failing call on
876/// this thread or [`rkr_clear_error`]. Do not free it.
877#[unsafe(no_mangle)]
878pub extern "C" fn rkr_last_error() -> *const rkr_error {
879    LAST_ERROR.with(|cell| {
880        cell.borrow()
881            .as_ref()
882            .map(|slot| &slot.view as *const rkr_error)
883            .unwrap_or(std::ptr::null())
884    })
885}
886
887/// Drop the thread-local error. A later success does not do this.
888#[unsafe(no_mangle)]
889pub extern "C" fn rkr_clear_error() {
890    clear_last_error();
891}
892/// An opaque handle to a full, lossless Rust `ConFrame` object.
893/// The C/C++ side needs to treat this as a void pointer
894// No #[repr(C)]: cbindgen then emits an incomplete struct, which C and C++
895// accept under -pedantic. The zero-length field keeps it unconstructible.
896pub struct RKRConFrame {
897    _private: [u8; 0],
898}
899/// An opaque handle to a Rust `ConFrameWriter` object.
900/// The C/C++ side needs to treat this as a void pointer
901// No #[repr(C)]: cbindgen then emits an incomplete struct, which C and C++
902// accept under -pedantic. The zero-length field keeps it unconstructible.
903pub struct RKRConFrameWriter {
904    _private: [u8; 0],
905}
906/// A transparent, "lossy" C-struct containing only the core atomic data.
907/// This can be extracted from an `RKRConFrame` handle for direct data access.
908/// The caller is responsible for freeing the `atoms` array using `free_c_frame`.
909/// Borrowed SoA column. `data` is valid until the parent frame is freed
910/// or a mutating call reallocates storage. No copy.
911#[repr(C)]
912pub struct RKRArrayView {
913    pub data: *const std::ffi::c_void,
914    pub n: usize,
915    pub cols: u32,
916    pub dtype_code: u8,
917    pub dtype_bits: u8,
918}
919
920impl RKRArrayView {
921    fn empty() -> Self {
922        Self {
923            data: std::ptr::null(),
924            n: 0,
925            cols: 0,
926            dtype_code: 0,
927            dtype_bits: 0,
928        }
929    }
930
931    fn from_array2(arr: &crate::storage_dtype::FloatArray2) -> Self {
932        let kind = arr.kind();
933        Self {
934            data: arr.data_ptr() as *const std::ffi::c_void,
935            n: arr.nrows(),
936            cols: arr.ncols() as u32,
937            dtype_code: kind.dlpack_code(),
938            dtype_bits: kind.dlpack_bits(),
939        }
940    }
941
942    fn from_array1(arr: &crate::storage_dtype::FloatArray1) -> Self {
943        let kind = arr.kind();
944        Self {
945            data: arr.data_ptr() as *const std::ffi::c_void,
946            n: arr.len(),
947            cols: 1,
948            dtype_code: kind.dlpack_code(),
949            dtype_bits: kind.dlpack_bits(),
950        }
951    }
952}
953
954#[repr(C)]
955pub struct CFrame {
956    pub atoms: *mut CAtom,
957    pub num_atoms: usize,
958    pub cell: [f64; 3],
959    pub angles: [f64; 3],
960    pub has_velocities: bool,
961    pub has_forces: bool,
962    pub has_energies: bool,
963}
964/// Transparent atom record extracted via [`rkr_frame_to_c_frame`].
965///
966/// `is_fixed` is the OR of `fixed_x`, `fixed_y`, `fixed_z`; it is kept
967/// for source compatibility with pre-spec-v2 callers that did not have
968/// per-axis flags. New code should use the per-axis fields.
969///
970/// `vx`/`vy`/`vz`, `fx`/`fy`/`fz`, and `energy` carry meaningful values
971/// only when `has_velocity`, `has_forces`, or `has_energy` is true
972/// respectively; the values are zeroed otherwise.
973#[repr(C)]
974pub struct CAtom {
975    pub atomic_number: u64,
976    pub x: f64,
977    pub y: f64,
978    pub z: f64,
979    pub atom_id: u64,
980    pub mass: f64,
981    /// True when any of `fixed_x`, `fixed_y`, `fixed_z` is true.
982    /// Kept for source compatibility; prefer the per-axis fields.
983    pub is_fixed: bool,
984    pub fixed_x: bool,
985    pub fixed_y: bool,
986    pub fixed_z: bool,
987    pub vx: f64,
988    pub vy: f64,
989    pub vz: f64,
990    pub has_velocity: bool,
991    pub fx: f64,
992    pub fy: f64,
993    pub fz: f64,
994    pub has_forces: bool,
995    /// Per-atom energy contribution; meaningful only when
996    /// `has_energy` is true. See [`crate::types::SECTION_ENERGIES`].
997    pub energy: f64,
998    pub has_energy: bool,
999}
1000#[repr(C)]
1001pub struct CConFrameIterator {
1002    iterator: *mut ConFrameIterator<'static>,
1003    file_contents: *mut crate::compression::ByteSource,
1004}
1005
1006/// Build an iterator over bytes this handle owns.
1007///
1008/// `utf8_checked` skips the scan when the caller already knows the buffer
1009/// is UTF-8. A failed scan frees the buffer and returns NULL, which is the
1010/// open-time contract of [`read_con_file_iterator`].
1011fn c_iterator_from_source(
1012    source: crate::compression::ByteSource,
1013    utf8_checked: bool,
1014) -> *mut CConFrameIterator {
1015    let source = Box::new(source);
1016    let source_ptr = Box::into_raw(source);
1017    let bytes = unsafe { (*source_ptr).as_slice() };
1018    if !utf8_checked && std::str::from_utf8(bytes).is_err() {
1019        unsafe {
1020            drop(Box::from_raw(source_ptr));
1021        }
1022        return ptr::null_mut();
1023    }
1024    // SAFETY: either the caller checked these bytes or the scan above did.
1025    // The iterator borrows them for as long as `source_ptr` is alive.
1026    let text: &'static str = unsafe { std::str::from_utf8_unchecked(bytes) };
1027    let iterator = Box::new(ConFrameIterator::new(text));
1028    let c_iterator = Box::new(CConFrameIterator {
1029        iterator: Box::into_raw(iterator),
1030        file_contents: source_ptr,
1031    });
1032    Box::into_raw(c_iterator)
1033}
1034
1035/// Build a path/buffer-backed C iterator from an owned CON text buffer.
1036fn c_iterator_from_owned_string(contents: String) -> *mut CConFrameIterator {
1037    c_iterator_from_source(
1038        crate::compression::ByteSource::Buf(contents.into_bytes()),
1039        true,
1040    )
1041}
1042
1043//=============================================================================
1044// Iterator and Memory Management
1045//=============================================================================
1046/// Creates a new iterator for a .con / .convel path, including transparent
1047/// gzip (`.con.gz`) and zstd (`.con.zst`, requires `zstd` feature) inputs via
1048/// [`crate::compression::read_file_contents`].
1049///
1050/// Returns NULL if the file cannot be read, decompressed, or is not valid
1051/// UTF-8. A successfully-opened file with zero frames returns a non-NULL
1052/// iterator that yields NULL on the first call to [`con_frame_iterator_next`].
1053/// The caller OWNS the returned pointer and MUST call [`free_con_frame_iterator`].
1054///
1055/// # Safety
1056/// filename_c must be a valid null-terminated string. The caller takes
1057/// ownership of the returned iterator.
1058#[unsafe(no_mangle)]
1059pub unsafe extern "C" fn read_con_file_iterator(
1060    filename_c: *const c_char,
1061) -> *mut CConFrameIterator {
1062    if filename_c.is_null() {
1063        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
1064    }
1065    let filename = match unsafe { CStr::from_ptr(filename_c).to_str() } {
1066        Ok(s) => s,
1067        Err(e) => {
1068            set_last_error(
1069                RKRStatus::RKR_STATUS_INVALID_UTF8 as i32,
1070                &e.to_string(),
1071                0,
1072                0,
1073            );
1074            return ptr::null_mut();
1075        }
1076    };
1077    let owned = match crate::compression::read_bytes_owned(Path::new(filename)) {
1078        Ok(bytes) => bytes,
1079        Err(e) => {
1080            note_boxed(e);
1081            return ptr::null_mut();
1082        }
1083    };
1084    if let Err(e) = std::str::from_utf8(owned.as_slice()) {
1085        set_last_error(
1086            RKRStatus::RKR_STATUS_INVALID_UTF8 as i32,
1087            &e.to_string(),
1088            0,
1089            0,
1090        );
1091        return ptr::null_mut();
1092    }
1093    c_iterator_from_source(owned, true)
1094}
1095
1096/// Iterate frames from an in-memory CON text buffer (null-terminated C string).
1097///
1098/// Use when the caller already decompressed (chemfiles, custom I/O) and wants
1099/// to avoid a temp file. Same ownership rules as [`read_con_file_iterator`].
1100///
1101/// # Safety
1102/// `contents_c` must be a valid null-terminated UTF-8 string, or NULL (returns NULL).
1103#[unsafe(no_mangle)]
1104pub unsafe extern "C" fn read_con_string_iterator(
1105    contents_c: *const c_char,
1106) -> *mut CConFrameIterator {
1107    if contents_c.is_null() {
1108        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
1109    }
1110    let contents = match unsafe { CStr::from_ptr(contents_c).to_str() } {
1111        Ok(s) => s.to_owned(),
1112        Err(e) => {
1113            set_last_error(
1114                RKRStatus::RKR_STATUS_INVALID_UTF8 as i32,
1115                &e.to_string(),
1116                0,
1117                0,
1118            );
1119            return ptr::null_mut();
1120        }
1121    };
1122    c_iterator_from_owned_string(contents)
1123}
1124
1125/// Iterate frames from a byte buffer (not necessarily null-terminated).
1126///
1127/// `len` is the number of bytes at `data`. Bytes must be valid UTF-8 CON text.
1128///
1129/// # Safety
1130/// `data` must be valid for `len` bytes if non-null and `len > 0`.
1131#[unsafe(no_mangle)]
1132pub unsafe extern "C" fn read_con_buffer_iterator(
1133    data: *const u8,
1134    len: usize,
1135) -> *mut CConFrameIterator {
1136    if data.is_null() && len > 0 {
1137        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
1138    }
1139    if len == 0 {
1140        return c_iterator_from_owned_string(String::new());
1141    }
1142    let slice = unsafe { std::slice::from_raw_parts(data, len) };
1143    let contents = match std::str::from_utf8(slice) {
1144        Ok(s) => s.to_owned(),
1145        Err(_) => return null_err::<_>(RKRStatus::RKR_STATUS_INVALID_UTF8),
1146    };
1147    c_iterator_from_owned_string(contents)
1148}
1149/// Reads the next frame from the iterator, returning an opaque handle.
1150/// The caller OWNS the returned handle and must free it with `free_rkr_frame`.
1151///
1152/// # Safety
1153/// iterator must be valid. The caller takes ownership of the returned frame.
1154#[unsafe(no_mangle)]
1155pub unsafe extern "C" fn con_frame_iterator_next(
1156    iterator: *mut CConFrameIterator,
1157) -> *mut RKRConFrame {
1158    if iterator.is_null() {
1159        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
1160    }
1161    let iter = unsafe { &mut *(*iterator).iterator };
1162    match iter.next() {
1163        Some(Ok(frame)) => Box::into_raw(Box::new(frame)) as *mut RKRConFrame,
1164        Some(Err(e)) => {
1165            let located =
1166                crate::error::LocatedParseError::new(e, iter.lines.line_no(), iter.frame_index());
1167            null_located(&located)
1168        }
1169        None => ptr::null_mut(),
1170    }
1171}
1172
1173/// Skip one frame without parsing atoms. `RKR_STATUS_SUCCESS` on skip,
1174/// `RKR_STATUS_INDEX_OUT_OF_BOUNDS` at EOF, other codes on parse error.
1175/// # Safety
1176///
1177/// A non-null pointer argument must point at a live value of its declared
1178/// type for this call. A null pointer is handled inside the function.
1179#[unsafe(no_mangle)]
1180pub unsafe extern "C" fn con_frame_iterator_forward(iterator: *mut CConFrameIterator) -> RKRStatus {
1181    if iterator.is_null() {
1182        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
1183    }
1184    let iter = unsafe { &mut *(*iterator).iterator };
1185    match iter.forward() {
1186        Some(Ok(())) => RKRStatus::RKR_STATUS_SUCCESS,
1187        Some(Err(e)) => {
1188            let located =
1189                crate::error::LocatedParseError::new(e, iter.lines.line_no(), iter.frame_index());
1190            note_located(&located)
1191        }
1192        None => note(RKRStatus::RKR_STATUS_INDEX_OUT_OF_BOUNDS),
1193    }
1194}
1195
1196/// Skip `n` frames without parsing atoms. Returns the number skipped, or
1197/// `usize::MAX` on a null iterator.
1198/// # Safety
1199///
1200/// A non-null pointer argument must point at a live value of its declared
1201/// type for this call. A null pointer is handled inside the function.
1202#[unsafe(no_mangle)]
1203pub unsafe extern "C" fn con_frame_iterator_skip(
1204    iterator: *mut CConFrameIterator,
1205    n: usize,
1206) -> usize {
1207    if iterator.is_null() {
1208        note(RKRStatus::RKR_STATUS_NULL_POINTER);
1209        return usize::MAX;
1210    }
1211    let iter = unsafe { &mut *(*iterator).iterator };
1212    match iter.skip_frames(n) {
1213        Ok(skipped) => skipped,
1214        Err(e) => {
1215            let located =
1216                crate::error::LocatedParseError::new(e, iter.lines.line_no(), iter.frame_index());
1217            note_located(&located);
1218            usize::MAX
1219        }
1220    }
1221}
1222
1223/// Skip `index` frames, then parse the next. NULL at EOF or on error.
1224/// # Safety
1225///
1226/// A non-null pointer argument must point at a live value of its declared
1227/// type for this call. A null pointer is handled inside the function.
1228#[unsafe(no_mangle)]
1229pub unsafe extern "C" fn con_frame_iterator_nth(
1230    iterator: *mut CConFrameIterator,
1231    index: usize,
1232) -> *mut RKRConFrame {
1233    if iterator.is_null() {
1234        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
1235    }
1236    let iter = unsafe { &mut *(*iterator).iterator };
1237    match iter.skip_frames_counted(index) {
1238        Ok(skipped) if skipped == index => {}
1239        Ok(_) => return null_err::<_>(RKRStatus::RKR_STATUS_INDEX_OUT_OF_BOUNDS),
1240        Err((_failed_at, e)) => {
1241            let located =
1242                crate::error::LocatedParseError::new(e, iter.lines.line_no(), iter.frame_index());
1243            return null_located(&located);
1244        }
1245    }
1246    match iter.next() {
1247        Some(Ok(frame)) => Box::into_raw(Box::new(frame)) as *mut RKRConFrame,
1248        Some(Err(e)) => {
1249            let located =
1250                crate::error::LocatedParseError::new(e, iter.lines.line_no(), iter.frame_index());
1251            null_located(&located)
1252        }
1253        None => null_err::<_>(RKRStatus::RKR_STATUS_INDEX_OUT_OF_BOUNDS),
1254    }
1255}
1256
1257/// Count frames on a path (skip walk, no atom parse). `usize::MAX` on error.
1258/// # Safety
1259///
1260/// A non-null pointer argument must point at a live value of its declared
1261/// type for this call. A null pointer is handled inside the function.
1262#[unsafe(no_mangle)]
1263pub unsafe extern "C" fn rkr_count_frames(filename_c: *const c_char) -> usize {
1264    if filename_c.is_null() {
1265        note(RKRStatus::RKR_STATUS_NULL_POINTER);
1266        return usize::MAX;
1267    }
1268    let filename = match unsafe { CStr::from_ptr(filename_c).to_str() } {
1269        Ok(s) => s,
1270        Err(e) => {
1271            set_last_error(
1272                RKRStatus::RKR_STATUS_INVALID_UTF8 as i32,
1273                &e.to_string(),
1274                0,
1275                0,
1276            );
1277            return usize::MAX;
1278        }
1279    };
1280    match crate::iterators::count_frames(Path::new(filename)) {
1281        Ok(n) => n,
1282        Err(e) => {
1283            note_load(e);
1284            usize::MAX
1285        }
1286    }
1287}
1288
1289/// Skip `index` frames on a path, then parse one. Caller frees with `free_rkr_frame`.
1290/// # Safety
1291///
1292/// A non-null pointer argument must point at a live value of its declared
1293/// type for this call. A null pointer is handled inside the function.
1294#[unsafe(no_mangle)]
1295pub unsafe extern "C" fn rkr_read_nth_frame(
1296    filename_c: *const c_char,
1297    index: usize,
1298) -> *mut RKRConFrame {
1299    if filename_c.is_null() {
1300        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
1301    }
1302    let filename = match unsafe { CStr::from_ptr(filename_c).to_str() } {
1303        Ok(s) => s,
1304        Err(e) => {
1305            set_last_error(
1306                RKRStatus::RKR_STATUS_INVALID_UTF8 as i32,
1307                &e.to_string(),
1308                0,
1309                0,
1310            );
1311            return ptr::null_mut();
1312        }
1313    };
1314    match crate::iterators::read_nth_frame_located(Path::new(filename), index) {
1315        Ok(frame) => Box::into_raw(Box::new(frame)) as *mut RKRConFrame,
1316        Err(e) => null_load(e),
1317    }
1318}
1319
1320/// An opaque random-access handle over one file. Free with `rkr_trajectory_free`.
1321// No #[repr(C)]: cbindgen then emits an incomplete struct, which C and C++
1322// accept under -pedantic. The zero-length field keeps it unconstructible.
1323pub struct RKRTrajectory {
1324    _private: [u8; 0],
1325}
1326
1327/// Open a file for reads by frame number.
1328///
1329/// The file is read once and its frame index is kept. An uncompressed file
1330/// reuses a valid `<path>.rcidx`; a nonzero `write_index` writes a fresh scan
1331/// there. gzip and zstd input is indexed in memory only. Returns NULL on
1332/// error, and `rkr_last_error_message` gives the reason.
1333///
1334/// # Safety
1335/// `filename_c` must be NULL or a valid null-terminated string.
1336#[unsafe(no_mangle)]
1337pub unsafe extern "C" fn rkr_trajectory_open(
1338    filename_c: *const c_char,
1339    write_index: i32,
1340) -> *mut RKRTrajectory {
1341    if filename_c.is_null() {
1342        set_last_error(
1343            RKRStatus::RKR_STATUS_NULL_POINTER as i32,
1344            "filename is NULL",
1345            0,
1346            0,
1347        );
1348        return ptr::null_mut();
1349    }
1350    let filename = match unsafe { CStr::from_ptr(filename_c).to_str() } {
1351        Ok(s) => s,
1352        Err(_) => {
1353            set_last_error(
1354                RKRStatus::RKR_STATUS_INVALID_UTF8 as i32,
1355                "filename is not valid UTF-8",
1356                0,
1357                0,
1358            );
1359            return ptr::null_mut();
1360        }
1361    };
1362    let opened = std::panic::catch_unwind(|| {
1363        crate::trajectory::ConTrajectory::open(Path::new(filename), write_index != 0)
1364            .map_err(|e| e.to_string())
1365    })
1366    .unwrap_or_else(|_| Err("internal error while opening the file".to_owned()));
1367    match opened {
1368        Ok(traj) => {
1369            clear_last_error();
1370            Box::into_raw(Box::new(traj)) as *mut RKRTrajectory
1371        }
1372        Err(msg) => {
1373            set_last_error(RKRStatus::RKR_STATUS_IO_ERROR as i32, &msg, 0, 0);
1374            ptr::null_mut()
1375        }
1376    }
1377}
1378
1379/// Number of frames in the handle.
1380///
1381/// A NULL handle returns `usize::MAX` and records `null argument`. A live
1382/// handle leaves `rkr_last_error_message` as it was.
1383///
1384/// # Safety
1385/// `handle` must be NULL or a live handle from `rkr_trajectory_open`.
1386#[unsafe(no_mangle)]
1387pub unsafe extern "C" fn rkr_trajectory_len(handle: *const RKRTrajectory) -> usize {
1388    match unsafe { (handle as *const crate::trajectory::ConTrajectory).as_ref() } {
1389        Some(traj) => traj.len(),
1390        None => {
1391            set_last_error(
1392                RKRStatus::RKR_STATUS_NULL_POINTER as i32,
1393                "null argument",
1394                0,
1395                0,
1396            );
1397            usize::MAX
1398        }
1399    }
1400}
1401
1402/// Parse frame `index` into `*out_frame`, which the caller frees with
1403/// `free_rkr_frame`.
1404///
1405/// Returns `RKR_STATUS_INDEX_OUT_OF_BOUNDS` when `index` is not below
1406/// `rkr_trajectory_len`, and `RKR_STATUS_IO_ERROR` when the frame does not
1407/// parse. A NULL argument returns `RKR_STATUS_NULL_POINTER` and records
1408/// `null argument`. `*out_frame` is NULL unless the status is success, and
1409/// on failure `rkr_last_error_message` gives the reason.
1410///
1411/// # Safety
1412/// `handle` must be NULL or a live handle; `out_frame` must be NULL or
1413/// valid for one pointer write.
1414#[unsafe(no_mangle)]
1415pub unsafe extern "C" fn rkr_trajectory_read_frame(
1416    handle: *const RKRTrajectory,
1417    index: usize,
1418    out_frame: *mut *mut RKRConFrame,
1419) -> RKRStatus {
1420    if !out_frame.is_null() {
1421        unsafe { *out_frame = ptr::null_mut() };
1422    }
1423    if handle.is_null() || out_frame.is_null() {
1424        set_last_error(
1425            RKRStatus::RKR_STATUS_NULL_POINTER as i32,
1426            "null argument",
1427            0,
1428            0,
1429        );
1430        return RKRStatus::RKR_STATUS_NULL_POINTER;
1431    }
1432    let traj = unsafe { &*(handle as *const crate::trajectory::ConTrajectory) };
1433    let parsed = std::panic::catch_unwind(|| traj.frame(index));
1434    let (status, msg) = match parsed {
1435        Ok(Ok(frame)) => {
1436            clear_last_error();
1437            unsafe { *out_frame = Box::into_raw(Box::new(frame)) as *mut RKRConFrame };
1438            return RKRStatus::RKR_STATUS_SUCCESS;
1439        }
1440        Ok(Err(crate::error::ParseError::IndexOutOfBounds { index, len })) => (
1441            RKRStatus::RKR_STATUS_INDEX_OUT_OF_BOUNDS,
1442            format!("frame index {index} is out of range for a trajectory of {len} frames"),
1443        ),
1444        Ok(Err(e)) => (
1445            RKRStatus::RKR_STATUS_IO_ERROR,
1446            format!("frame {index}: {e}"),
1447        ),
1448        Err(_) => (
1449            RKRStatus::RKR_STATUS_INTERNAL_ERROR,
1450            format!("internal error while reading frame {index}"),
1451        ),
1452    };
1453    set_last_error(status as i32, &msg, 0, 0);
1454    status
1455}
1456
1457/// Free a handle from `rkr_trajectory_open`. NULL is a no-op.
1458///
1459/// # Safety
1460/// `handle` must be NULL or a live handle that is not used afterwards.
1461#[unsafe(no_mangle)]
1462pub unsafe extern "C" fn rkr_trajectory_free(handle: *mut RKRTrajectory) {
1463    if !handle.is_null() {
1464        let _ = unsafe { Box::from_raw(handle as *mut crate::trajectory::ConTrajectory) };
1465    }
1466}
1467/// Frees the memory for an opaque `RKRConFrame` handle.
1468///
1469/// # Safety
1470/// frame_handle must be valid or null.
1471#[unsafe(no_mangle)]
1472pub unsafe extern "C" fn free_rkr_frame(frame_handle: *mut RKRConFrame) {
1473    if !frame_handle.is_null() {
1474        let _ = unsafe { Box::from_raw(frame_handle as *mut ConFrame) };
1475    }
1476}
1477/// Frees the memory for a `CConFrameIterator`.
1478///
1479/// # Safety
1480/// iterator must be valid or null.
1481#[unsafe(no_mangle)]
1482pub unsafe extern "C" fn free_con_frame_iterator(iterator: *mut CConFrameIterator) {
1483    if iterator.is_null() {
1484        return;
1485    }
1486    unsafe {
1487        let c_iterator_box = Box::from_raw(iterator);
1488        let _ = Box::from_raw(c_iterator_box.iterator);
1489        let _ = Box::from_raw(c_iterator_box.file_contents);
1490    }
1491}
1492//=============================================================================
1493// Data Accessors (The "Getter" API)
1494//=============================================================================
1495/// Extracts the core atomic data into a transparent `CFrame` struct.
1496/// The caller OWNS the returned pointer and MUST call `free_c_frame` on it.
1497///
1498/// # Safety
1499/// frame_handle must be valid. The caller takes ownership of the returned CFrame.
1500#[unsafe(no_mangle)]
1501pub unsafe extern "C" fn rkr_frame_to_c_frame(frame_handle: *const RKRConFrame) -> *mut CFrame {
1502    let frame = match unsafe { (frame_handle as *const ConFrame).as_ref() } {
1503        Some(f) => f,
1504        None => return null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
1505    };
1506    let masses_iter = frame
1507        .header
1508        .natms_per_type
1509        .iter()
1510        .zip(frame.header.masses_per_type.iter())
1511        .flat_map(|(num_atoms, mass)| std::iter::repeat_n(*mass, *num_atoms));
1512    let has_velocities = frame.has_velocities();
1513    let mut c_atoms: Vec<CAtom> = frame
1514        .atom_data
1515        .iter()
1516        .zip(masses_iter)
1517        .map(|(atom_datum, mass)| {
1518            let [vx, vy, vz] = atom_datum.velocity().unwrap_or([0.0; 3]);
1519            let [fx, fy, fz] = atom_datum.force().unwrap_or([0.0; 3]);
1520            CAtom {
1521                atomic_number: symbol_to_atomic_number(&atom_datum.symbol),
1522                x: atom_datum.x,
1523                y: atom_datum.y,
1524                z: atom_datum.z,
1525                is_fixed: atom_datum.is_fixed(),
1526                fixed_x: atom_datum.fixed[0],
1527                fixed_y: atom_datum.fixed[1],
1528                fixed_z: atom_datum.fixed[2],
1529                atom_id: atom_datum.atom_id,
1530                mass,
1531                vx,
1532                vy,
1533                vz,
1534                has_velocity: atom_datum.has_velocity(),
1535                fx,
1536                fy,
1537                fz,
1538                has_forces: atom_datum.has_forces(),
1539                energy: atom_datum.energy().unwrap_or(0.0),
1540                has_energy: atom_datum.has_energy(),
1541            }
1542        })
1543        .collect();
1544    let atoms_ptr = c_atoms.as_mut_ptr();
1545    let num_atoms = c_atoms.len();
1546    std::mem::forget(c_atoms);
1547    let has_forces = frame.has_forces();
1548    let has_energies = frame.has_energies();
1549    let c_frame = Box::new(CFrame {
1550        atoms: atoms_ptr,
1551        num_atoms,
1552        cell: frame.header.boxl,
1553        angles: frame.header.angles,
1554        has_velocities,
1555        has_forces,
1556        has_energies,
1557    });
1558    Box::into_raw(c_frame)
1559}
1560/// Frees the memory of a `CFrame` struct, including its internal atoms array.
1561///
1562/// # Safety
1563/// frame must be valid or null.
1564#[unsafe(no_mangle)]
1565pub unsafe extern "C" fn free_c_frame(frame: *mut CFrame) {
1566    if frame.is_null() {
1567        return;
1568    }
1569    unsafe {
1570        let frame_box = Box::from_raw(frame);
1571        let _ = Vec::from_raw_parts(frame_box.atoms, frame_box.num_atoms, frame_box.num_atoms);
1572    }
1573}
1574/// Copies a header string line into a caller-provided buffer.
1575///
1576/// `is_prebox=true` selects from the two prebox lines (line 0 = user
1577/// text, line 1 = JSON metadata); `false` selects from the two postbox
1578/// lines. Strings longer than `buffer_len - 1` bytes are truncated; the
1579/// final byte is always set to NUL.
1580///
1581/// Returns `RKR_STATUS_SUCCESS` on success,
1582/// `RKR_STATUS_INDEX_OUT_OF_BOUNDS` if `line_index >= 2`,
1583/// `RKR_STATUS_NULL_POINTER` if `frame_handle` or `buffer` is NULL,
1584/// `RKR_STATUS_BUFFER_TOO_SMALL` if `buffer_len == 0`.
1585///
1586/// Pair with [`rkr_frame_get_header_line_cpp`] when the caller prefers
1587/// an allocated string with no fixed length cap; that variant returns
1588/// NULL for the same out-of-bounds condition.
1589///
1590/// # Safety
1591/// frame_handle must be valid. buffer must be at least buffer_len bytes.
1592#[unsafe(no_mangle)]
1593pub unsafe extern "C" fn rkr_frame_get_header_line(
1594    frame_handle: *const RKRConFrame,
1595    is_prebox: bool,
1596    line_index: usize,
1597    buffer: *mut c_char,
1598    buffer_len: usize,
1599) -> RKRStatus {
1600    let frame = match unsafe { (frame_handle as *const ConFrame).as_ref() } {
1601        Some(f) => f,
1602        None => return note(RKRStatus::RKR_STATUS_NULL_POINTER),
1603    };
1604    if buffer.is_null() {
1605        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
1606    }
1607    if buffer_len == 0 {
1608        return note(RKRStatus::RKR_STATUS_BUFFER_TOO_SMALL);
1609    }
1610    let line_to_copy: Option<&str> = if is_prebox {
1611        match line_index {
1612            0 => Some(frame.header.prebox_header.user.as_str()),
1613            1 => Some(frame.header.prebox_header.metadata_line()),
1614            _ => None,
1615        }
1616    } else {
1617        frame
1618            .header
1619            .postbox_header
1620            .get(line_index)
1621            .map(String::as_str)
1622    };
1623    if let Some(line) = line_to_copy {
1624        let bytes = line.as_bytes();
1625        let len_to_copy = std::cmp::min(bytes.len(), buffer_len - 1);
1626        unsafe {
1627            ptr::copy_nonoverlapping(bytes.as_ptr(), buffer as *mut u8, len_to_copy);
1628            *buffer.add(len_to_copy) = 0;
1629        }
1630        note(RKRStatus::RKR_STATUS_SUCCESS)
1631    } else {
1632        note(RKRStatus::RKR_STATUS_INDEX_OUT_OF_BOUNDS)
1633    }
1634}
1635/// Gets a header string line as a newly allocated, null-terminated C string.
1636///
1637/// The caller OWNS the returned pointer and MUST call `rkr_free_string`
1638/// on it to prevent a memory leak. Returns NULL on error or if the
1639/// index is invalid (use [`rkr_frame_get_header_line`] when a status
1640/// code is preferred to NULL-vs-success disambiguation).
1641///
1642/// The `_cpp` suffix is historical; the function is callable from both
1643/// C and C++.
1644///
1645/// # Safety
1646/// frame_handle must be valid. The caller takes ownership of the returned string.
1647#[unsafe(no_mangle)]
1648pub unsafe extern "C" fn rkr_frame_get_header_line_cpp(
1649    frame_handle: *const RKRConFrame,
1650    is_prebox: bool,
1651    line_index: usize,
1652) -> *mut c_char {
1653    let frame = match unsafe { (frame_handle as *const ConFrame).as_ref() } {
1654        Some(f) => f,
1655        None => return null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
1656    };
1657    let line_to_copy: Option<&str> = if is_prebox {
1658        match line_index {
1659            0 => Some(frame.header.prebox_header.user.as_str()),
1660            1 => Some(frame.header.prebox_header.metadata_line()),
1661            _ => None,
1662        }
1663    } else {
1664        frame
1665            .header
1666            .postbox_header
1667            .get(line_index)
1668            .map(String::as_str)
1669    };
1670    if let Some(line) = line_to_copy {
1671        // Convert the Rust string slice to a C-compatible, heap-allocated string.
1672        match CString::new(line) {
1673            Ok(c_string) => c_string.into_raw(), // Give ownership to the C caller
1674            Err(_) => null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR), // In case the string contains a null byte
1675        }
1676    } else {
1677        ptr::null_mut() // Index out of bounds
1678    }
1679}
1680/// Frees a C string that was allocated by Rust (e.g., from
1681/// `rkr_frame_metadata_json`, `rkr_frame_potential_type`, or
1682/// `rkr_frame_get_header_line_cpp`). Safe to call with NULL (no-op).
1683///
1684/// # Safety
1685/// s must be either NULL or a pointer previously returned by an
1686/// allocating Rust FFI function in this crate.
1687#[unsafe(no_mangle)]
1688pub unsafe extern "C" fn rkr_free_string(s: *mut c_char) {
1689    if !s.is_null() {
1690        // Retake ownership of the CString to deallocate it properly.
1691        let _ = unsafe { CString::from_raw(s) };
1692    }
1693}
1694//=============================================================================
1695// FFI Writer Functions (Writer Object Model)
1696//=============================================================================
1697/// Type-erased writer that backs every `RKRConFrameWriter` handle.
1698///
1699/// `ConFrameWriter<W>` is generic over its sink, so a plain `File`, a
1700/// gzip `GzEncoder<File>`, and a zstd encoder all monomorphise to
1701/// distinct, layout-incompatible types. Boxing the sink as
1702/// `Box<dyn Write>` collapses them to a single concrete handle type, so
1703/// `free_rkr_writer` and `rkr_writer_extend` can cast the opaque pointer
1704/// to exactly one type regardless of the compression chosen at
1705/// construction. Dropping the box flushes the `BufWriter` and then runs
1706/// the sink's own `Drop` (gzip/zstd finalize their streams there).
1707type RkrWriter = ConFrameWriter<Box<dyn std::io::Write>>;
1708/// Boxes a sink into an `RKRConFrameWriter` handle at the requested
1709/// precision. `precision == None` selects the writer's built-in default.
1710#[inline]
1711fn into_rkr_writer(sink: Box<dyn std::io::Write>, precision: Option<u8>) -> *mut RKRConFrameWriter {
1712    let writer: RkrWriter = match precision {
1713        Some(p) => ConFrameWriter::with_precision(sink, p as usize),
1714        None => ConFrameWriter::new(sink),
1715    };
1716    Box::into_raw(Box::new(writer)) as *mut RKRConFrameWriter
1717}
1718/// Parses a borrowed C string, returning `None` for null or non-UTF-8.
1719#[inline]
1720unsafe fn cstr_path<'a>(filename_c: *const c_char) -> Option<&'a str> {
1721    if filename_c.is_null() {
1722        return None;
1723    }
1724    unsafe { CStr::from_ptr(filename_c).to_str().ok() }
1725}
1726/// Creates a new frame writer for the specified file.
1727/// The caller OWNS the returned pointer and MUST call `free_rkr_writer`.
1728///
1729/// # Safety
1730/// filename_c must be valid. The caller takes ownership of the returned writer.
1731#[unsafe(no_mangle)]
1732pub unsafe extern "C" fn create_writer_from_path_c(
1733    filename_c: *const c_char,
1734) -> *mut RKRConFrameWriter {
1735    let filename = match unsafe { cstr_path(filename_c) } {
1736        Some(s) => s,
1737        None => return null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
1738    };
1739    match File::create(filename) {
1740        Ok(file) => into_rkr_writer(Box::new(file), None),
1741        Err(_) => null_err::<_>(RKRStatus::RKR_STATUS_IO_ERROR),
1742    }
1743}
1744/// Creates a CON writer that preserves every finite binary64 value.
1745/// The caller owns the handle and must call `free_rkr_writer`.
1746///
1747/// # Safety
1748/// filename_c must be a valid NUL-terminated path or null.
1749#[unsafe(no_mangle)]
1750pub unsafe extern "C" fn create_writer_from_path_round_trip_c(
1751    filename_c: *const c_char,
1752) -> *mut RKRConFrameWriter {
1753    let filename = match unsafe { cstr_path(filename_c) } {
1754        Some(s) => s,
1755        None => return null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
1756    };
1757    match File::create(filename) {
1758        Ok(file) => {
1759            let writer: RkrWriter = ConFrameWriter::with_float_format(
1760                Box::new(file),
1761                crate::writer::FloatFormat::RoundTrip,
1762            );
1763            Box::into_raw(Box::new(writer)) as *mut RKRConFrameWriter
1764        }
1765        Err(_) => null_err::<_>(RKRStatus::RKR_STATUS_IO_ERROR),
1766    }
1767}
1768
1769/// Opens an uncompressed file for appending.
1770///
1771/// The caller owns the handle and must call `free_rkr_writer`. A missing
1772/// file is created. A non-empty file that does not end in a newline receives
1773/// one. Gzip and zstd paths return null; [`rkr_last_error_message`] explains
1774/// why.
1775///
1776/// # Safety
1777/// `filename_c` must be a valid NUL-terminated path or null.
1778#[unsafe(no_mangle)]
1779pub unsafe extern "C" fn create_writer_from_path_append_c(
1780    filename_c: *const c_char,
1781) -> *mut RKRConFrameWriter {
1782    let Some(filename) = (unsafe { cstr_path(filename_c) }) else {
1783        return ptr::null_mut();
1784    };
1785    match crate::writer::open_uncompressed_append(Path::new(filename)) {
1786        Ok(file) => into_rkr_writer(Box::new(file), None),
1787        Err(err) => {
1788            set_last_error(
1789                RKRStatus::RKR_STATUS_IO_ERROR as i32,
1790                &err.to_string(),
1791                0,
1792                0,
1793            );
1794            ptr::null_mut()
1795        }
1796    }
1797}
1798
1799/// Opens an uncompressed file for appending with a fixed decimal precision.
1800///
1801/// The caller owns the handle and must call `free_rkr_writer`.
1802///
1803/// # Safety
1804/// `filename_c` must be a valid NUL-terminated path or null.
1805#[unsafe(no_mangle)]
1806pub unsafe extern "C" fn create_writer_from_path_append_with_precision_c(
1807    filename_c: *const c_char,
1808    precision: u8,
1809) -> *mut RKRConFrameWriter {
1810    let Some(filename) = (unsafe { cstr_path(filename_c) }) else {
1811        return ptr::null_mut();
1812    };
1813    match crate::writer::open_uncompressed_append(Path::new(filename)) {
1814        Ok(file) => into_rkr_writer(Box::new(file), Some(precision)),
1815        Err(err) => {
1816            set_last_error(
1817                RKRStatus::RKR_STATUS_IO_ERROR as i32,
1818                &err.to_string(),
1819                0,
1820                0,
1821            );
1822            ptr::null_mut()
1823        }
1824    }
1825}
1826
1827/// Flushes buffered CON data and reports write errors.
1828///
1829/// On failure the status is `RKR_STATUS_IO_ERROR` and
1830/// [`rkr_last_error_message`] returns the underlying I/O text.
1831///
1832/// # Safety
1833/// writer_handle must be a live writer handle or null.
1834#[unsafe(no_mangle)]
1835pub unsafe extern "C" fn rkr_writer_flush(writer_handle: *mut RKRConFrameWriter) -> RKRStatus {
1836    let writer = match unsafe { (writer_handle as *mut RkrWriter).as_mut() } {
1837        Some(w) => w,
1838        None => return note(RKRStatus::RKR_STATUS_NULL_POINTER),
1839    };
1840    match writer.flush() {
1841        Ok(()) => {
1842            clear_last_error();
1843            RKRStatus::RKR_STATUS_SUCCESS
1844        }
1845        Err(err) => {
1846            set_last_error(
1847                RKRStatus::RKR_STATUS_IO_ERROR as i32,
1848                &err.to_string(),
1849                0,
1850                0,
1851            );
1852            RKRStatus::RKR_STATUS_IO_ERROR
1853        }
1854    }
1855}
1856
1857/// Frees the memory for an `RKRConFrameWriter`, closing the associated file.
1858///
1859/// # Safety
1860/// writer_handle must be valid or null.
1861#[unsafe(no_mangle)]
1862pub unsafe extern "C" fn free_rkr_writer(writer_handle: *mut RKRConFrameWriter) {
1863    if !writer_handle.is_null() {
1864        let _ = unsafe { Box::from_raw(writer_handle as *mut RkrWriter) };
1865    }
1866}
1867/// Rebuild a parsed frame the way the Python, Julia, and Fortran writers do.
1868///
1869/// The builder stamps `con_spec_minor` when the file omitted it. The caller
1870/// owns the returned frame and must free it with `free_rkr_frame`. Returns
1871/// NULL on a null argument or when the rebuild fails.
1872///
1873/// # Safety
1874/// `frame_handle` must be a valid frame or null.
1875#[unsafe(no_mangle)]
1876pub unsafe extern "C" fn rkr_frame_binding_rewrite(
1877    frame_handle: *const RKRConFrame,
1878) -> *mut RKRConFrame {
1879    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
1880        return ptr::null_mut();
1881    };
1882    match binding_rewrite_frame(frame) {
1883        Ok(rewritten) => Box::into_raw(Box::new(rewritten)) as *mut RKRConFrame,
1884        Err(_) => ptr::null_mut(),
1885    }
1886}
1887
1888/// Write frames with the binding metadata stamp and the caller's atoms.
1889///
1890/// Unlike [`rkr_frame_binding_rewrite`], this does not allocate a second
1891/// copy of the atoms. The stamp is restored before the function returns.
1892/// A format failure stays `RKR_STATUS_IO_ERROR`, and
1893/// [`rkr_last_error_message`] returns the underlying text.
1894///
1895/// # Safety
1896/// `writer_handle` and `frame_handles` must be valid. Each frame is mutated
1897/// only for the metadata map, and that map is restored.
1898#[unsafe(no_mangle)]
1899pub unsafe extern "C" fn rkr_writer_extend_binding(
1900    writer_handle: *mut RKRConFrameWriter,
1901    frame_handles: *const *mut RKRConFrame,
1902    num_frames: usize,
1903) -> RKRStatus {
1904    let writer = match unsafe { (writer_handle as *mut RkrWriter).as_mut() } {
1905        Some(w) => w,
1906        None => return note(RKRStatus::RKR_STATUS_NULL_POINTER),
1907    };
1908    if frame_handles.is_null() && num_frames > 0 {
1909        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
1910    }
1911    for i in 0..num_frames {
1912        let handle = unsafe { *frame_handles.add(i) };
1913        let Some(frame) = (unsafe { (handle as *mut ConFrame).as_mut() }) else {
1914            return note(RKRStatus::RKR_STATUS_NULL_POINTER);
1915        };
1916        if let Err(err) = writer.write_frame_binding(frame) {
1917            set_last_error(
1918                RKRStatus::RKR_STATUS_IO_ERROR as i32,
1919                &err.to_string(),
1920                0,
1921                0,
1922            );
1923            return RKRStatus::RKR_STATUS_IO_ERROR;
1924        }
1925    }
1926    clear_last_error();
1927    RKRStatus::RKR_STATUS_SUCCESS
1928}
1929
1930/// Writes multiple frames from an array of handles to the file managed by the writer.
1931/// Returns `RKR_STATUS_SUCCESS` on success, or an error code.
1932///
1933/// Format failures such as a repeated atom id stay `RKR_STATUS_IO_ERROR`.
1934/// [`rkr_last_error_message`] returns the underlying text, which
1935/// [`rkr_status_message`] does not carry.
1936///
1937/// # Safety
1938/// writer_handle and frame_handles must be valid.
1939#[unsafe(no_mangle)]
1940pub unsafe extern "C" fn rkr_writer_extend(
1941    writer_handle: *mut RKRConFrameWriter,
1942    frame_handles: *const *const RKRConFrame,
1943    num_frames: usize,
1944) -> RKRStatus {
1945    let writer = match unsafe { (writer_handle as *mut RkrWriter).as_mut() } {
1946        Some(w) => w,
1947        None => return note(RKRStatus::RKR_STATUS_NULL_POINTER),
1948    };
1949    if frame_handles.is_null() {
1950        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
1951    }
1952    let handles_slice = unsafe { std::slice::from_raw_parts(frame_handles, num_frames) };
1953    let mut rust_frames: Vec<&ConFrame> = Vec::with_capacity(num_frames);
1954    if handles_slice.iter().any(|&handle| handle.is_null()) {
1955        // Fail fast if any handle is null, as this indicates a bug on the
1956        // caller's side.
1957        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
1958    }
1959    for &handle in handles_slice.iter() {
1960        // Assume the handle is valid.
1961        match unsafe { (handle as *const ConFrame).as_ref() } {
1962            Some(frame) => rust_frames.push(frame),
1963            // This case should be unreachable if the handle is not null, but we handle it for safety.
1964            None => return note(RKRStatus::RKR_STATUS_NULL_POINTER),
1965        }
1966    }
1967    match writer.extend(rust_frames.into_iter()) {
1968        Ok(_) => {
1969            clear_last_error();
1970            RKRStatus::RKR_STATUS_SUCCESS
1971        }
1972        Err(err) => {
1973            set_last_error(
1974                RKRStatus::RKR_STATUS_IO_ERROR as i32,
1975                &err.to_string(),
1976                0,
1977                0,
1978            );
1979            RKRStatus::RKR_STATUS_IO_ERROR
1980        }
1981    }
1982}
1983
1984/// Serializes frames to a newly allocated CON string. No file is created.
1985///
1986/// On success `*out_text` is a NUL-terminated buffer of `*out_len` payload
1987/// bytes (the NUL is not included in the length). Free it with
1988/// [`rkr_free_string`]. The bytes match `create_writer_from_path_c` writing
1989/// the same frames. `num_frames == 0` yields an empty string and accepts a
1990/// null `frame_handles`.
1991///
1992/// # Safety
1993/// `out_text` and `out_len` must be valid. Each frame handle must be valid
1994/// when `num_frames > 0`.
1995#[unsafe(no_mangle)]
1996pub unsafe extern "C" fn rkr_write_frames_to_string(
1997    frame_handles: *const *const RKRConFrame,
1998    num_frames: usize,
1999    out_text: *mut *mut c_char,
2000    out_len: *mut usize,
2001) -> RKRStatus {
2002    if out_text.is_null() || out_len.is_null() {
2003        return RKRStatus::RKR_STATUS_NULL_POINTER;
2004    }
2005    unsafe {
2006        *out_text = ptr::null_mut();
2007        *out_len = 0;
2008    }
2009    if num_frames > 0 && frame_handles.is_null() {
2010        return RKRStatus::RKR_STATUS_NULL_POINTER;
2011    }
2012    let mut buffer = Vec::new();
2013    {
2014        let mut writer = ConFrameWriter::new(&mut buffer);
2015        for i in 0..num_frames {
2016            let handle = unsafe { *frame_handles.add(i) };
2017            let Some(frame) = (unsafe { (handle as *const ConFrame).as_ref() }) else {
2018                return RKRStatus::RKR_STATUS_NULL_POINTER;
2019            };
2020            if let Err(err) = writer.write_frame(frame) {
2021                set_last_error(
2022                    RKRStatus::RKR_STATUS_IO_ERROR as i32,
2023                    &err.to_string(),
2024                    0,
2025                    0,
2026                );
2027                return RKRStatus::RKR_STATUS_IO_ERROR;
2028            }
2029        }
2030    }
2031    let len = buffer.len();
2032    match CString::new(buffer) {
2033        Ok(text) => {
2034            unsafe {
2035                *out_text = text.into_raw();
2036                *out_len = len;
2037            }
2038            clear_last_error();
2039            RKRStatus::RKR_STATUS_SUCCESS
2040        }
2041        Err(_) => {
2042            set_last_error(
2043                RKRStatus::RKR_STATUS_IO_ERROR as i32,
2044                "serialized CON contains an interior NUL",
2045                0,
2046                0,
2047            );
2048            RKRStatus::RKR_STATUS_IO_ERROR
2049        }
2050    }
2051}
2052
2053/// Enable (`canonical != 0`) or disable campaign-stable CON serialization on an open writer.
2054/// Matches Rust `ConFrameWriter::canonical(true)` (deterministic metadata key order).
2055///
2056/// # Safety
2057/// `writer_handle` must be valid or null (null → `RKR_STATUS_NULL_POINTER`).
2058#[unsafe(no_mangle)]
2059pub unsafe extern "C" fn rkr_writer_set_canonical(
2060    writer_handle: *mut RKRConFrameWriter,
2061    canonical: u8,
2062) -> RKRStatus {
2063    let writer = match unsafe { (writer_handle as *mut RkrWriter).as_mut() } {
2064        Some(w) => w,
2065        None => return note(RKRStatus::RKR_STATUS_NULL_POINTER),
2066    };
2067    writer.set_canonical(canonical != 0);
2068    note(RKRStatus::RKR_STATUS_SUCCESS)
2069}
2070
2071/// Returns 1 if the writer is in canonical mode, 0 otherwise (or on null handle).
2072/// # Safety
2073///
2074/// A non-null pointer argument must point at a live value of its declared
2075/// type for this call. A null pointer is handled inside the function.
2076#[unsafe(no_mangle)]
2077pub unsafe extern "C" fn rkr_writer_is_canonical(writer_handle: *const RKRConFrameWriter) -> u8 {
2078    match unsafe { (writer_handle as *const RkrWriter).as_ref() } {
2079        Some(w) => u8::from(w.is_canonical()),
2080        None => 0,
2081    }
2082}
2083
2084#[cfg(test)]
2085mod index_proj_ffi_tests {
2086    use super::*;
2087    use std::ffi::CStr;
2088    use std::fs;
2089    use std::path::PathBuf;
2090
2091    fn fixture_path() -> PathBuf {
2092        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/tiny_cuh2.con")
2093    }
2094
2095    #[test]
2096    fn ffi_projection_matches_index_proj() {
2097        let frames = crate::iterators::read_all_frames(&fixture_path()).unwrap();
2098        let fr = &frames[0];
2099        let handle = fr as *const ConFrame as *const RKRConFrame;
2100        let proj = crate::index_proj::FrameIndexProjection::from_frame(fr);
2101        // Full eight-surface campaign contract (plus JSON) via shipped C symbols.
2102        assert_eq!(rkr_frame_index_natoms(handle), proj.n_atoms);
2103        assert_eq!(rkr_frame_sections_mask(handle), proj.sections_mask);
2104        let formula_c = unsafe { rkr_frame_composition_formula(handle) };
2105        assert!(!formula_c.is_null());
2106        let formula = unsafe { CStr::from_ptr(formula_c) }.to_str().unwrap();
2107        assert_eq!(formula, proj.formula);
2108        unsafe { rkr_free_string(formula_c) };
2109        let ie = rkr_frame_index_energy(handle);
2110        match proj.energy {
2111            Some(e) => assert!((ie - e).abs() < 1e-12 || (ie.is_nan() && e.is_nan())),
2112            None => assert!(ie.is_nan()),
2113        }
2114        let tm = rkr_frame_total_mass(handle);
2115        match proj.total_mass {
2116            Some(m) => assert!((tm - m).abs() < 1e-9, "total_mass C={tm} proj={m}"),
2117            None => assert!(tm.is_nan()),
2118        }
2119        let cv = rkr_frame_cell_volume(handle);
2120        match proj.cell_volume {
2121            Some(v) => assert!(
2122                (cv - v).abs() < 1e-6 * v.max(1.0),
2123                "cell_volume C={cv} proj={v}"
2124            ),
2125            None => assert!(cv.is_nan()),
2126        }
2127        let fm = rkr_frame_fmax(handle);
2128        match proj.fmax {
2129            Some(f) => assert!((fm - f).abs() < 1e-12 || (fm.is_nan() && f.is_nan())),
2130            None => assert!(fm.is_nan()),
2131        }
2132        let json_c = unsafe { rkr_frame_index_projection_json(handle) };
2133        assert!(!json_c.is_null());
2134        let json = unsafe { CStr::from_ptr(json_c) }.to_str().unwrap();
2135        assert!(json.contains("\"formula\""));
2136        assert!(json.contains(&proj.formula) || proj.formula.is_empty());
2137        assert!(json.contains("\"n_atoms\""));
2138        assert!(json.contains("\"total_mass\"") || json.contains("\"cell_volume\""));
2139        unsafe { rkr_free_string(json_c) };
2140    }
2141
2142    #[test]
2143    fn ffi_canonical_writer_byte_identical() {
2144        let frames = crate::iterators::read_all_frames(&fixture_path()).unwrap();
2145        let fr = &frames[0];
2146        let dir = tempfile::tempdir().unwrap();
2147        let p1 = dir.path().join("a.con");
2148        let p2 = dir.path().join("b.con");
2149        for p in [&p1, &p2] {
2150            let path_c = std::ffi::CString::new(p.to_str().unwrap()).unwrap();
2151            let w = unsafe { create_writer_from_path_c(path_c.as_ptr()) };
2152            assert!(!w.is_null());
2153            assert_eq!(
2154                unsafe { rkr_writer_set_canonical(w, 1) },
2155                note(RKRStatus::RKR_STATUS_SUCCESS)
2156            );
2157            assert_eq!(unsafe { rkr_writer_is_canonical(w) }, 1);
2158            let handles = [fr as *const ConFrame as *const RKRConFrame];
2159            assert_eq!(
2160                unsafe { rkr_writer_extend(w, handles.as_ptr(), 1) },
2161                note(RKRStatus::RKR_STATUS_SUCCESS)
2162            );
2163            unsafe { free_rkr_writer(w) };
2164        }
2165        let b1 = fs::read(&p1).unwrap();
2166        let b2 = fs::read(&p2).unwrap();
2167        assert_eq!(b1, b2);
2168        assert!(!b1.is_empty());
2169    }
2170}
2171//=============================================================================
2172// Writer with Precision
2173//=============================================================================
2174/// Creates a new frame writer with custom floating-point precision.
2175/// The caller OWNS the returned pointer and MUST call `free_rkr_writer`.
2176///
2177/// # Safety
2178/// filename_c must be valid. The caller takes ownership of the returned writer.
2179#[unsafe(no_mangle)]
2180pub unsafe extern "C" fn create_writer_from_path_with_precision_c(
2181    filename_c: *const c_char,
2182    precision: u8,
2183) -> *mut RKRConFrameWriter {
2184    let filename = match unsafe { cstr_path(filename_c) } {
2185        Some(s) => s,
2186        None => return null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
2187    };
2188    match File::create(filename) {
2189        Ok(file) => into_rkr_writer(Box::new(file), Some(precision)),
2190        Err(_) => null_err::<_>(RKRStatus::RKR_STATUS_IO_ERROR),
2191    }
2192}
2193//=============================================================================
2194// Frame Builder FFI (construct ConFrame from C data)
2195//=============================================================================
2196/// An opaque handle to a Rust `ConFrameBuilder` object.
2197// No #[repr(C)]: cbindgen then emits an incomplete struct, which C and C++
2198// accept under -pedantic. The zero-length field keeps it unconstructible.
2199pub struct RKRConFrameBuilder {
2200    _private: [u8; 0],
2201}
2202#[allow(clippy::too_many_arguments)]
2203unsafe fn add_builder_atom(
2204    builder_handle: *mut RKRConFrameBuilder,
2205    symbol: *const c_char,
2206    x: f64,
2207    y: f64,
2208    z: f64,
2209    fixed: [bool; 3],
2210    atom_id: u64,
2211    mass: f64,
2212    velocity: Option<[f64; 3]>,
2213    forces: Option<[f64; 3]>,
2214) -> RKRStatus {
2215    if builder_handle.is_null() || symbol.is_null() {
2216        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2217    }
2218    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2219    let sym = match unsafe { CStr::from_ptr(symbol).to_str() } {
2220        Ok(s) => s,
2221        Err(_) => return note(RKRStatus::RKR_STATUS_INVALID_UTF8),
2222    };
2223    builder.add_atom(sym, x, y, z, fixed, atom_id, mass);
2224    if let Some(v) = velocity {
2225        builder.with_velocity(v);
2226    }
2227    if let Some(f) = forces {
2228        builder.with_force(f);
2229    }
2230    note(RKRStatus::RKR_STATUS_SUCCESS)
2231}
2232/// Attaches a velocity vector to the most recently added atom on a builder.
2233/// No-op if no atom has been added yet.
2234///
2235/// # Safety
2236/// builder_handle must be valid. velocity must point to 3 contiguous f64 values.
2237#[unsafe(no_mangle)]
2238pub unsafe extern "C" fn rkr_frame_builder_set_last_velocity(
2239    builder_handle: *mut RKRConFrameBuilder,
2240    velocity: *const f64,
2241) -> RKRStatus {
2242    if builder_handle.is_null() || velocity.is_null() {
2243        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2244    }
2245    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2246    let v = unsafe { [*velocity, *velocity.add(1), *velocity.add(2)] };
2247    builder.with_velocity(v);
2248    note(RKRStatus::RKR_STATUS_SUCCESS)
2249}
2250/// Attaches a force vector to the most recently added atom on a builder.
2251/// No-op if no atom has been added yet.
2252///
2253/// # Safety
2254/// builder_handle must be valid. force must point to 3 contiguous f64 values.
2255#[unsafe(no_mangle)]
2256pub unsafe extern "C" fn rkr_frame_builder_set_last_force(
2257    builder_handle: *mut RKRConFrameBuilder,
2258    force: *const f64,
2259) -> RKRStatus {
2260    if builder_handle.is_null() || force.is_null() {
2261        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2262    }
2263    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2264    let f = unsafe { [*force, *force.add(1), *force.add(2)] };
2265    builder.with_force(f);
2266    note(RKRStatus::RKR_STATUS_SUCCESS)
2267}
2268/// Attaches a displacement vector (Angstrom) to the most recently added
2269/// atom on a builder. No-op if no atom has been added yet.
2270///
2271/// # Safety
2272/// builder_handle must be valid. displacement must point to 3 contiguous
2273/// f64 values.
2274#[unsafe(no_mangle)]
2275pub unsafe extern "C" fn rkr_frame_builder_set_last_displacement(
2276    builder_handle: *mut RKRConFrameBuilder,
2277    displacement: *const f64,
2278) -> RKRStatus {
2279    if builder_handle.is_null() || displacement.is_null() {
2280        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2281    }
2282    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2283    let d = unsafe { [*displacement, *displacement.add(1), *displacement.add(2)] };
2284    builder.with_displacement(d);
2285    note(RKRStatus::RKR_STATUS_SUCCESS)
2286}
2287/// Attaches a spread vector (Angstrom) to the most recently added
2288/// atom on a builder. No-op if no atom has been added yet.
2289///
2290/// # Safety
2291/// builder_handle must be valid. spread must point to 3 contiguous
2292/// f64 values.
2293#[unsafe(no_mangle)]
2294pub unsafe extern "C" fn rkr_frame_builder_set_last_spread(
2295    builder_handle: *mut RKRConFrameBuilder,
2296    spread: *const f64,
2297) -> RKRStatus {
2298    if builder_handle.is_null() || spread.is_null() {
2299        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2300    }
2301    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2302    let d = unsafe { [*spread, *spread.add(1), *spread.add(2)] };
2303    builder.with_spread(d);
2304    note(RKRStatus::RKR_STATUS_SUCCESS)
2305}
2306/// Attaches a per-atom energy to the most recently added atom on a
2307/// builder. No-op if no atom has been added yet.
2308///
2309/// Use this together with the per-frame `energy` metadata key when a
2310/// caller wants to round-trip an "Energies of Component" decomposition
2311/// alongside the total.
2312///
2313/// # Safety
2314/// builder_handle must be valid.
2315#[unsafe(no_mangle)]
2316pub unsafe extern "C" fn rkr_frame_builder_set_last_energy(
2317    builder_handle: *mut RKRConFrameBuilder,
2318    energy: f64,
2319) -> RKRStatus {
2320    if builder_handle.is_null() {
2321        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2322    }
2323    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2324    builder.with_energy(energy);
2325    note(RKRStatus::RKR_STATUS_SUCCESS)
2326}
2327// ----- v0.11.0 in-place mutation FFI ---------------------------------------
2328//
2329// Mirrors `ConFrameBuilder::set_atom_* / clear_atom_* / *_from_flat /
2330// get_atom_* / atom_count` for C / C++ / Python / Julia consumers. All
2331// mutators return RKRStatus; getters return raw values via out-parameters
2332// (so a caller can distinguish "atom has no force" from "successful read of
2333// f={0,0,0}" via the `has_*` boolean out-parameter).
2334//
2335// IndexOutOfBounds errors from the Rust side surface as
2336// RKR_STATUS_INDEX_OUT_OF_BOUNDS; all NULL-handle / NULL-out-pointer paths
2337// return RKR_STATUS_NULL_POINTER. Bulk setters with the wrong length return
2338// RKR_STATUS_INDEX_OUT_OF_BOUNDS as well (the caller sized the buffer
2339// wrong).
2340fn map_builder_err(e: crate::error::ParseError) -> RKRStatus {
2341    use crate::error::ParseError;
2342    match e {
2343        ParseError::IndexOutOfBounds { .. } | ParseError::InvalidVectorLength { .. } => {
2344            note(RKRStatus::RKR_STATUS_INDEX_OUT_OF_BOUNDS)
2345        }
2346        ParseError::MassMismatch { .. } | ParseError::ValidationError(_) => {
2347            note(RKRStatus::RKR_STATUS_VALIDATION_ERROR)
2348        }
2349        _ => note(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
2350    }
2351}
2352/// Returns the number of atoms currently held in the builder.
2353///
2354/// # Safety
2355/// builder_handle must be a valid pointer returned by rkr_frame_new and
2356/// not yet consumed by rkr_frame_builder_build / freed.
2357/// Returns 0 on NULL handle.
2358#[unsafe(no_mangle)]
2359pub unsafe extern "C" fn rkr_frame_builder_atom_count(
2360    builder_handle: *const RKRConFrameBuilder,
2361) -> usize {
2362    if builder_handle.is_null() {
2363        return 0;
2364    }
2365    let builder = unsafe { &*(builder_handle as *const ConFrameBuilder) };
2366    builder.atom_count()
2367}
2368/// Updates the Cartesian position of an existing atom.
2369/// # Safety
2370/// builder_handle must be valid.
2371#[unsafe(no_mangle)]
2372pub unsafe extern "C" fn rkr_frame_builder_set_atom_position(
2373    builder_handle: *mut RKRConFrameBuilder,
2374    index: usize,
2375    x: f64,
2376    y: f64,
2377    z: f64,
2378) -> RKRStatus {
2379    if builder_handle.is_null() {
2380        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2381    }
2382    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2383    match builder.set_atom_position(index, x, y, z) {
2384        Ok(_) => note(RKRStatus::RKR_STATUS_SUCCESS),
2385        Err(e) => map_builder_err(e),
2386    }
2387}
2388/// Sets the velocity vector of an existing atom from 3 contiguous f64 values.
2389/// # Safety
2390/// builder_handle must be valid; velocity must point to 3 contiguous f64.
2391#[unsafe(no_mangle)]
2392pub unsafe extern "C" fn rkr_frame_builder_set_atom_velocity(
2393    builder_handle: *mut RKRConFrameBuilder,
2394    index: usize,
2395    velocity: *const f64,
2396) -> RKRStatus {
2397    if builder_handle.is_null() || velocity.is_null() {
2398        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2399    }
2400    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2401    let v = unsafe { [*velocity, *velocity.add(1), *velocity.add(2)] };
2402    match builder.set_atom_velocity(index, v) {
2403        Ok(_) => note(RKRStatus::RKR_STATUS_SUCCESS),
2404        Err(e) => map_builder_err(e),
2405    }
2406}
2407/// Sets the force vector of an existing atom from 3 contiguous f64 values.
2408/// # Safety
2409/// builder_handle must be valid; force must point to 3 contiguous f64.
2410#[unsafe(no_mangle)]
2411pub unsafe extern "C" fn rkr_frame_builder_set_atom_force(
2412    builder_handle: *mut RKRConFrameBuilder,
2413    index: usize,
2414    force: *const f64,
2415) -> RKRStatus {
2416    if builder_handle.is_null() || force.is_null() {
2417        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2418    }
2419    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2420    let f = unsafe { [*force, *force.add(1), *force.add(2)] };
2421    match builder.set_atom_force(index, f) {
2422        Ok(_) => note(RKRStatus::RKR_STATUS_SUCCESS),
2423        Err(e) => map_builder_err(e),
2424    }
2425}
2426/// Sets the displacement vector (Angstrom) of an existing atom from 3
2427/// contiguous f64 values.
2428/// # Safety
2429/// builder_handle must be valid; displacement must point to 3 contiguous f64.
2430#[unsafe(no_mangle)]
2431pub unsafe extern "C" fn rkr_frame_builder_set_atom_displacement(
2432    builder_handle: *mut RKRConFrameBuilder,
2433    index: usize,
2434    displacement: *const f64,
2435) -> RKRStatus {
2436    if builder_handle.is_null() || displacement.is_null() {
2437        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2438    }
2439    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2440    let d = unsafe { [*displacement, *displacement.add(1), *displacement.add(2)] };
2441    match builder.set_atom_displacement(index, d) {
2442        Ok(_) => note(RKRStatus::RKR_STATUS_SUCCESS),
2443        Err(e) => map_builder_err(e),
2444    }
2445}
2446/// Sets the spread vector (Angstrom) of an existing atom from 3
2447/// contiguous f64 values.
2448/// # Safety
2449/// builder_handle must be valid; spread must point to 3 contiguous f64.
2450#[unsafe(no_mangle)]
2451pub unsafe extern "C" fn rkr_frame_builder_set_atom_spread(
2452    builder_handle: *mut RKRConFrameBuilder,
2453    index: usize,
2454    spread: *const f64,
2455) -> RKRStatus {
2456    if builder_handle.is_null() || spread.is_null() {
2457        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2458    }
2459    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2460    let d = unsafe { [*spread, *spread.add(1), *spread.add(2)] };
2461    match builder.set_atom_spread(index, d) {
2462        Ok(_) => note(RKRStatus::RKR_STATUS_SUCCESS),
2463        Err(e) => map_builder_err(e),
2464    }
2465}
2466/// Sets the per-atom energy contribution of an existing atom.
2467/// # Safety
2468/// builder_handle must be valid.
2469#[unsafe(no_mangle)]
2470pub unsafe extern "C" fn rkr_frame_builder_set_atom_energy(
2471    builder_handle: *mut RKRConFrameBuilder,
2472    index: usize,
2473    energy: f64,
2474) -> RKRStatus {
2475    if builder_handle.is_null() {
2476        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2477    }
2478    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2479    match builder.set_atom_energy(index, energy) {
2480        Ok(_) => note(RKRStatus::RKR_STATUS_SUCCESS),
2481        Err(e) => map_builder_err(e),
2482    }
2483}
2484/// Updates per-direction fixed flags `[fixed_x, fixed_y, fixed_z]`.
2485/// # Safety
2486/// builder_handle must be valid.
2487#[unsafe(no_mangle)]
2488pub unsafe extern "C" fn rkr_frame_builder_set_atom_fixed(
2489    builder_handle: *mut RKRConFrameBuilder,
2490    index: usize,
2491    fixed_x: bool,
2492    fixed_y: bool,
2493    fixed_z: bool,
2494) -> RKRStatus {
2495    if builder_handle.is_null() {
2496        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2497    }
2498    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2499    match builder.set_atom_fixed(index, [fixed_x, fixed_y, fixed_z]) {
2500        Ok(_) => note(RKRStatus::RKR_STATUS_SUCCESS),
2501        Err(e) => map_builder_err(e),
2502    }
2503}
2504/// Updates the mass of an existing atom.
2505/// # Safety
2506/// builder_handle must be valid.
2507#[unsafe(no_mangle)]
2508pub unsafe extern "C" fn rkr_frame_builder_set_atom_mass(
2509    builder_handle: *mut RKRConFrameBuilder,
2510    index: usize,
2511    mass: f64,
2512) -> RKRStatus {
2513    if builder_handle.is_null() {
2514        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2515    }
2516    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2517    match builder.set_atom_mass(index, mass) {
2518        Ok(_) => note(RKRStatus::RKR_STATUS_SUCCESS),
2519        Err(e) => map_builder_err(e),
2520    }
2521}
2522/// Updates the atom_id (pre-grouping index from .con column 5) of an
2523/// existing atom. The underlying `Array1<u64>` buffer pointer stays
2524/// stable; callers that hold a raw `*const u64` via
2525/// `rkr_frame_builder_atom_ids_data` do not need to refresh after this.
2526/// # Safety
2527/// builder_handle must be valid.
2528#[unsafe(no_mangle)]
2529pub unsafe extern "C" fn rkr_frame_builder_set_atom_id(
2530    builder_handle: *mut RKRConFrameBuilder,
2531    index: usize,
2532    atom_id: u64,
2533) -> RKRStatus {
2534    if builder_handle.is_null() {
2535        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2536    }
2537    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2538    match builder.set_atom_id(index, atom_id) {
2539        Ok(_) => note(RKRStatus::RKR_STATUS_SUCCESS),
2540        Err(e) => map_builder_err(e),
2541    }
2542}
2543/// Removes velocity / force / energy data from an existing atom.
2544/// # Safety
2545/// builder_handle must be valid.
2546#[unsafe(no_mangle)]
2547pub unsafe extern "C" fn rkr_frame_builder_clear_atom_velocity(
2548    builder_handle: *mut RKRConFrameBuilder,
2549    index: usize,
2550) -> RKRStatus {
2551    if builder_handle.is_null() {
2552        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2553    }
2554    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2555    match builder.clear_atom_velocity(index) {
2556        Ok(_) => note(RKRStatus::RKR_STATUS_SUCCESS),
2557        Err(e) => map_builder_err(e),
2558    }
2559}
2560/// # Safety
2561/// builder_handle must be valid.
2562#[unsafe(no_mangle)]
2563pub unsafe extern "C" fn rkr_frame_builder_clear_atom_force(
2564    builder_handle: *mut RKRConFrameBuilder,
2565    index: usize,
2566) -> RKRStatus {
2567    if builder_handle.is_null() {
2568        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2569    }
2570    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2571    match builder.clear_atom_force(index) {
2572        Ok(_) => note(RKRStatus::RKR_STATUS_SUCCESS),
2573        Err(e) => map_builder_err(e),
2574    }
2575}
2576/// # Safety
2577/// builder_handle must be valid.
2578#[unsafe(no_mangle)]
2579pub unsafe extern "C" fn rkr_frame_builder_clear_atom_displacement(
2580    builder_handle: *mut RKRConFrameBuilder,
2581    index: usize,
2582) -> RKRStatus {
2583    if builder_handle.is_null() {
2584        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2585    }
2586    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2587    match builder.clear_atom_displacement(index) {
2588        Ok(_) => note(RKRStatus::RKR_STATUS_SUCCESS),
2589        Err(e) => map_builder_err(e),
2590    }
2591}
2592/// # Safety
2593/// builder_handle must be valid.
2594#[unsafe(no_mangle)]
2595pub unsafe extern "C" fn rkr_frame_builder_clear_atom_spread(
2596    builder_handle: *mut RKRConFrameBuilder,
2597    index: usize,
2598) -> RKRStatus {
2599    if builder_handle.is_null() {
2600        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2601    }
2602    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2603    match builder.clear_atom_spread(index) {
2604        Ok(_) => note(RKRStatus::RKR_STATUS_SUCCESS),
2605        Err(e) => map_builder_err(e),
2606    }
2607}
2608/// # Safety
2609/// builder_handle must be valid.
2610#[unsafe(no_mangle)]
2611pub unsafe extern "C" fn rkr_frame_builder_clear_atom_energy(
2612    builder_handle: *mut RKRConFrameBuilder,
2613    index: usize,
2614) -> RKRStatus {
2615    if builder_handle.is_null() {
2616        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2617    }
2618    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2619    match builder.clear_atom_energy(index) {
2620        Ok(_) => note(RKRStatus::RKR_STATUS_SUCCESS),
2621        Err(e) => map_builder_err(e),
2622    }
2623}
2624/// Bulk-update positions for every atom from a flat row-major
2625/// `[x0,y0,z0,x1,y1,z1,...]` buffer of length `3 * atom_count()`.
2626/// # Safety
2627/// builder_handle must be valid; positions must point to `3 * len` f64.
2628#[unsafe(no_mangle)]
2629pub unsafe extern "C" fn rkr_frame_builder_set_positions_from_flat(
2630    builder_handle: *mut RKRConFrameBuilder,
2631    positions: *const f64,
2632    len: usize,
2633) -> RKRStatus {
2634    if builder_handle.is_null() || positions.is_null() {
2635        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2636    }
2637    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2638    let slice = unsafe { std::slice::from_raw_parts(positions, len) };
2639    match builder.set_positions_from_flat(slice) {
2640        Ok(_) => note(RKRStatus::RKR_STATUS_SUCCESS),
2641        Err(e) => map_builder_err(e),
2642    }
2643}
2644/// Bulk-update forces for every atom.
2645/// # Safety
2646/// builder_handle must be valid; forces must point to `3 * len` f64.
2647#[unsafe(no_mangle)]
2648pub unsafe extern "C" fn rkr_frame_builder_set_forces_from_flat(
2649    builder_handle: *mut RKRConFrameBuilder,
2650    forces: *const f64,
2651    len: usize,
2652) -> RKRStatus {
2653    if builder_handle.is_null() || forces.is_null() {
2654        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2655    }
2656    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2657    let slice = unsafe { std::slice::from_raw_parts(forces, len) };
2658    match builder.set_forces_from_flat(slice) {
2659        Ok(_) => note(RKRStatus::RKR_STATUS_SUCCESS),
2660        Err(e) => map_builder_err(e),
2661    }
2662}
2663/// Bulk-update displacements (Angstrom) for every atom.
2664/// # Safety
2665/// builder_handle must be valid; displacements must point to `len` f64
2666/// (`len == 3 * atom_count`).
2667#[unsafe(no_mangle)]
2668pub unsafe extern "C" fn rkr_frame_builder_set_displacements_from_flat(
2669    builder_handle: *mut RKRConFrameBuilder,
2670    displacements: *const f64,
2671    len: usize,
2672) -> RKRStatus {
2673    if builder_handle.is_null() || displacements.is_null() {
2674        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2675    }
2676    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2677    let slice = unsafe { std::slice::from_raw_parts(displacements, len) };
2678    match builder.set_displacements_from_flat(slice) {
2679        Ok(_) => note(RKRStatus::RKR_STATUS_SUCCESS),
2680        Err(e) => map_builder_err(e),
2681    }
2682}
2683/// Bulk-update spreads (Angstrom) for every atom.
2684/// # Safety
2685/// builder_handle must be valid; spreads must point to `len` f64
2686/// (`len == 3 * atom_count`).
2687#[unsafe(no_mangle)]
2688pub unsafe extern "C" fn rkr_frame_builder_set_spreads_from_flat(
2689    builder_handle: *mut RKRConFrameBuilder,
2690    spreads: *const f64,
2691    len: usize,
2692) -> RKRStatus {
2693    if builder_handle.is_null() || spreads.is_null() {
2694        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2695    }
2696    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2697    let slice = unsafe { std::slice::from_raw_parts(spreads, len) };
2698    match builder.set_spreads_from_flat(slice) {
2699        Ok(_) => note(RKRStatus::RKR_STATUS_SUCCESS),
2700        Err(e) => map_builder_err(e),
2701    }
2702}
2703/// Bulk-update per-atom energies (one f64 per atom).
2704/// # Safety
2705/// builder_handle must be valid; energies must point to `len` f64.
2706#[unsafe(no_mangle)]
2707pub unsafe extern "C" fn rkr_frame_builder_set_atom_energies_from_flat(
2708    builder_handle: *mut RKRConFrameBuilder,
2709    energies: *const f64,
2710    len: usize,
2711) -> RKRStatus {
2712    if builder_handle.is_null() || energies.is_null() {
2713        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2714    }
2715    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
2716    let slice = unsafe { std::slice::from_raw_parts(energies, len) };
2717    match builder.set_atom_energies_from_flat(slice) {
2718        Ok(_) => note(RKRStatus::RKR_STATUS_SUCCESS),
2719        Err(e) => map_builder_err(e),
2720    }
2721}
2722/// Reads the position of an existing atom into 3 contiguous f64 out values.
2723/// # Safety
2724/// builder_handle must be valid; out_xyz must point to 3 writable f64.
2725#[unsafe(no_mangle)]
2726pub unsafe extern "C" fn rkr_frame_builder_get_atom_position(
2727    builder_handle: *const RKRConFrameBuilder,
2728    index: usize,
2729    out_xyz: *mut f64,
2730) -> RKRStatus {
2731    if builder_handle.is_null() || out_xyz.is_null() {
2732        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2733    }
2734    let builder = unsafe { &*(builder_handle as *const ConFrameBuilder) };
2735    match builder.get_atom_position(index) {
2736        Ok((x, y, z)) => unsafe {
2737            *out_xyz = x;
2738            *out_xyz.add(1) = y;
2739            *out_xyz.add(2) = z;
2740            note(RKRStatus::RKR_STATUS_SUCCESS)
2741        },
2742        Err(e) => map_builder_err(e),
2743    }
2744}
2745/// Reads the velocity / force vector of an atom (if any) into 3 contiguous
2746/// f64. `*has_value` is set to `true` if the atom carries that vector,
2747/// `false` if it does not (in which case `out_xyz` is left untouched).
2748///
2749/// # Safety
2750/// builder_handle, out_xyz, has_value must all be valid pointers.
2751#[unsafe(no_mangle)]
2752pub unsafe extern "C" fn rkr_frame_builder_get_atom_velocity(
2753    builder_handle: *const RKRConFrameBuilder,
2754    index: usize,
2755    out_xyz: *mut f64,
2756    has_value: *mut bool,
2757) -> RKRStatus {
2758    if builder_handle.is_null() || out_xyz.is_null() || has_value.is_null() {
2759        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2760    }
2761    let builder = unsafe { &*(builder_handle as *const ConFrameBuilder) };
2762    match builder.get_atom_velocity(index) {
2763        Ok(Some(v)) => unsafe {
2764            *out_xyz = v[0];
2765            *out_xyz.add(1) = v[1];
2766            *out_xyz.add(2) = v[2];
2767            *has_value = true;
2768            note(RKRStatus::RKR_STATUS_SUCCESS)
2769        },
2770        Ok(None) => unsafe {
2771            *has_value = false;
2772            note(RKRStatus::RKR_STATUS_SUCCESS)
2773        },
2774        Err(e) => map_builder_err(e),
2775    }
2776}
2777/// # Safety
2778/// builder_handle, out_xyz, has_value must all be valid pointers.
2779#[unsafe(no_mangle)]
2780pub unsafe extern "C" fn rkr_frame_builder_get_atom_force(
2781    builder_handle: *const RKRConFrameBuilder,
2782    index: usize,
2783    out_xyz: *mut f64,
2784    has_value: *mut bool,
2785) -> RKRStatus {
2786    if builder_handle.is_null() || out_xyz.is_null() || has_value.is_null() {
2787        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2788    }
2789    let builder = unsafe { &*(builder_handle as *const ConFrameBuilder) };
2790    match builder.get_atom_force(index) {
2791        Ok(Some(f)) => unsafe {
2792            *out_xyz = f[0];
2793            *out_xyz.add(1) = f[1];
2794            *out_xyz.add(2) = f[2];
2795            *has_value = true;
2796            note(RKRStatus::RKR_STATUS_SUCCESS)
2797        },
2798        Ok(None) => unsafe {
2799            *has_value = false;
2800            note(RKRStatus::RKR_STATUS_SUCCESS)
2801        },
2802        Err(e) => map_builder_err(e),
2803    }
2804}
2805/// Reads the displacement of an atom (if any). `*has_value` is set to
2806/// `true` if the atom carries a displacement, else `false` and `out_xyz`
2807/// is left untouched.
2808/// # Safety
2809/// builder_handle, out_xyz, has_value must all be valid pointers.
2810#[unsafe(no_mangle)]
2811pub unsafe extern "C" fn rkr_frame_builder_get_atom_displacement(
2812    builder_handle: *const RKRConFrameBuilder,
2813    index: usize,
2814    out_xyz: *mut f64,
2815    has_value: *mut bool,
2816) -> RKRStatus {
2817    if builder_handle.is_null() || out_xyz.is_null() || has_value.is_null() {
2818        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2819    }
2820    let builder = unsafe { &*(builder_handle as *const ConFrameBuilder) };
2821    match builder.get_atom_displacement(index) {
2822        Ok(Some(d)) => unsafe {
2823            *out_xyz = d[0];
2824            *out_xyz.add(1) = d[1];
2825            *out_xyz.add(2) = d[2];
2826            *has_value = true;
2827            note(RKRStatus::RKR_STATUS_SUCCESS)
2828        },
2829        Ok(None) => unsafe {
2830            *has_value = false;
2831            note(RKRStatus::RKR_STATUS_SUCCESS)
2832        },
2833        Err(e) => map_builder_err(e),
2834    }
2835}
2836/// Reads the spread of an atom (if any). `*has_value` is set to
2837/// `true` if the atom carries a spread, else `false` and `out_xyz`
2838/// is left untouched.
2839/// # Safety
2840/// builder_handle, out_xyz, has_value must all be valid pointers.
2841#[unsafe(no_mangle)]
2842pub unsafe extern "C" fn rkr_frame_builder_get_atom_spread(
2843    builder_handle: *const RKRConFrameBuilder,
2844    index: usize,
2845    out_xyz: *mut f64,
2846    has_value: *mut bool,
2847) -> RKRStatus {
2848    if builder_handle.is_null() || out_xyz.is_null() || has_value.is_null() {
2849        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2850    }
2851    let builder = unsafe { &*(builder_handle as *const ConFrameBuilder) };
2852    match builder.get_atom_spread(index) {
2853        Ok(Some(d)) => unsafe {
2854            *out_xyz = d[0];
2855            *out_xyz.add(1) = d[1];
2856            *out_xyz.add(2) = d[2];
2857            *has_value = true;
2858            note(RKRStatus::RKR_STATUS_SUCCESS)
2859        },
2860        Ok(None) => unsafe {
2861            *has_value = false;
2862            note(RKRStatus::RKR_STATUS_SUCCESS)
2863        },
2864        Err(e) => map_builder_err(e),
2865    }
2866}
2867/// Reads the per-atom energy of an atom (if any). `*has_value` is set to
2868/// `true` if the atom carries an energy contribution, else `false` and
2869/// `*out_value` is left untouched.
2870/// # Safety
2871/// builder_handle, out_value, has_value must all be valid pointers.
2872#[unsafe(no_mangle)]
2873pub unsafe extern "C" fn rkr_frame_builder_get_atom_energy(
2874    builder_handle: *const RKRConFrameBuilder,
2875    index: usize,
2876    out_value: *mut f64,
2877    has_value: *mut bool,
2878) -> RKRStatus {
2879    if builder_handle.is_null() || out_value.is_null() || has_value.is_null() {
2880        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2881    }
2882    let builder = unsafe { &*(builder_handle as *const ConFrameBuilder) };
2883    match builder.get_atom_energy(index) {
2884        Ok(Some(e)) => unsafe {
2885            *out_value = e;
2886            *has_value = true;
2887            note(RKRStatus::RKR_STATUS_SUCCESS)
2888        },
2889        Ok(None) => unsafe {
2890            *has_value = false;
2891            note(RKRStatus::RKR_STATUS_SUCCESS)
2892        },
2893        Err(e) => map_builder_err(e),
2894    }
2895}
2896/// Reads the mass of an existing atom.
2897/// # Safety
2898/// builder_handle and out_mass must be valid pointers.
2899#[unsafe(no_mangle)]
2900pub unsafe extern "C" fn rkr_frame_builder_get_atom_mass(
2901    builder_handle: *const RKRConFrameBuilder,
2902    index: usize,
2903    out_mass: *mut f64,
2904) -> RKRStatus {
2905    if builder_handle.is_null() || out_mass.is_null() {
2906        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
2907    }
2908    let builder = unsafe { &*(builder_handle as *const ConFrameBuilder) };
2909    match builder.get_atom_mass(index) {
2910        Ok(m) => unsafe {
2911            *out_mass = m;
2912            note(RKRStatus::RKR_STATUS_SUCCESS)
2913        },
2914        Err(e) => map_builder_err(e),
2915    }
2916}
2917// ----- v0.11.0 DLPack tier-3 export FFI -------------------------------------
2918//
2919// Cross-language zero-copy via the DLPack 1.0 ABI. Each per-atom field of
2920// the builder is exported as an owning `DLManagedTensorVersioned*`. The
2921// caller is responsible for invoking the tensor's deleter callback to
2922// release the backing storage when finished. v0.11 ships the OWNING /
2923// CLONED variant: the tensor carries its own copy of the field data so it
2924// remains valid past the builder's lifetime. This is the conservative
2925// choice for cross-process / language-runtime consumers (Python GC,
2926// Julia GC, ...) where the consumer may outlive the Rust-side
2927// that hands out a non-owning view backed by `Arc<ndarray::Array<...>>`
2928// storage (matches metatensor v2's `Arc<RwLock<ArrayD<T>>>` pattern) for
2929// in-process zero-copy.
2930//
2931// Optional sections (velocities, forces, atom_energies) return
2932// RKR_STATUS_SECTION_ABSENT when the section is not declared on the
2933// builder; the out parameter is left untouched. Always-present fields
2934// (positions, masses, atom_ids) always return a tensor on success.
2935/// Re-export of dlpk's `DLManagedTensorVersioned` for the C ABI surface.
2936/// Defined here so cbindgen emits a forward declaration without pulling
2937/// in the full dlpk header; consumers include `<dlpack/dlpack.h>` (or
2938/// equivalent) and cast through the standard DLPack ABI.
2939pub use dlpk::sys::DLManagedTensorVersioned as RKRDLManagedTensorVersioned;
2940fn map_dlpack_err(e: crate::error::ParseError) -> RKRStatus {
2941    use crate::error::ParseError;
2942    match e {
2943        ParseError::ValidationError(ref msg) if msg.contains("device mismatch") => {
2944            note(RKRStatus::RKR_STATUS_DEVICE_MISMATCH)
2945        }
2946        ParseError::ValidationError(ref msg)
2947            if msg.contains("no device allocator") || msg.contains("allocator") =>
2948        {
2949            note(RKRStatus::RKR_STATUS_DEVICE_ALLOC_UNSUPPORTED)
2950        }
2951        ParseError::ValidationError(_) => note(RKRStatus::RKR_STATUS_VALIDATION_ERROR),
2952        _ => note(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
2953    }
2954}
2955/// DLPack `DLDataTypeCode` values (same numerics as `dlpack.h` / dlpk).
2956///
2957/// Use with [`RKRDLDataType::code`]. Common: `RKR_DL_FLOAT = 2`, `RKR_DL_UINT = 1`.
2958pub mod rkr_dl_type_code {
2959    pub const RKR_DL_INT: u8 = 0;
2960    pub const RKR_DL_UINT: u8 = 1;
2961    pub const RKR_DL_FLOAT: u8 = 2;
2962    pub const RKR_DL_OPAQUE_HANDLE: u8 = 3;
2963    pub const RKR_DL_BFLOAT: u8 = 4;
2964    pub const RKR_DL_COMPLEX: u8 = 5;
2965    pub const RKR_DL_BOOL: u8 = 6;
2966}
2967
2968/// DLPack `DLDeviceType` values (same numerics as `dlpack.h`). CPU = 1.
2969pub mod rkr_dl_device_type {
2970    pub const RKR_DL_CPU: i32 = 1;
2971    pub const RKR_DL_CUDA: i32 = 2;
2972    pub const RKR_DL_CUDA_HOST: i32 = 3;
2973}
2974
2975/// Element type request — **layout-identical** to DLPack `DLDataType`
2976/// (`uint8_t code`, `uint8_t bits`, `uint16_t lanes`). Interchangeable with
2977/// `DLDataType` from `<dlpack/dlpack.h>` when that header is included.
2978#[repr(C)]
2979#[derive(Clone, Copy, Debug)]
2980pub struct RKRDLDataType {
2981    /// `DLDataTypeCode` (e.g. [`rkr_dl_type_code::RKR_DL_FLOAT`]).
2982    pub code: u8,
2983    /// Bit width (32 or 64 for float sections today).
2984    pub bits: u8,
2985    /// Vector lanes (must be 1 for current exports).
2986    pub lanes: u16,
2987}
2988
2989/// Device request — **layout-identical** to DLPack `DLDevice`
2990/// (`DLDeviceType device_type`, `int32_t device_id`).
2991#[repr(C)]
2992#[derive(Clone, Copy, Debug)]
2993pub struct RKRDLDevice {
2994    /// `DLDeviceType` (e.g. [`rkr_dl_device_type::RKR_DL_CPU`]).
2995    pub device_type: i32,
2996    pub device_id: i32,
2997}
2998
2999/// Options for DLPack export: requested **DLPack** `DLDataType` + `DLDevice`.
3000///
3001/// Pass to `*_dlpack_ex`. NULL → `kDLFloat` / 64 / lanes 1 on **CPU**.
3002///
3003/// **Dtype (CPU):** any combination dlpk can host from converted CON data —
3004/// signed/unsigned ints (8/16/32/64), IEEE floats (32/64), and bool (8-bit
3005/// DLPack convention). Values are cast from on-disk binary64 (or u64 for atom
3006/// ids). Complex / bfloat / float8 / opaque / multi-lane types return
3007/// `RKR_STATUS_VALIDATION_ERROR` until implemented.
3008///
3009/// **Device:** `kDLCPU` always; with `--features cuda`, `kDLCUDA` performs H2D
3010/// into real device memory then exports DLPack. Other devices return
3011/// `RKR_STATUS_FEATURE_DISABLED` so callers can feature-detect.
3012#[repr(C)]
3013#[derive(Clone, Copy, Debug)]
3014pub struct RKRDlpackExportOptions {
3015    /// Requested element type (DLPack `DLDataType` layout).
3016    pub dtype: RKRDLDataType,
3017    /// Requested placement (DLPack `DLDevice` layout).
3018    pub device: RKRDLDevice,
3019}
3020
3021impl Default for RKRDlpackExportOptions {
3022    fn default() -> Self {
3023        Self {
3024            dtype: RKRDLDataType {
3025                code: rkr_dl_type_code::RKR_DL_FLOAT,
3026                bits: 64,
3027                lanes: 1,
3028            },
3029            device: RKRDLDevice {
3030                device_type: rkr_dl_device_type::RKR_DL_CPU,
3031                device_id: 0,
3032            },
3033        }
3034    }
3035}
3036
3037/// Resolve options; NULL → defaults.
3038/// CPU always; CUDA accepted when built with `--features cuda` (H2D export).
3039fn resolve_dlpack_opts(
3040    opts: *const RKRDlpackExportOptions,
3041) -> Result<RKRDlpackExportOptions, RKRStatus> {
3042    let o = if opts.is_null() {
3043        RKRDlpackExportOptions::default()
3044    } else {
3045        unsafe { *opts }
3046    };
3047    let dt = o.device.device_type;
3048    if dt == rkr_dl_device_type::RKR_DL_CPU {
3049        // ok
3050    } else if dt == rkr_dl_device_type::RKR_DL_CUDA {
3051        #[cfg(not(feature = "cuda"))]
3052        {
3053            return Err(RKRStatus::RKR_STATUS_FEATURE_DISABLED);
3054        }
3055        #[cfg(feature = "cuda")]
3056        {
3057            // accepted — H2D in frame as_dlpack / storage layer
3058        }
3059    } else {
3060        return Err(RKRStatus::RKR_STATUS_FEATURE_DISABLED);
3061    }
3062    if o.dtype.lanes != 1 {
3063        return Err(RKRStatus::RKR_STATUS_VALIDATION_ERROR);
3064    }
3065    Ok(o)
3066}
3067
3068fn finish_dlpack_tensor<E: std::fmt::Display>(
3069    result: Result<dlpk::DLPackTensor, E>,
3070    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3071) -> RKRStatus {
3072    match result {
3073        Ok(tensor) => {
3074            let raw = tensor.into_raw();
3075            unsafe {
3076                *out_tensor = raw.as_ptr();
3077            }
3078            note(RKRStatus::RKR_STATUS_SUCCESS)
3079        }
3080        Err(e) => map_dlpack_err(crate::error::ParseError::ValidationError(format!(
3081            "DLPack export failed: {e}"
3082        ))),
3083    }
3084}
3085
3086/// Cast CON `f64` samples into a DLPack tensor with the requested dtype (CPU).
3087/// `shape` is 1-D `[n]` or 2-D `[rows, cols]` with `rows * cols == data.len()`.
3088fn export_f64_slice_as_dlpack(
3089    data: &[f64],
3090    shape: &[usize],
3091    dtype: RKRDLDataType,
3092    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3093) -> RKRStatus {
3094    use rkr_dl_type_code::*;
3095    if dtype.lanes != 1 {
3096        return note(RKRStatus::RKR_STATUS_VALIDATION_ERROR);
3097    }
3098    macro_rules! arc_export {
3099        ($ty:ty, $map:expr) => {{
3100            let v: Vec<$ty> = data.iter().map($map).collect();
3101            match *shape {
3102                [r, c] => match ndarray::ArcArray2::from_shape_vec((r, c), v) {
3103                    Ok(a) => dlpk::DLPackTensor::try_from(a),
3104                    Err(_) => return note(RKRStatus::RKR_STATUS_VALIDATION_ERROR),
3105                },
3106                [_] => dlpk::DLPackTensor::try_from(ndarray::ArcArray1::from_vec(v)),
3107                _ => return note(RKRStatus::RKR_STATUS_VALIDATION_ERROR),
3108            }
3109        }};
3110    }
3111    let tensor = match (dtype.code, dtype.bits) {
3112        (RKR_DL_FLOAT, 64) => arc_export!(f64, |&x| x),
3113        (RKR_DL_FLOAT, 32) => arc_export!(f32, |&x| x as f32),
3114        (RKR_DL_INT, 8) => arc_export!(i8, |&x| x as i8),
3115        (RKR_DL_INT, 16) => arc_export!(i16, |&x| x as i16),
3116        (RKR_DL_INT, 32) => arc_export!(i32, |&x| x as i32),
3117        (RKR_DL_INT, 64) => arc_export!(i64, |&x| x as i64),
3118        (RKR_DL_UINT, 8) => arc_export!(u8, |&x| x as u8),
3119        (RKR_DL_UINT, 16) => arc_export!(u16, |&x| x as u16),
3120        (RKR_DL_UINT, 32) => arc_export!(u32, |&x| x as u32),
3121        (RKR_DL_UINT, 64) => arc_export!(u64, |&x| x as u64),
3122        (RKR_DL_BOOL, 8) => {
3123            // bool has no ndarray Zero; use Vec → DLPack (1-D length = element count)
3124            let v: Vec<bool> = data.iter().map(|&x| x != 0.0).collect();
3125            return finish_dlpack_tensor(dlpk::DLPackTensor::try_from(v), out_tensor);
3126        }
3127        // Complex / bfloat / float8 / opaque: not hosted from CON f64 yet
3128        _ => return note(RKRStatus::RKR_STATUS_VALIDATION_ERROR),
3129    };
3130    finish_dlpack_tensor(tensor, out_tensor)
3131}
3132
3133fn export_owned_array2_dlpack_opts(
3134    arr: &ndarray::ArcArray2<f64>,
3135    opts: &RKRDlpackExportOptions,
3136    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3137) -> RKRStatus {
3138    let (r, c) = arr.dim();
3139    let flat: Vec<f64> = arr.iter().copied().collect();
3140    if opts.device.device_type == rkr_dl_device_type::RKR_DL_CUDA {
3141        #[cfg(feature = "cuda")]
3142        {
3143            // H2D into real device memory (f64 only for CUDA path here).
3144            if opts.dtype.code != rkr_dl_type_code::RKR_DL_FLOAT || opts.dtype.bits != 64 {
3145                return note(RKRStatus::RKR_STATUS_VALIDATION_ERROR);
3146            }
3147            return finish_dlpack_tensor(
3148                crate::cuda_array::export_host_f64_as_cuda_dlpack(
3149                    &[r, c],
3150                    &flat,
3151                    opts.device.device_id,
3152                ),
3153                out_tensor,
3154            );
3155        }
3156        #[cfg(not(feature = "cuda"))]
3157        {
3158            return note(RKRStatus::RKR_STATUS_FEATURE_DISABLED);
3159        }
3160    }
3161    export_f64_slice_as_dlpack(&flat, &[r, c], opts.dtype, out_tensor)
3162}
3163
3164fn export_owned_array1_f64_dlpack_opts(
3165    arr: &ndarray::ArcArray1<f64>,
3166    opts: &RKRDlpackExportOptions,
3167    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3168) -> RKRStatus {
3169    let flat = arr.to_vec();
3170    let n = flat.len();
3171    if opts.device.device_type == rkr_dl_device_type::RKR_DL_CUDA {
3172        #[cfg(feature = "cuda")]
3173        {
3174            if opts.dtype.code != rkr_dl_type_code::RKR_DL_FLOAT || opts.dtype.bits != 64 {
3175                return note(RKRStatus::RKR_STATUS_VALIDATION_ERROR);
3176            }
3177            return finish_dlpack_tensor(
3178                crate::cuda_array::export_host_f64_as_cuda_dlpack(
3179                    &[n],
3180                    &flat,
3181                    opts.device.device_id,
3182                ),
3183                out_tensor,
3184            );
3185        }
3186        #[cfg(not(feature = "cuda"))]
3187        {
3188            return note(RKRStatus::RKR_STATUS_FEATURE_DISABLED);
3189        }
3190    }
3191    export_f64_slice_as_dlpack(&flat, &[n], opts.dtype, out_tensor)
3192}
3193
3194fn export_owned_array1_u64_dlpack(
3195    arr: &ndarray::ArcArray1<u64>,
3196    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3197) -> RKRStatus {
3198    finish_dlpack_tensor(dlpk::DLPackTensor::try_from(arr.clone()), out_tensor)
3199}
3200
3201/// Atom ids: default uint64; or cast via f64 path when `opts.dtype` requests another host type.
3202fn export_owned_array1_u64_dlpack_opts(
3203    arr: &ndarray::ArcArray1<u64>,
3204    opts: &RKRDlpackExportOptions,
3205    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3206) -> RKRStatus {
3207    use rkr_dl_type_code::*;
3208    if opts.dtype.code == RKR_DL_UINT && opts.dtype.bits == 64 && opts.dtype.lanes == 1 {
3209        return export_owned_array1_u64_dlpack(arr, out_tensor);
3210    }
3211    let as_f64: Vec<f64> = arr.iter().map(|&x| x as f64).collect();
3212    let n = as_f64.len();
3213    export_f64_slice_as_dlpack(&as_f64, &[n], opts.dtype, out_tensor)
3214}
3215/// Export builder positions as a DLPack-managed tensor.
3216///
3217/// On success the caller-supplied `*out_tensor` is set to a newly-
3218/// allocated `DLManagedTensorVersioned*` that owns a clone of the
3219/// builder's `(N, 3) f64` row-major positions buffer. The caller MUST
3220/// invoke `(*out_tensor)->deleter(*out_tensor)` to release it.
3221///
3222/// # Safety
3223/// `builder_handle` must be a valid builder handle; `out_tensor` must
3224/// be a valid pointer to a writable `*mut DLManagedTensorVersioned`.
3225#[unsafe(no_mangle)]
3226pub unsafe extern "C" fn rkr_frame_builder_positions_dlpack(
3227    builder_handle: *const RKRConFrameBuilder,
3228    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3229) -> RKRStatus {
3230    unsafe { rkr_frame_builder_positions_dlpack_ex(builder_handle, std::ptr::null(), out_tensor) }
3231}
3232
3233/// Like [`rkr_frame_builder_positions_dlpack`] with explicit precision/device.
3234///
3235/// `opts` may be NULL (float64 / CPU). See [`RKRDlpackExportOptions`].
3236///
3237/// # Safety
3238/// Same as the non-`_ex` entry; `opts` must be null or point at a valid struct.
3239#[unsafe(no_mangle)]
3240pub unsafe extern "C" fn rkr_frame_builder_positions_dlpack_ex(
3241    builder_handle: *const RKRConFrameBuilder,
3242    opts: *const RKRDlpackExportOptions,
3243    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3244) -> RKRStatus {
3245    if builder_handle.is_null() || out_tensor.is_null() {
3246        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
3247    }
3248    let o = match resolve_dlpack_opts(opts) {
3249        Ok(o) => o,
3250        Err(st) => return st,
3251    };
3252    let builder = unsafe { &*(builder_handle as *const ConFrameBuilder) };
3253    export_owned_array2_dlpack_opts(builder.positions_2d_ref(), &o, out_tensor)
3254}
3255
3256/// Export builder velocities as a DLPack-managed tensor.
3257///
3258/// Returns `RKR_STATUS_SECTION_ABSENT` if the velocities section is not
3259/// declared; otherwise `(N, 3) f64`. See positions_dlpack for ownership
3260/// semantics.
3261///
3262/// # Safety
3263/// `builder_handle` must be a valid builder handle; `out_tensor` must
3264/// be a valid pointer to a writable `*mut DLManagedTensorVersioned`.
3265#[unsafe(no_mangle)]
3266pub unsafe extern "C" fn rkr_frame_builder_velocities_dlpack(
3267    builder_handle: *const RKRConFrameBuilder,
3268    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3269) -> RKRStatus {
3270    unsafe { rkr_frame_builder_velocities_dlpack_ex(builder_handle, std::ptr::null(), out_tensor) }
3271}
3272
3273/// # Safety
3274///
3275/// A non-null pointer argument must point at a live value of its declared
3276/// type for this call. A null pointer is handled inside the function.
3277#[unsafe(no_mangle)]
3278pub unsafe extern "C" fn rkr_frame_builder_velocities_dlpack_ex(
3279    builder_handle: *const RKRConFrameBuilder,
3280    opts: *const RKRDlpackExportOptions,
3281    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3282) -> RKRStatus {
3283    if builder_handle.is_null() || out_tensor.is_null() {
3284        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
3285    }
3286    let o = match resolve_dlpack_opts(opts) {
3287        Ok(o) => o,
3288        Err(st) => return st,
3289    };
3290    let builder = unsafe { &*(builder_handle as *const ConFrameBuilder) };
3291    if !builder.has_velocities_section() {
3292        return note(RKRStatus::RKR_STATUS_SECTION_ABSENT);
3293    }
3294    export_owned_array2_dlpack_opts(builder.velocities_2d_ref(), &o, out_tensor)
3295}
3296
3297/// Export builder forces as a DLPack-managed tensor.
3298///
3299/// Returns `RKR_STATUS_SECTION_ABSENT` if the forces section is not
3300/// declared.
3301///
3302/// # Safety
3303/// `builder_handle` must be a valid builder handle; `out_tensor` must
3304/// be a valid pointer to a writable `*mut DLManagedTensorVersioned`.
3305#[unsafe(no_mangle)]
3306pub unsafe extern "C" fn rkr_frame_builder_forces_dlpack(
3307    builder_handle: *const RKRConFrameBuilder,
3308    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3309) -> RKRStatus {
3310    unsafe { rkr_frame_builder_forces_dlpack_ex(builder_handle, std::ptr::null(), out_tensor) }
3311}
3312
3313/// # Safety
3314///
3315/// A non-null pointer argument must point at a live value of its declared
3316/// type for this call. A null pointer is handled inside the function.
3317#[unsafe(no_mangle)]
3318pub unsafe extern "C" fn rkr_frame_builder_forces_dlpack_ex(
3319    builder_handle: *const RKRConFrameBuilder,
3320    opts: *const RKRDlpackExportOptions,
3321    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3322) -> RKRStatus {
3323    if builder_handle.is_null() || out_tensor.is_null() {
3324        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
3325    }
3326    let o = match resolve_dlpack_opts(opts) {
3327        Ok(o) => o,
3328        Err(st) => return st,
3329    };
3330    let builder = unsafe { &*(builder_handle as *const ConFrameBuilder) };
3331    if !builder.has_forces_section() {
3332        return note(RKRStatus::RKR_STATUS_SECTION_ABSENT);
3333    }
3334    export_owned_array2_dlpack_opts(builder.forces_2d_ref(), &o, out_tensor)
3335}
3336
3337/// Export builder displacements as a DLPack-managed tensor.
3338///
3339/// Returns `RKR_STATUS_SECTION_ABSENT` if the displacements section is not
3340/// declared.
3341///
3342/// # Safety
3343/// `builder_handle` must be a valid builder handle; `out_tensor` must
3344/// be a valid pointer to a writable `*mut DLManagedTensorVersioned`.
3345#[unsafe(no_mangle)]
3346pub unsafe extern "C" fn rkr_frame_builder_displacements_dlpack(
3347    builder_handle: *const RKRConFrameBuilder,
3348    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3349) -> RKRStatus {
3350    unsafe {
3351        rkr_frame_builder_displacements_dlpack_ex(builder_handle, std::ptr::null(), out_tensor)
3352    }
3353}
3354
3355/// Like [`rkr_frame_builder_displacements_dlpack`] with export options
3356/// (NULL `opts` selects float64 on CPU).
3357///
3358/// # Safety
3359/// Same contract as [`rkr_frame_builder_displacements_dlpack`]; `opts` is
3360/// NULL or points to a valid `RKRDlpackExportOptions`.
3361#[unsafe(no_mangle)]
3362pub unsafe extern "C" fn rkr_frame_builder_displacements_dlpack_ex(
3363    builder_handle: *const RKRConFrameBuilder,
3364    opts: *const RKRDlpackExportOptions,
3365    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3366) -> RKRStatus {
3367    if builder_handle.is_null() || out_tensor.is_null() {
3368        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
3369    }
3370    let o = match resolve_dlpack_opts(opts) {
3371        Ok(o) => o,
3372        Err(st) => return st,
3373    };
3374    let builder = unsafe { &*(builder_handle as *const ConFrameBuilder) };
3375    if !builder.has_displacements_section() {
3376        return note(RKRStatus::RKR_STATUS_SECTION_ABSENT);
3377    }
3378    export_owned_array2_dlpack_opts(builder.displacements_2d_ref(), &o, out_tensor)
3379}
3380
3381/// Export builder spreads as a DLPack-managed tensor.
3382///
3383/// Returns `RKR_STATUS_SECTION_ABSENT` if the spreads section is not
3384/// declared.
3385///
3386/// # Safety
3387/// `builder_handle` must be a valid builder handle; `out_tensor` must
3388/// be a valid pointer to a writable `*mut DLManagedTensorVersioned`.
3389#[unsafe(no_mangle)]
3390pub unsafe extern "C" fn rkr_frame_builder_spreads_dlpack(
3391    builder_handle: *const RKRConFrameBuilder,
3392    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3393) -> RKRStatus {
3394    unsafe { rkr_frame_builder_spreads_dlpack_ex(builder_handle, std::ptr::null(), out_tensor) }
3395}
3396
3397/// Like [`rkr_frame_builder_spreads_dlpack`] with export options
3398/// (NULL `opts` selects float64 on CPU).
3399///
3400/// # Safety
3401/// Same contract as [`rkr_frame_builder_spreads_dlpack`]; `opts` is
3402/// NULL or points to a valid `RKRDlpackExportOptions`.
3403#[unsafe(no_mangle)]
3404pub unsafe extern "C" fn rkr_frame_builder_spreads_dlpack_ex(
3405    builder_handle: *const RKRConFrameBuilder,
3406    opts: *const RKRDlpackExportOptions,
3407    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3408) -> RKRStatus {
3409    if builder_handle.is_null() || out_tensor.is_null() {
3410        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
3411    }
3412    let o = match resolve_dlpack_opts(opts) {
3413        Ok(o) => o,
3414        Err(st) => return st,
3415    };
3416    let builder = unsafe { &*(builder_handle as *const ConFrameBuilder) };
3417    if !builder.has_spreads_section() {
3418        return note(RKRStatus::RKR_STATUS_SECTION_ABSENT);
3419    }
3420    export_owned_array2_dlpack_opts(builder.spreads_2d_ref(), &o, out_tensor)
3421}
3422
3423/// Export builder per-atom energies as a DLPack-managed tensor.
3424///
3425/// Returns `RKR_STATUS_SECTION_ABSENT` if the energies section is not
3426/// declared; otherwise `(N,) f64`.
3427///
3428/// # Safety
3429/// `builder_handle` must be a valid builder handle; `out_tensor` must
3430/// be a valid pointer to a writable `*mut DLManagedTensorVersioned`.
3431#[unsafe(no_mangle)]
3432pub unsafe extern "C" fn rkr_frame_builder_atom_energies_dlpack(
3433    builder_handle: *const RKRConFrameBuilder,
3434    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3435) -> RKRStatus {
3436    unsafe {
3437        rkr_frame_builder_atom_energies_dlpack_ex(builder_handle, std::ptr::null(), out_tensor)
3438    }
3439}
3440
3441/// # Safety
3442///
3443/// A non-null pointer argument must point at a live value of its declared
3444/// type for this call. A null pointer is handled inside the function.
3445#[unsafe(no_mangle)]
3446pub unsafe extern "C" fn rkr_frame_builder_atom_energies_dlpack_ex(
3447    builder_handle: *const RKRConFrameBuilder,
3448    opts: *const RKRDlpackExportOptions,
3449    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3450) -> RKRStatus {
3451    if builder_handle.is_null() || out_tensor.is_null() {
3452        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
3453    }
3454    let o = match resolve_dlpack_opts(opts) {
3455        Ok(o) => o,
3456        Err(st) => return st,
3457    };
3458    let builder = unsafe { &*(builder_handle as *const ConFrameBuilder) };
3459    if !builder.has_energies_section() {
3460        return note(RKRStatus::RKR_STATUS_SECTION_ABSENT);
3461    }
3462    export_owned_array1_f64_dlpack_opts(builder.atom_energies_1d_ref(), &o, out_tensor)
3463}
3464
3465/// Export builder per-atom masses as a DLPack-managed tensor `(N,) f64`.
3466///
3467/// # Safety
3468/// `builder_handle` must be a valid builder handle; `out_tensor` must
3469/// be a valid pointer to a writable `*mut DLManagedTensorVersioned`.
3470#[unsafe(no_mangle)]
3471pub unsafe extern "C" fn rkr_frame_builder_masses_dlpack(
3472    builder_handle: *const RKRConFrameBuilder,
3473    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3474) -> RKRStatus {
3475    unsafe { rkr_frame_builder_masses_dlpack_ex(builder_handle, std::ptr::null(), out_tensor) }
3476}
3477
3478/// # Safety
3479///
3480/// A non-null pointer argument must point at a live value of its declared
3481/// type for this call. A null pointer is handled inside the function.
3482#[unsafe(no_mangle)]
3483pub unsafe extern "C" fn rkr_frame_builder_masses_dlpack_ex(
3484    builder_handle: *const RKRConFrameBuilder,
3485    opts: *const RKRDlpackExportOptions,
3486    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3487) -> RKRStatus {
3488    if builder_handle.is_null() || out_tensor.is_null() {
3489        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
3490    }
3491    let o = match resolve_dlpack_opts(opts) {
3492        Ok(o) => o,
3493        Err(st) => return st,
3494    };
3495    let builder = unsafe { &*(builder_handle as *const ConFrameBuilder) };
3496    export_owned_array1_f64_dlpack_opts(builder.masses_1d_ref(), &o, out_tensor)
3497}
3498/// Export builder per-atom ids as a DLPack-managed tensor `(N,) u64`.
3499///
3500/// # Safety
3501/// `builder_handle` must be a valid builder handle; `out_tensor` must
3502/// be a valid pointer to a writable `*mut DLManagedTensorVersioned`.
3503#[unsafe(no_mangle)]
3504pub unsafe extern "C" fn rkr_frame_builder_atom_ids_dlpack(
3505    builder_handle: *const RKRConFrameBuilder,
3506    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3507) -> RKRStatus {
3508    unsafe { rkr_frame_builder_atom_ids_dlpack_ex(builder_handle, std::ptr::null(), out_tensor) }
3509}
3510
3511/// # Safety
3512///
3513/// A non-null pointer argument must point at a live value of its declared
3514/// type for this call. A null pointer is handled inside the function.
3515#[unsafe(no_mangle)]
3516pub unsafe extern "C" fn rkr_frame_builder_atom_ids_dlpack_ex(
3517    builder_handle: *const RKRConFrameBuilder,
3518    opts: *const RKRDlpackExportOptions,
3519    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
3520) -> RKRStatus {
3521    if builder_handle.is_null() || out_tensor.is_null() {
3522        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
3523    }
3524    let o = match resolve_dlpack_opts(opts) {
3525        Ok(o) => o,
3526        Err(st) => return st,
3527    };
3528    let builder = unsafe { &*(builder_handle as *const ConFrameBuilder) };
3529    export_owned_array1_u64_dlpack_opts(builder.atom_ids_1d_ref(), &o, out_tensor)
3530}
3531// ----- v0.11.1 in-process zero-copy raw-pointer FFI -------------------------
3532//
3533// The DLPack tier-3 export above clones field data into an owning tensor so
3534// the consumer can outlive the builder; this is the right contract for
3535// language-runtime / cross-process consumers (Python GC, Julia GC,
3536// inter-process exchange). For *in-process* zero-copy on the hot path
3537// (LAMMPS-style `lmp->atom->x` direct pointer access used by integrators,
3538// dynamics drivers, eOn's Matter Eigen::Map<RowMajor> views), we expose
3539// raw pointers into the builder's storage. The lifetime contract is
3540// purely caller-managed: the pointer is valid while the builder is alive
3541// and no add_atom call has grown the underlying ndarray. This mirrors
3542// the LAMMPS / OpenMM / GROMACS C-side hot path and is what makes a
3543// thin Matter wrapper over ConFrameBuilder fast.
3544//
3545// Cross-language ML consumers should use the DLPack tier above; raw
3546// pointer access is for in-process hot paths only.
3547/// Borrow the positions buffer as a raw `(N, 3) f64` row-major pointer.
3548/// Returns NULL on invalid handle. Pointer is valid until the builder
3549/// is dropped or `add_atom` reallocates.
3550///
3551/// # Safety
3552/// builder_handle must be valid; the returned pointer must not be
3553/// dereferenced after a call to add_atom on the same builder.
3554#[unsafe(no_mangle)]
3555pub unsafe extern "C" fn rkr_frame_builder_positions_data(
3556    builder_handle: *mut RKRConFrameBuilder,
3557) -> *mut f64 {
3558    if builder_handle.is_null() {
3559        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
3560    }
3561    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
3562    builder
3563        .positions_view_mut()
3564        .as_slice_memory_order_mut()
3565        .map(|s| s.as_mut_ptr())
3566        .unwrap_or(std::ptr::null_mut())
3567}
3568/// Borrow the velocities buffer as a raw `(N, 3) f64` row-major pointer.
3569/// Returns NULL if the velocities section is absent or the handle is
3570/// invalid.
3571///
3572/// # Safety
3573/// Same contract as rkr_frame_builder_positions_data.
3574#[unsafe(no_mangle)]
3575pub unsafe extern "C" fn rkr_frame_builder_velocities_data(
3576    builder_handle: *mut RKRConFrameBuilder,
3577) -> *mut f64 {
3578    if builder_handle.is_null() {
3579        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
3580    }
3581    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
3582    if !builder.has_velocities_section() {
3583        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
3584    }
3585    let slice = builder.velocities_mut();
3586    if slice.is_empty() {
3587        std::ptr::null_mut()
3588    } else {
3589        slice.as_mut_ptr()
3590    }
3591}
3592/// Borrow the forces buffer as a raw `(N, 3) f64` row-major pointer.
3593/// Returns NULL if the forces section is absent.
3594///
3595/// # Safety
3596/// Same contract as rkr_frame_builder_positions_data.
3597#[unsafe(no_mangle)]
3598pub unsafe extern "C" fn rkr_frame_builder_forces_data(
3599    builder_handle: *mut RKRConFrameBuilder,
3600) -> *mut f64 {
3601    if builder_handle.is_null() {
3602        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
3603    }
3604    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
3605    if !builder.has_forces_section() {
3606        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
3607    }
3608    let slice = builder.forces_mut();
3609    if slice.is_empty() {
3610        std::ptr::null_mut()
3611    } else {
3612        slice.as_mut_ptr()
3613    }
3614}
3615/// Borrow the displacements buffer as a raw `(N, 3) f64` row-major pointer.
3616/// Returns NULL if the displacements section is absent.
3617///
3618/// # Safety
3619/// Same contract as rkr_frame_builder_positions_data.
3620#[unsafe(no_mangle)]
3621pub unsafe extern "C" fn rkr_frame_builder_displacements_data(
3622    builder_handle: *mut RKRConFrameBuilder,
3623) -> *mut f64 {
3624    if builder_handle.is_null() {
3625        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
3626    }
3627    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
3628    if !builder.has_displacements_section() {
3629        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
3630    }
3631    let slice = builder.displacements_mut();
3632    if slice.is_empty() {
3633        std::ptr::null_mut()
3634    } else {
3635        slice.as_mut_ptr()
3636    }
3637}
3638/// Borrow the spreads buffer as a raw `(N, 3) f64` row-major pointer.
3639/// Returns NULL if the spreads section is absent.
3640///
3641/// # Safety
3642/// Same contract as rkr_frame_builder_positions_data.
3643#[unsafe(no_mangle)]
3644pub unsafe extern "C" fn rkr_frame_builder_spreads_data(
3645    builder_handle: *mut RKRConFrameBuilder,
3646) -> *mut f64 {
3647    if builder_handle.is_null() {
3648        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
3649    }
3650    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
3651    if !builder.has_spreads_section() {
3652        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
3653    }
3654    let slice = builder.spreads_mut();
3655    if slice.is_empty() {
3656        std::ptr::null_mut()
3657    } else {
3658        slice.as_mut_ptr()
3659    }
3660}
3661/// Borrow the per-atom energies buffer as a raw `(N,) f64` pointer.
3662/// Returns NULL if the energies section is absent.
3663///
3664/// # Safety
3665/// Same contract as rkr_frame_builder_positions_data.
3666#[unsafe(no_mangle)]
3667pub unsafe extern "C" fn rkr_frame_builder_atom_energies_data(
3668    builder_handle: *mut RKRConFrameBuilder,
3669) -> *mut f64 {
3670    if builder_handle.is_null() {
3671        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
3672    }
3673    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
3674    if !builder.has_energies_section() {
3675        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
3676    }
3677    let slice = builder.atom_energies_mut();
3678    if slice.is_empty() {
3679        std::ptr::null_mut()
3680    } else {
3681        slice.as_mut_ptr()
3682    }
3683}
3684/// Borrow the per-atom masses buffer as a raw `(N,) f64` pointer.
3685///
3686/// # Safety
3687/// Same contract as rkr_frame_builder_positions_data.
3688#[unsafe(no_mangle)]
3689pub unsafe extern "C" fn rkr_frame_builder_masses_data(
3690    builder_handle: *mut RKRConFrameBuilder,
3691) -> *mut f64 {
3692    if builder_handle.is_null() {
3693        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
3694    }
3695    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
3696    let slice = builder.masses_mut();
3697    if slice.is_empty() {
3698        std::ptr::null_mut()
3699    } else {
3700        slice.as_mut_ptr()
3701    }
3702}
3703/// Borrow the per-atom atom_ids buffer as a raw `(N,) u64` pointer.
3704///
3705/// # Safety
3706/// Same contract as rkr_frame_builder_positions_data.
3707#[unsafe(no_mangle)]
3708pub unsafe extern "C" fn rkr_frame_builder_atom_ids_data(
3709    builder_handle: *const RKRConFrameBuilder,
3710) -> *const u64 {
3711    if builder_handle.is_null() {
3712        return std::ptr::null();
3713    }
3714    let builder = unsafe { &*(builder_handle as *const ConFrameBuilder) };
3715    let slice = builder.atom_ids();
3716    if slice.is_empty() {
3717        std::ptr::null()
3718    } else {
3719        slice.as_ptr()
3720    }
3721}
3722// ----- end v0.11.0 in-place mutation FFI ------------------------------------
3723/// Adds an atom with optional per-axis fixed mask, velocity, and force vectors.
3724///
3725/// `velocity` and `force` are pointers to 3 contiguous f64 values, or NULL if
3726/// absent. This is the unified entry point that replaces the eight
3727/// `rkr_frame_add_atom_*` convenience functions; callers may continue using
3728/// those for source compatibility.
3729///
3730/// # Safety
3731/// builder_handle and symbol must be valid. velocity (if non-null) must point
3732/// to 3 contiguous f64 values, and force (if non-null) likewise.
3733#[unsafe(no_mangle)]
3734#[allow(clippy::too_many_arguments)]
3735pub unsafe extern "C" fn rkr_frame_add_atom_full(
3736    builder_handle: *mut RKRConFrameBuilder,
3737    symbol: *const c_char,
3738    x: f64,
3739    y: f64,
3740    z: f64,
3741    fixed_x: bool,
3742    fixed_y: bool,
3743    fixed_z: bool,
3744    atom_id: u64,
3745    mass: f64,
3746    velocity: *const f64,
3747    force: *const f64,
3748) -> RKRStatus {
3749    let velocity = if velocity.is_null() {
3750        None
3751    } else {
3752        Some(unsafe { [*velocity, *velocity.add(1), *velocity.add(2)] })
3753    };
3754    let force = if force.is_null() {
3755        None
3756    } else {
3757        Some(unsafe { [*force, *force.add(1), *force.add(2)] })
3758    };
3759    unsafe {
3760        add_builder_atom(
3761            builder_handle,
3762            symbol,
3763            x,
3764            y,
3765            z,
3766            [fixed_x, fixed_y, fixed_z],
3767            atom_id,
3768            mass,
3769            velocity,
3770            force,
3771        )
3772    }
3773}
3774/// Creates a new frame builder with the given cell dimensions, angles,
3775/// and header lines.
3776///
3777/// `prebox1` is accepted for source compatibility but ignored: the
3778/// JSON metadata line is regenerated by the writer from the builder's
3779/// `spec_version`, `metadata`, and `sections`. Pass NULL or any string.
3780/// The caller OWNS the returned pointer and MUST call
3781/// `free_rkr_frame_builder` or consume it via `rkr_frame_builder_build`.
3782/// Returns NULL on error.
3783///
3784/// # Safety
3785/// cell and angles must point to 3 doubles. prebox0, postbox0, and
3786/// postbox1 must be NULL or valid null-terminated strings; prebox1 is
3787/// not dereferenced. The caller takes ownership of the returned
3788/// builder.
3789#[unsafe(no_mangle)]
3790pub unsafe extern "C" fn rkr_frame_new(
3791    cell: *const f64,
3792    angles: *const f64,
3793    prebox0: *const c_char,
3794    prebox1: *const c_char,
3795    postbox0: *const c_char,
3796    postbox1: *const c_char,
3797) -> *mut RKRConFrameBuilder {
3798    if cell.is_null() || angles.is_null() {
3799        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
3800    }
3801    let cell_arr = unsafe { [*cell, *cell.add(1), *cell.add(2)] };
3802    let angles_arr = unsafe { [*angles, *angles.add(1), *angles.add(2)] };
3803    let get_str = |p: *const c_char| -> String {
3804        if p.is_null() {
3805            String::new()
3806        } else {
3807            unsafe { CStr::from_ptr(p) }
3808                .to_str()
3809                .unwrap_or("")
3810                .to_string()
3811        }
3812    };
3813    // prebox1 is the JSON metadata slot, regenerated on write from
3814    // metadata + sections; it is accepted for ABI continuity but ignored.
3815    let _ = get_str(prebox1);
3816    let mut builder = ConFrameBuilder::new(cell_arr, angles_arr);
3817    builder
3818        .prebox_header(get_str(prebox0))
3819        .postbox_header([get_str(postbox0), get_str(postbox1)]);
3820    Box::into_raw(Box::new(builder)) as *mut RKRConFrameBuilder
3821}
3822/// Parses and sets JSON metadata on an existing frame builder.
3823/// Returns `RKR_STATUS_SUCCESS` on success, or an error code.
3824///
3825/// # Safety
3826/// builder_handle and metadata_json must be valid.
3827#[unsafe(no_mangle)]
3828pub unsafe extern "C" fn rkr_frame_builder_set_metadata_json(
3829    builder_handle: *mut RKRConFrameBuilder,
3830    metadata_json: *const c_char,
3831) -> RKRStatus {
3832    if builder_handle.is_null() || metadata_json.is_null() {
3833        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
3834    }
3835    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
3836    let metadata_json = match unsafe { CStr::from_ptr(metadata_json).to_str() } {
3837        Ok(s) => s,
3838        Err(_) => return note(RKRStatus::RKR_STATUS_INVALID_UTF8),
3839    };
3840    match builder.set_metadata_json(metadata_json) {
3841        Ok(()) => note(RKRStatus::RKR_STATUS_SUCCESS),
3842        Err(_) => note(RKRStatus::RKR_STATUS_INVALID_JSON),
3843    }
3844}
3845/// Sets the units object on an existing frame builder.
3846/// `units_json` is a JSON object, for example
3847/// `{"length":"angstrom","energy":"eV","mass":"amu","time":"(amu*angstrom^2/eV)^0.5"}`.
3848/// Returns `RKR_STATUS_SUCCESS` on success, `RKR_STATUS_INVALID_JSON` when
3849/// the text is not a JSON object, or `RKR_STATUS_VALIDATION_ERROR` when a
3850/// unit expression is not valid.
3851///
3852/// # Safety
3853/// builder_handle and units_json must be valid.
3854#[unsafe(no_mangle)]
3855pub unsafe extern "C" fn rkr_frame_builder_set_units(
3856    builder_handle: *mut RKRConFrameBuilder,
3857    units_json: *const c_char,
3858) -> RKRStatus {
3859    if builder_handle.is_null() || units_json.is_null() {
3860        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
3861    }
3862    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
3863    let units_json = match unsafe { CStr::from_ptr(units_json).to_str() } {
3864        Ok(s) => s,
3865        Err(_) => return note(RKRStatus::RKR_STATUS_INVALID_UTF8),
3866    };
3867    let units: serde_json::Value = match serde_json::from_str(units_json) {
3868        Ok(value) => value,
3869        Err(_) => return note(RKRStatus::RKR_STATUS_INVALID_JSON),
3870    };
3871    match builder.set_units(units) {
3872        Ok(()) => note(RKRStatus::RKR_STATUS_SUCCESS),
3873        Err(_) => note(RKRStatus::RKR_STATUS_VALIDATION_ERROR),
3874    }
3875}
3876/// Sets `con_spec_minor` on an existing frame builder.
3877/// A v3 frame built without this call carries minor 1.
3878/// Returns `RKR_STATUS_SUCCESS` on success.
3879///
3880/// # Safety
3881/// builder_handle must be valid.
3882#[unsafe(no_mangle)]
3883pub unsafe extern "C" fn rkr_frame_builder_set_con_spec_minor(
3884    builder_handle: *mut RKRConFrameBuilder,
3885    minor: u32,
3886) -> RKRStatus {
3887    if builder_handle.is_null() {
3888        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
3889    }
3890    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
3891    builder.set_con_spec_minor(minor);
3892    note(RKRStatus::RKR_STATUS_SUCCESS)
3893}
3894/// Sets a numeric metadata key on an existing frame builder.
3895/// Returns `RKR_STATUS_SUCCESS` on success, or an error code.
3896///
3897/// # Safety
3898/// builder_handle and key must be valid.
3899#[unsafe(no_mangle)]
3900pub unsafe extern "C" fn rkr_frame_builder_set_scalar_metadata(
3901    builder_handle: *mut RKRConFrameBuilder,
3902    key: *const c_char,
3903    value: f64,
3904) -> RKRStatus {
3905    if builder_handle.is_null() || key.is_null() {
3906        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
3907    }
3908    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
3909    let key = match unsafe { CStr::from_ptr(key).to_str() } {
3910        Ok(s) => s,
3911        Err(_) => return note(RKRStatus::RKR_STATUS_INVALID_UTF8),
3912    };
3913    builder.set_scalar_metadata(key, value);
3914    note(RKRStatus::RKR_STATUS_SUCCESS)
3915}
3916/// Sets a string metadata key on an existing frame builder.
3917/// Returns `RKR_STATUS_SUCCESS` on success, or an error code.
3918///
3919/// # Safety
3920/// builder_handle, key, and value must be valid.
3921#[unsafe(no_mangle)]
3922pub unsafe extern "C" fn rkr_frame_builder_set_string_metadata(
3923    builder_handle: *mut RKRConFrameBuilder,
3924    key: *const c_char,
3925    value: *const c_char,
3926) -> RKRStatus {
3927    if builder_handle.is_null() || key.is_null() || value.is_null() {
3928        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
3929    }
3930    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
3931    let key = match unsafe { CStr::from_ptr(key).to_str() } {
3932        Ok(s) => s,
3933        Err(_) => return note(RKRStatus::RKR_STATUS_INVALID_UTF8),
3934    };
3935    let value = match unsafe { CStr::from_ptr(value).to_str() } {
3936        Ok(s) => s,
3937        Err(_) => return note(RKRStatus::RKR_STATUS_INVALID_UTF8),
3938    };
3939    builder.set_string_metadata(key, value);
3940    note(RKRStatus::RKR_STATUS_SUCCESS)
3941}
3942/// Sets the per-frame total energy metadata on an existing frame builder.
3943/// Returns `RKR_STATUS_SUCCESS` on success, or an error code.
3944///
3945/// # Safety
3946/// builder_handle must be valid.
3947#[unsafe(no_mangle)]
3948pub unsafe extern "C" fn rkr_frame_builder_set_energy(
3949    builder_handle: *mut RKRConFrameBuilder,
3950    energy: f64,
3951) -> RKRStatus {
3952    if builder_handle.is_null() {
3953        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
3954    }
3955    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
3956    builder.set_energy(energy);
3957    note(RKRStatus::RKR_STATUS_SUCCESS)
3958}
3959/// Sets the zero-based frame index metadata on an existing frame builder.
3960/// Returns `RKR_STATUS_SUCCESS` on success, or an error code.
3961///
3962/// # Safety
3963/// builder_handle must be valid.
3964#[unsafe(no_mangle)]
3965pub unsafe extern "C" fn rkr_frame_builder_set_frame_index(
3966    builder_handle: *mut RKRConFrameBuilder,
3967    idx: u64,
3968) -> RKRStatus {
3969    if builder_handle.is_null() {
3970        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
3971    }
3972    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
3973    builder.set_frame_index(idx);
3974    note(RKRStatus::RKR_STATUS_SUCCESS)
3975}
3976/// Sets the simulation time metadata on an existing frame builder.
3977/// Returns `RKR_STATUS_SUCCESS` on success, or an error code.
3978///
3979/// # Safety
3980/// builder_handle must be valid.
3981#[unsafe(no_mangle)]
3982pub unsafe extern "C" fn rkr_frame_builder_set_time(
3983    builder_handle: *mut RKRConFrameBuilder,
3984    time: f64,
3985) -> RKRStatus {
3986    if builder_handle.is_null() {
3987        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
3988    }
3989    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
3990    builder.set_time(time);
3991    note(RKRStatus::RKR_STATUS_SUCCESS)
3992}
3993/// Sets the timestep metadata on an existing frame builder.
3994/// Returns `RKR_STATUS_SUCCESS` on success, or an error code.
3995///
3996/// # Safety
3997/// builder_handle must be valid.
3998#[unsafe(no_mangle)]
3999pub unsafe extern "C" fn rkr_frame_builder_set_timestep(
4000    builder_handle: *mut RKRConFrameBuilder,
4001    dt: f64,
4002) -> RKRStatus {
4003    if builder_handle.is_null() {
4004        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
4005    }
4006    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
4007    builder.set_timestep(dt);
4008    note(RKRStatus::RKR_STATUS_SUCCESS)
4009}
4010/// Sets the NEB bead index metadata on an existing frame builder.
4011/// Returns `RKR_STATUS_SUCCESS` on success, or an error code.
4012///
4013/// # Safety
4014/// builder_handle must be valid.
4015#[unsafe(no_mangle)]
4016pub unsafe extern "C" fn rkr_frame_builder_set_neb_bead(
4017    builder_handle: *mut RKRConFrameBuilder,
4018    bead: u64,
4019) -> RKRStatus {
4020    if builder_handle.is_null() {
4021        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
4022    }
4023    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
4024    builder.set_neb_bead(bead);
4025    note(RKRStatus::RKR_STATUS_SUCCESS)
4026}
4027/// Sets the NEB band index metadata on an existing frame builder.
4028/// Returns `RKR_STATUS_SUCCESS` on success, or an error code.
4029///
4030/// # Safety
4031/// builder_handle must be valid.
4032#[unsafe(no_mangle)]
4033pub unsafe extern "C" fn rkr_frame_builder_set_neb_band(
4034    builder_handle: *mut RKRConFrameBuilder,
4035    band: u64,
4036) -> RKRStatus {
4037    if builder_handle.is_null() {
4038        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
4039    }
4040    let builder = unsafe { &mut *(builder_handle as *mut ConFrameBuilder) };
4041    builder.set_neb_band(band);
4042    note(RKRStatus::RKR_STATUS_SUCCESS)
4043}
4044// -----------------------------------------------------------------------------
4045// Legacy add_atom variants (kept for source compatibility)
4046//
4047// The unified entry point is `rkr_frame_add_atom_full`, which accepts
4048// optional velocity and force pointers. The eight functions below
4049// pre-date the unified call and remain in the API for code that was
4050// written against earlier 0.x releases. New callers should prefer
4051// `rkr_frame_add_atom_full`.
4052// -----------------------------------------------------------------------------
4053/// **Deprecated**: prefer `rkr_frame_add_atom_full` with NULL velocity
4054/// and force pointers. Adds an atom (no velocity, no forces) to the
4055/// builder using a single uniform fixed flag.
4056/// Returns `RKR_STATUS_SUCCESS` on success, or an error code.
4057///
4058/// # Safety
4059/// builder_handle and symbol must be valid.
4060#[unsafe(no_mangle)]
4061pub unsafe extern "C" fn rkr_frame_add_atom(
4062    builder_handle: *mut RKRConFrameBuilder,
4063    symbol: *const c_char,
4064    x: f64,
4065    y: f64,
4066    z: f64,
4067    is_fixed: bool,
4068    atom_id: u64,
4069    mass: f64,
4070) -> RKRStatus {
4071    unsafe {
4072        add_builder_atom(
4073            builder_handle,
4074            symbol,
4075            x,
4076            y,
4077            z,
4078            [is_fixed; 3],
4079            atom_id,
4080            mass,
4081            None,
4082            None,
4083        )
4084    }
4085}
4086/// **Deprecated**: prefer `rkr_frame_add_atom_full`. Adds an atom (no
4087/// velocity, no forces) using per-axis fixed flags.
4088/// Returns `RKR_STATUS_SUCCESS` on success, or an error code.
4089///
4090/// # Safety
4091/// builder_handle and symbol must be valid.
4092#[unsafe(no_mangle)]
4093pub unsafe extern "C" fn rkr_frame_add_atom_with_fixed_mask(
4094    builder_handle: *mut RKRConFrameBuilder,
4095    symbol: *const c_char,
4096    x: f64,
4097    y: f64,
4098    z: f64,
4099    fixed_x: bool,
4100    fixed_y: bool,
4101    fixed_z: bool,
4102    atom_id: u64,
4103    mass: f64,
4104) -> RKRStatus {
4105    unsafe {
4106        add_builder_atom(
4107            builder_handle,
4108            symbol,
4109            x,
4110            y,
4111            z,
4112            [fixed_x, fixed_y, fixed_z],
4113            atom_id,
4114            mass,
4115            None,
4116            None,
4117        )
4118    }
4119}
4120/// **Deprecated**: prefer `rkr_frame_add_atom_full`. Adds an atom with
4121/// a velocity vector and a single uniform fixed flag.
4122/// Returns `RKR_STATUS_SUCCESS` on success, or an error code.
4123///
4124/// # Safety
4125/// builder_handle and symbol must be valid.
4126#[unsafe(no_mangle)]
4127pub unsafe extern "C" fn rkr_frame_add_atom_with_velocity(
4128    builder_handle: *mut RKRConFrameBuilder,
4129    symbol: *const c_char,
4130    x: f64,
4131    y: f64,
4132    z: f64,
4133    is_fixed: bool,
4134    atom_id: u64,
4135    mass: f64,
4136    vx: f64,
4137    vy: f64,
4138    vz: f64,
4139) -> RKRStatus {
4140    unsafe {
4141        add_builder_atom(
4142            builder_handle,
4143            symbol,
4144            x,
4145            y,
4146            z,
4147            [is_fixed; 3],
4148            atom_id,
4149            mass,
4150            Some([vx, vy, vz]),
4151            None,
4152        )
4153    }
4154}
4155/// **Deprecated**: prefer `rkr_frame_add_atom_full`. Adds an atom with
4156/// a velocity vector and per-axis fixed flags.
4157/// Returns `RKR_STATUS_SUCCESS` on success, or an error code.
4158///
4159/// # Safety
4160/// builder_handle and symbol must be valid.
4161#[unsafe(no_mangle)]
4162pub unsafe extern "C" fn rkr_frame_add_atom_with_velocity_fixed_mask(
4163    builder_handle: *mut RKRConFrameBuilder,
4164    symbol: *const c_char,
4165    x: f64,
4166    y: f64,
4167    z: f64,
4168    fixed_x: bool,
4169    fixed_y: bool,
4170    fixed_z: bool,
4171    atom_id: u64,
4172    mass: f64,
4173    vx: f64,
4174    vy: f64,
4175    vz: f64,
4176) -> RKRStatus {
4177    unsafe {
4178        add_builder_atom(
4179            builder_handle,
4180            symbol,
4181            x,
4182            y,
4183            z,
4184            [fixed_x, fixed_y, fixed_z],
4185            atom_id,
4186            mass,
4187            Some([vx, vy, vz]),
4188            None,
4189        )
4190    }
4191}
4192/// **Deprecated**: prefer `rkr_frame_add_atom_full`. Adds an atom with
4193/// a force vector and a single uniform fixed flag.
4194/// Returns `RKR_STATUS_SUCCESS` on success, or an error code.
4195///
4196/// # Safety
4197/// builder_handle and symbol must be valid.
4198#[unsafe(no_mangle)]
4199pub unsafe extern "C" fn rkr_frame_add_atom_with_forces(
4200    builder_handle: *mut RKRConFrameBuilder,
4201    symbol: *const c_char,
4202    x: f64,
4203    y: f64,
4204    z: f64,
4205    is_fixed: bool,
4206    atom_id: u64,
4207    mass: f64,
4208    fx: f64,
4209    fy: f64,
4210    fz: f64,
4211) -> RKRStatus {
4212    unsafe {
4213        add_builder_atom(
4214            builder_handle,
4215            symbol,
4216            x,
4217            y,
4218            z,
4219            [is_fixed; 3],
4220            atom_id,
4221            mass,
4222            None,
4223            Some([fx, fy, fz]),
4224        )
4225    }
4226}
4227/// **Deprecated**: prefer `rkr_frame_add_atom_full`. Adds an atom with
4228/// a force vector and per-axis fixed flags.
4229/// Returns `RKR_STATUS_SUCCESS` on success, or an error code.
4230///
4231/// # Safety
4232/// builder_handle and symbol must be valid.
4233#[unsafe(no_mangle)]
4234pub unsafe extern "C" fn rkr_frame_add_atom_with_forces_fixed_mask(
4235    builder_handle: *mut RKRConFrameBuilder,
4236    symbol: *const c_char,
4237    x: f64,
4238    y: f64,
4239    z: f64,
4240    fixed_x: bool,
4241    fixed_y: bool,
4242    fixed_z: bool,
4243    atom_id: u64,
4244    mass: f64,
4245    fx: f64,
4246    fy: f64,
4247    fz: f64,
4248) -> RKRStatus {
4249    unsafe {
4250        add_builder_atom(
4251            builder_handle,
4252            symbol,
4253            x,
4254            y,
4255            z,
4256            [fixed_x, fixed_y, fixed_z],
4257            atom_id,
4258            mass,
4259            None,
4260            Some([fx, fy, fz]),
4261        )
4262    }
4263}
4264/// **Deprecated**: prefer `rkr_frame_add_atom_full`. Adds an atom with
4265/// both velocity and force vectors and a single uniform fixed flag.
4266/// Returns `RKR_STATUS_SUCCESS` on success, or an error code.
4267///
4268/// # Safety
4269/// builder_handle and symbol must be valid.
4270#[unsafe(no_mangle)]
4271pub unsafe extern "C" fn rkr_frame_add_atom_with_velocity_and_forces(
4272    builder_handle: *mut RKRConFrameBuilder,
4273    symbol: *const c_char,
4274    x: f64,
4275    y: f64,
4276    z: f64,
4277    is_fixed: bool,
4278    atom_id: u64,
4279    mass: f64,
4280    vx: f64,
4281    vy: f64,
4282    vz: f64,
4283    fx: f64,
4284    fy: f64,
4285    fz: f64,
4286) -> RKRStatus {
4287    unsafe {
4288        add_builder_atom(
4289            builder_handle,
4290            symbol,
4291            x,
4292            y,
4293            z,
4294            [is_fixed; 3],
4295            atom_id,
4296            mass,
4297            Some([vx, vy, vz]),
4298            Some([fx, fy, fz]),
4299        )
4300    }
4301}
4302/// **Deprecated**: prefer `rkr_frame_add_atom_full`. Adds an atom with
4303/// both velocity and force vectors and per-axis fixed flags.
4304/// Returns `RKR_STATUS_SUCCESS` on success, or an error code.
4305///
4306/// # Safety
4307/// builder_handle and symbol must be valid.
4308#[unsafe(no_mangle)]
4309pub unsafe extern "C" fn rkr_frame_add_atom_with_velocity_and_forces_fixed_mask(
4310    builder_handle: *mut RKRConFrameBuilder,
4311    symbol: *const c_char,
4312    x: f64,
4313    y: f64,
4314    z: f64,
4315    fixed_x: bool,
4316    fixed_y: bool,
4317    fixed_z: bool,
4318    atom_id: u64,
4319    mass: f64,
4320    vx: f64,
4321    vy: f64,
4322    vz: f64,
4323    fx: f64,
4324    fy: f64,
4325    fz: f64,
4326) -> RKRStatus {
4327    unsafe {
4328        add_builder_atom(
4329            builder_handle,
4330            symbol,
4331            x,
4332            y,
4333            z,
4334            [fixed_x, fixed_y, fixed_z],
4335            atom_id,
4336            mass,
4337            Some([vx, vy, vz]),
4338            Some([fx, fy, fz]),
4339        )
4340    }
4341}
4342/// Consumes the builder and returns a finalized RKRConFrame handle.
4343/// The builder handle is invalidated after this call.
4344/// The caller OWNS the returned frame and MUST call `free_rkr_frame`.
4345/// Returns NULL on error, including
4346/// [`crate::error::ParseError::MassMismatch`].
4347///
4348/// # Safety
4349/// builder_handle must be valid. The caller takes ownership of the returned frame.
4350#[unsafe(no_mangle)]
4351pub unsafe extern "C" fn rkr_frame_builder_build(
4352    builder_handle: *mut RKRConFrameBuilder,
4353) -> *mut RKRConFrame {
4354    if builder_handle.is_null() {
4355        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
4356    }
4357    let builder = unsafe { *Box::from_raw(builder_handle as *mut ConFrameBuilder) };
4358    match builder.build() {
4359        Ok(frame) => Box::into_raw(Box::new(frame)) as *mut RKRConFrame,
4360        Err(_) => null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER),
4361    }
4362}
4363/// Frees a frame builder without building.
4364///
4365/// # Safety
4366/// builder_handle must be valid or null.
4367#[unsafe(no_mangle)]
4368pub unsafe extern "C" fn free_rkr_frame_builder(builder_handle: *mut RKRConFrameBuilder) {
4369    if !builder_handle.is_null() {
4370        let _ = unsafe { Box::from_raw(builder_handle as *mut ConFrameBuilder) };
4371    }
4372}
4373/// Cheap, copy-on-write clone of a frame builder. Returned handle owns
4374/// a new `ConFrameBuilder` whose per-atom buffers share storage with
4375/// the source via ArcArray; any subsequent mutation triggers a
4376/// per-buffer copy-on-write so writes do not leak across clones.
4377///
4378/// Intended for downstream consumers (NEB image bulk allocation,
4379/// trajectory snapshots) that need many builders carrying the same
4380/// per-atom data without paying N copies up-front. Returns NULL on
4381/// NULL input.
4382///
4383/// The caller OWNS the returned handle and MUST call
4384/// `free_rkr_frame_builder` (or consume via `rkr_frame_builder_build`).
4385///
4386/// # Safety
4387/// `builder_handle` must be a valid pointer returned by `rkr_frame_new`
4388/// (or by an earlier `rkr_frame_builder_clone`) and not yet freed.
4389#[unsafe(no_mangle)]
4390pub unsafe extern "C" fn rkr_frame_builder_clone(
4391    builder_handle: *const RKRConFrameBuilder,
4392) -> *mut RKRConFrameBuilder {
4393    if builder_handle.is_null() {
4394        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
4395    }
4396    let builder = unsafe { &*(builder_handle as *const ConFrameBuilder) };
4397    let cloned = builder.clone();
4398    Box::into_raw(Box::new(cloned)) as *mut RKRConFrameBuilder
4399}
4400/// Creates a new gzip-compressed frame writer for the specified file.
4401/// The caller OWNS the returned pointer and MUST call `free_rkr_writer`.
4402///
4403/// # Safety
4404/// filename_c must be valid. The caller takes ownership of the returned writer.
4405#[unsafe(no_mangle)]
4406pub unsafe extern "C" fn create_writer_gzip_c(filename_c: *const c_char) -> *mut RKRConFrameWriter {
4407    let filename = match unsafe { cstr_path(filename_c) } {
4408        Some(s) => s,
4409        None => return null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
4410    };
4411    match crate::compression::gzip_writer(Path::new(filename)) {
4412        Ok(encoder) => into_rkr_writer(Box::new(encoder), None),
4413        Err(_) => null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
4414    }
4415}
4416/// Creates a gzip-compressed frame writer with a custom floating-point
4417/// precision. The caller OWNS the returned pointer and MUST call
4418/// `free_rkr_writer`.
4419///
4420/// # Safety
4421/// filename_c must be valid. The caller takes ownership of the returned writer.
4422#[unsafe(no_mangle)]
4423pub unsafe extern "C" fn create_writer_gzip_with_precision_c(
4424    filename_c: *const c_char,
4425    precision: u8,
4426) -> *mut RKRConFrameWriter {
4427    let filename = match unsafe { cstr_path(filename_c) } {
4428        Some(s) => s,
4429        None => return null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
4430    };
4431    match crate::compression::gzip_writer(Path::new(filename)) {
4432        Ok(encoder) => into_rkr_writer(Box::new(encoder), Some(precision)),
4433        Err(_) => null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
4434    }
4435}
4436/// Creates a new zstd-compressed frame writer for the specified file.
4437/// The caller OWNS the returned pointer and MUST call `free_rkr_writer`.
4438///
4439/// Only present when readcon-core is built with the `zstd` Cargo
4440/// feature; the C header guards the declaration with
4441/// `READCON_CORE_HAS_ZSTD`.
4442///
4443/// # Safety
4444/// filename_c must be valid. The caller takes ownership of the returned writer.
4445#[cfg(feature = "zstd")]
4446#[unsafe(no_mangle)]
4447pub unsafe extern "C" fn create_writer_zstd_c(filename_c: *const c_char) -> *mut RKRConFrameWriter {
4448    let filename = match unsafe { cstr_path(filename_c) } {
4449        Some(s) => s,
4450        None => return null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
4451    };
4452    match crate::compression::zstd_writer(Path::new(filename)) {
4453        Ok(encoder) => into_rkr_writer(Box::new(encoder), None),
4454        Err(_) => null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
4455    }
4456}
4457/// Creates a zstd-compressed frame writer with a custom floating-point
4458/// precision. The caller OWNS the returned pointer and MUST call
4459/// `free_rkr_writer`.
4460///
4461/// Only present when readcon-core is built with the `zstd` Cargo
4462/// feature; the C header guards the declaration with
4463/// `READCON_CORE_HAS_ZSTD`.
4464///
4465/// # Safety
4466/// filename_c must be valid. The caller takes ownership of the returned writer.
4467#[cfg(feature = "zstd")]
4468#[unsafe(no_mangle)]
4469pub unsafe extern "C" fn create_writer_zstd_with_precision_c(
4470    filename_c: *const c_char,
4471    precision: u8,
4472) -> *mut RKRConFrameWriter {
4473    let filename = match unsafe { cstr_path(filename_c) } {
4474        Some(s) => s,
4475        None => return null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
4476    };
4477    match crate::compression::zstd_writer(Path::new(filename)) {
4478        Ok(encoder) => into_rkr_writer(Box::new(encoder), Some(precision)),
4479        Err(_) => null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
4480    }
4481}
4482//=============================================================================
4483// Direct mmap-based Reader FFI
4484//=============================================================================
4485/// Reads the first frame from a .con file.
4486/// Uses `read_to_string` for small files (< 64 KiB) and mmap for larger ones.
4487/// Stops after the first frame rather than parsing the entire file.
4488/// The caller OWNS the returned handle and MUST call `free_rkr_frame`.
4489/// Returns NULL on error.
4490///
4491/// # Safety
4492/// filename_c must be valid. The caller takes ownership of the returned frame.
4493#[unsafe(no_mangle)]
4494pub unsafe extern "C" fn rkr_read_first_frame(filename_c: *const c_char) -> *mut RKRConFrame {
4495    if filename_c.is_null() {
4496        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
4497    }
4498    let filename = match unsafe { CStr::from_ptr(filename_c).to_str() } {
4499        Ok(s) => s,
4500        Err(e) => {
4501            set_last_error(
4502                RKRStatus::RKR_STATUS_INVALID_UTF8 as i32,
4503                &e.to_string(),
4504                0,
4505                0,
4506            );
4507            return ptr::null_mut();
4508        }
4509    };
4510    match iterators::read_first_frame_located(Path::new(filename)) {
4511        Ok(frame) => Box::into_raw(Box::new(frame)) as *mut RKRConFrame,
4512        Err(e) => null_load(e),
4513    }
4514}
4515/// Reads all frames from a .con file using mmap.
4516/// Returns an array of frame handles and sets `num_frames` to the count.
4517/// The caller OWNS both the array and each frame handle.
4518/// Free frames with `free_rkr_frame` and the array with `free_rkr_frame_array`.
4519/// Returns NULL on error.
4520///
4521/// # Safety
4522/// filename_c and num_frames must be valid. The caller takes ownership of the returned handles and array.
4523#[unsafe(no_mangle)]
4524pub unsafe extern "C" fn rkr_read_all_frames(
4525    filename_c: *const c_char,
4526    num_frames: *mut usize,
4527) -> *mut *mut RKRConFrame {
4528    if filename_c.is_null() || num_frames.is_null() {
4529        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
4530    }
4531    let filename = match unsafe { CStr::from_ptr(filename_c).to_str() } {
4532        Ok(s) => s,
4533        Err(e) => {
4534            set_last_error(
4535                RKRStatus::RKR_STATUS_INVALID_UTF8 as i32,
4536                &e.to_string(),
4537                0,
4538                0,
4539            );
4540            return ptr::null_mut();
4541        }
4542    };
4543    match iterators::read_all_frames_located(Path::new(filename), None) {
4544        Ok(frames) => pack_frame_handles(frames, num_frames),
4545        Err(e) => null_load(e),
4546    }
4547}
4548
4549/// Like [`rkr_read_all_frames`], with an explicit worker count.
4550///
4551/// `n_threads == 0` and `n_threads == 1` parse on the calling thread.
4552/// `n_threads >= 2` pins a Rayon pool of that size when `parallel` is
4553/// on; otherwise the parse is sequential.
4554///
4555/// # Safety
4556/// Same contract as [`rkr_read_all_frames`].
4557#[unsafe(no_mangle)]
4558pub unsafe extern "C" fn rkr_read_all_frames_n_threads(
4559    filename_c: *const c_char,
4560    num_frames: *mut usize,
4561    n_threads: usize,
4562) -> *mut *mut RKRConFrame {
4563    if filename_c.is_null() || num_frames.is_null() {
4564        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
4565    }
4566    let filename = match unsafe { CStr::from_ptr(filename_c).to_str() } {
4567        Ok(s) => s,
4568        Err(e) => {
4569            set_last_error(
4570                RKRStatus::RKR_STATUS_INVALID_UTF8 as i32,
4571                &e.to_string(),
4572                0,
4573                0,
4574            );
4575            return ptr::null_mut();
4576        }
4577    };
4578    let threads = if n_threads == 0 {
4579        None
4580    } else {
4581        Some(n_threads)
4582    };
4583    match iterators::read_all_frames_located(Path::new(filename), threads) {
4584        Ok(frames) => pack_frame_handles(frames, num_frames),
4585        Err(e) => null_load(e),
4586    }
4587}
4588
4589/// Opaque owner of a coordinate column. The allocation is [`PositionOwned`].
4590pub struct RKRPositionBlock {
4591    _private: [u8; 0],
4592}
4593
4594struct PositionOwned {
4595    values: Vec<f64>,
4596    n_frames: usize,
4597    n_atoms: usize,
4598}
4599
4600/// Coordinates of every frame, one row-major `f64` buffer from the column walker.
4601///
4602/// `*n_frames` and `*n_atoms` are set on success. The caller owns the
4603/// returned handle and frees it with [`rkr_free_position_block`]. Values
4604/// are borrowed with [`rkr_position_block_values`] until that free. A file
4605/// whose frames do not share one atom count fails the same way
4606/// [`crate::iterators::read_positions_with_threads`] does. `n_threads == 0`
4607/// and `n_threads == 1` parse on the calling thread. `n_threads >= 2`
4608/// reparses each recorded span on a Rayon pool when `parallel` is on.
4609///
4610/// Returns NULL on error. `rkr_last_error` carries the same class, message,
4611/// line, and frame as [`rkr_read_all_frames`] for a file that reader rejects.
4612///
4613/// # Safety
4614/// `filename_c`, `n_frames`, and `n_atoms` must be valid. The caller takes
4615/// ownership of the returned handle.
4616#[unsafe(no_mangle)]
4617pub unsafe extern "C" fn rkr_read_positions_n_threads(
4618    filename_c: *const c_char,
4619    n_frames: *mut usize,
4620    n_atoms: *mut usize,
4621    n_threads: usize,
4622) -> *mut RKRPositionBlock {
4623    if filename_c.is_null() || n_frames.is_null() || n_atoms.is_null() {
4624        return null_err::<RKRPositionBlock>(RKRStatus::RKR_STATUS_NULL_POINTER);
4625    }
4626    let filename = match unsafe { CStr::from_ptr(filename_c).to_str() } {
4627        Ok(s) => s,
4628        Err(e) => {
4629            set_last_error(
4630                RKRStatus::RKR_STATUS_INVALID_UTF8 as i32,
4631                &e.to_string(),
4632                0,
4633                0,
4634            );
4635            return ptr::null_mut();
4636        }
4637    };
4638    let threads = if n_threads == 0 {
4639        None
4640    } else {
4641        Some(n_threads)
4642    };
4643    match iterators::read_positions_with_threads(Path::new(filename), threads) {
4644        Ok(block) => {
4645            unsafe {
4646                *n_frames = block.n_frames;
4647                *n_atoms = block.n_atoms;
4648            }
4649            Box::into_raw(Box::new(PositionOwned {
4650                n_frames: block.n_frames,
4651                n_atoms: block.n_atoms,
4652                values: block.values,
4653            })) as *mut RKRPositionBlock
4654        }
4655        Err(err) => {
4656            note_boxed(err);
4657            ptr::null_mut()
4658        }
4659    }
4660}
4661
4662/// Like [`rkr_read_positions_n_threads`] on the calling thread.
4663///
4664/// # Safety
4665/// Same contract as [`rkr_read_positions_n_threads`].
4666#[unsafe(no_mangle)]
4667pub unsafe extern "C" fn rkr_read_positions(
4668    filename_c: *const c_char,
4669    n_frames: *mut usize,
4670    n_atoms: *mut usize,
4671) -> *mut RKRPositionBlock {
4672    unsafe { rkr_read_positions_n_threads(filename_c, n_frames, n_atoms, 1) }
4673}
4674
4675/// Row-major `x y z` pointer for a block from [`rkr_read_positions`].
4676///
4677/// The pointer is valid until [`rkr_free_position_block`]. NULL when
4678/// `block` is NULL.
4679///
4680/// # Safety
4681/// `block` is null or a live handle from [`rkr_read_positions`].
4682#[unsafe(no_mangle)]
4683pub unsafe extern "C" fn rkr_position_block_values(block: *const RKRPositionBlock) -> *const f64 {
4684    if block.is_null() {
4685        return ptr::null();
4686    }
4687    let owned = unsafe { &*(block as *const PositionOwned) };
4688    debug_assert_eq!(
4689        owned.values.len(),
4690        owned
4691            .n_frames
4692            .saturating_mul(owned.n_atoms)
4693            .saturating_mul(3)
4694    );
4695    owned.values.as_ptr()
4696}
4697
4698/// Frees a handle from [`rkr_read_positions`]. NULL is a no-op.
4699///
4700/// # Safety
4701/// `block` is null or the pointer returned by [`rkr_read_positions`].
4702#[unsafe(no_mangle)]
4703pub unsafe extern "C" fn rkr_free_position_block(block: *mut RKRPositionBlock) {
4704    if block.is_null() {
4705        return;
4706    }
4707    unsafe {
4708        drop(Box::from_raw(block as *mut PositionOwned));
4709    }
4710}
4711
4712/// Pack owned frames into a C array (`len == capacity`) and write `num_frames`.
4713pub(crate) fn pack_frame_handles(
4714    frames: Vec<ConFrame>,
4715    num_frames: *mut usize,
4716) -> *mut *mut RKRConFrame {
4717    let count = frames.len();
4718    let mut handles: Vec<*mut RKRConFrame> = frames
4719        .into_iter()
4720        .map(|f| Box::into_raw(Box::new(f)) as *mut RKRConFrame)
4721        .collect();
4722    handles.shrink_to_fit();
4723    debug_assert_eq!(handles.len(), handles.capacity());
4724    let ptr = handles.as_mut_ptr();
4725    std::mem::forget(handles);
4726    unsafe { *num_frames = count };
4727    ptr
4728}
4729/// Frees an array of frame handles returned by `rkr_read_all_frames`.
4730/// Each frame is freed individually, then the array itself.
4731///
4732/// # Safety
4733/// frames must be valid or null.
4734#[unsafe(no_mangle)]
4735pub unsafe extern "C" fn free_rkr_frame_array(frames: *mut *mut RKRConFrame, num_frames: usize) {
4736    if frames.is_null() {
4737        return;
4738    }
4739    unsafe {
4740        let handles = Vec::from_raw_parts(frames, num_frames, num_frames);
4741        for handle in handles {
4742            if !handle.is_null() {
4743                let _ = Box::from_raw(handle as *mut ConFrame);
4744            }
4745        }
4746    }
4747}
4748/// Free only the outer pointer array from `rkr_read_all_frames` (not the frames).
4749///
4750/// # Safety
4751/// `frames` null or from `rkr_read_all_frames` with length `num_frames`. Frame
4752/// pointers must be owned elsewhere (e.g. language wrappers).
4753#[unsafe(no_mangle)]
4754pub unsafe extern "C" fn free_rkr_frame_ptr_array(
4755    frames: *mut *mut RKRConFrame,
4756    num_frames: usize,
4757) {
4758    if frames.is_null() {
4759        return;
4760    }
4761    unsafe {
4762        let _ptrs = Vec::from_raw_parts(frames, num_frames, num_frames);
4763    }
4764}
4765
4766//=============================================================================
4767// ---------------------------------------------------------------------------
4768// Metatensor TensorBlock exports (`metatensor` Cargo feature)
4769//
4770// Boundary types are metatensor-sys only (`metatensor::c_api::mts_block_t`).
4771// Construction: `metatensor_export` (high-level). Transfer/free: single helpers
4772// in that module (`tensor_block_into_raw_mts` / `mts_block_free_sys`).
4773// Lean builds omit these symbols (`READCON_CORE_HAS_METATENSOR` in the header).
4774// ---------------------------------------------------------------------------
4775/// Free an owned block from `rkr_frame_metatensor_*_block`.
4776/// Prefer this or `mts_block_free` (metatensor.h) — not both on the same pointer.
4777///
4778/// # Safety
4779/// `block` is NULL or an owning `mts_block_t*` from this library's transfer helper.
4780#[cfg(feature = "metatensor")]
4781#[unsafe(no_mangle)]
4782pub unsafe extern "C" fn rkr_mts_block_free(block: *mut metatensor::c_api::mts_block_t) {
4783    unsafe { crate::metatensor_export::mts_block_free_sys(block) };
4784}
4785/// Positions `[N,3]` TensorBlock. Caller frees with `rkr_mts_block_free` / `mts_block_free`.
4786/// # Safety
4787///
4788/// A non-null pointer argument must point at a live value of its declared
4789/// type for this call. A null pointer is handled inside the function.
4790#[cfg(feature = "metatensor")]
4791#[unsafe(no_mangle)]
4792pub unsafe extern "C" fn rkr_frame_metatensor_positions_block(
4793    frame_handle: *const RKRConFrame,
4794    out_block: *mut *mut metatensor::c_api::mts_block_t,
4795) -> RKRStatus {
4796    if frame_handle.is_null() || out_block.is_null() {
4797        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
4798    }
4799    unsafe { *out_block = std::ptr::null_mut() };
4800    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
4801        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
4802    };
4803    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4804        crate::metatensor_export::frame_positions_block(frame)
4805    })) {
4806        Ok(Ok(b)) => {
4807            unsafe { *out_block = crate::metatensor_export::tensor_block_into_raw_mts(b) };
4808            note(RKRStatus::RKR_STATUS_SUCCESS)
4809        }
4810        Ok(Err(_)) | Err(_) => note(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
4811    }
4812}
4813/// # Safety
4814///
4815/// A non-null pointer argument must point at a live value of its declared
4816/// type for this call. A null pointer is handled inside the function.
4817#[cfg(feature = "metatensor")]
4818#[unsafe(no_mangle)]
4819pub unsafe extern "C" fn rkr_frame_metatensor_velocities_block(
4820    frame_handle: *const RKRConFrame,
4821    out_block: *mut *mut metatensor::c_api::mts_block_t,
4822) -> RKRStatus {
4823    if frame_handle.is_null() || out_block.is_null() {
4824        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
4825    }
4826    unsafe { *out_block = std::ptr::null_mut() };
4827    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
4828        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
4829    };
4830    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4831        crate::metatensor_export::frame_velocities_block(frame)
4832    })) {
4833        Ok(Ok(Some(b))) => {
4834            unsafe { *out_block = crate::metatensor_export::tensor_block_into_raw_mts(b) };
4835            note(RKRStatus::RKR_STATUS_SUCCESS)
4836        }
4837        Ok(Ok(None)) => note(RKRStatus::RKR_STATUS_SECTION_ABSENT),
4838        Ok(Err(_)) | Err(_) => note(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
4839    }
4840}
4841/// # Safety
4842///
4843/// A non-null pointer argument must point at a live value of its declared
4844/// type for this call. A null pointer is handled inside the function.
4845#[cfg(feature = "metatensor")]
4846#[unsafe(no_mangle)]
4847pub unsafe extern "C" fn rkr_frame_metatensor_forces_block(
4848    frame_handle: *const RKRConFrame,
4849    out_block: *mut *mut metatensor::c_api::mts_block_t,
4850) -> RKRStatus {
4851    if frame_handle.is_null() || out_block.is_null() {
4852        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
4853    }
4854    unsafe { *out_block = std::ptr::null_mut() };
4855    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
4856        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
4857    };
4858    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4859        crate::metatensor_export::frame_forces_block(frame)
4860    })) {
4861        Ok(Ok(Some(b))) => {
4862            unsafe { *out_block = crate::metatensor_export::tensor_block_into_raw_mts(b) };
4863            note(RKRStatus::RKR_STATUS_SUCCESS)
4864        }
4865        Ok(Ok(None)) => note(RKRStatus::RKR_STATUS_SECTION_ABSENT),
4866        Ok(Err(_)) | Err(_) => note(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
4867    }
4868}
4869/// # Safety
4870///
4871/// A non-null pointer argument must point at a live value of its declared
4872/// type for this call. A null pointer is handled inside the function.
4873#[cfg(feature = "metatensor")]
4874#[unsafe(no_mangle)]
4875pub unsafe extern "C" fn rkr_frame_metatensor_atom_energies_block(
4876    frame_handle: *const RKRConFrame,
4877    out_block: *mut *mut metatensor::c_api::mts_block_t,
4878) -> RKRStatus {
4879    if frame_handle.is_null() || out_block.is_null() {
4880        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
4881    }
4882    unsafe { *out_block = std::ptr::null_mut() };
4883    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
4884        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
4885    };
4886    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4887        crate::metatensor_export::frame_energies_block(frame)
4888    })) {
4889        Ok(Ok(Some(b))) => {
4890            unsafe { *out_block = crate::metatensor_export::tensor_block_into_raw_mts(b) };
4891            note(RKRStatus::RKR_STATUS_SUCCESS)
4892        }
4893        Ok(Ok(None)) => note(RKRStatus::RKR_STATUS_SECTION_ABSENT),
4894        Ok(Err(_)) | Err(_) => note(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
4895    }
4896}
4897/// # Safety
4898///
4899/// A non-null pointer argument must point at a live value of its declared
4900/// type for this call. A null pointer is handled inside the function.
4901#[cfg(not(feature = "zstd"))]
4902#[unsafe(no_mangle)]
4903pub unsafe extern "C" fn create_writer_zstd_c(
4904    _filename_c: *const c_char,
4905) -> *mut RKRConFrameWriter {
4906    ptr::null_mut()
4907}
4908/// # Safety
4909///
4910/// A non-null pointer argument must point at a live value of its declared
4911/// type for this call. A null pointer is handled inside the function.
4912#[cfg(not(feature = "zstd"))]
4913#[unsafe(no_mangle)]
4914pub unsafe extern "C" fn create_writer_zstd_with_precision_c(
4915    _filename_c: *const c_char,
4916    _precision: u8,
4917) -> *mut RKRConFrameWriter {
4918    ptr::null_mut()
4919}
4920//=============================================================================
4921/// Lean-build stubs: always export metatensor C symbols so Fortran/C can link without `#ifdef`.
4922/// Real implementations live under `feature = "metatensor"`.
4923#[cfg(not(feature = "metatensor"))]
4924// No #[repr(C)]: cbindgen then emits an incomplete struct, which C and C++
4925// accept under -pedantic. The zero-length field keeps it unconstructible.
4926// The name is the C type. Renaming it would change the exported ABI.
4927#[allow(non_camel_case_types)]
4928pub struct mts_block_t {
4929    _private: [u8; 0],
4930}
4931/// # Safety
4932///
4933/// A non-null pointer argument must point at a live value of its declared
4934/// type for this call. A null pointer is handled inside the function.
4935#[cfg(not(feature = "metatensor"))]
4936#[unsafe(no_mangle)]
4937pub unsafe extern "C" fn rkr_mts_block_free(_block: *mut mts_block_t) {}
4938/// # Safety
4939///
4940/// A non-null pointer argument must point at a live value of its declared
4941/// type for this call. A null pointer is handled inside the function.
4942#[cfg(not(feature = "metatensor"))]
4943#[unsafe(no_mangle)]
4944pub unsafe extern "C" fn rkr_frame_metatensor_positions_block(
4945    _frame_handle: *const RKRConFrame,
4946    out_block: *mut *mut mts_block_t,
4947) -> RKRStatus {
4948    if !out_block.is_null() {
4949        unsafe { *out_block = std::ptr::null_mut() };
4950    }
4951    note(RKRStatus::RKR_STATUS_FEATURE_DISABLED)
4952}
4953/// # Safety
4954///
4955/// A non-null pointer argument must point at a live value of its declared
4956/// type for this call. A null pointer is handled inside the function.
4957#[cfg(not(feature = "metatensor"))]
4958#[unsafe(no_mangle)]
4959pub unsafe extern "C" fn rkr_frame_metatensor_velocities_block(
4960    _frame_handle: *const RKRConFrame,
4961    out_block: *mut *mut mts_block_t,
4962) -> RKRStatus {
4963    if !out_block.is_null() {
4964        unsafe { *out_block = std::ptr::null_mut() };
4965    }
4966    note(RKRStatus::RKR_STATUS_FEATURE_DISABLED)
4967}
4968/// # Safety
4969///
4970/// A non-null pointer argument must point at a live value of its declared
4971/// type for this call. A null pointer is handled inside the function.
4972#[cfg(not(feature = "metatensor"))]
4973#[unsafe(no_mangle)]
4974pub unsafe extern "C" fn rkr_frame_metatensor_forces_block(
4975    _frame_handle: *const RKRConFrame,
4976    out_block: *mut *mut mts_block_t,
4977) -> RKRStatus {
4978    if !out_block.is_null() {
4979        unsafe { *out_block = std::ptr::null_mut() };
4980    }
4981    note(RKRStatus::RKR_STATUS_FEATURE_DISABLED)
4982}
4983/// # Safety
4984///
4985/// A non-null pointer argument must point at a live value of its declared
4986/// type for this call. A null pointer is handled inside the function.
4987#[cfg(not(feature = "metatensor"))]
4988#[unsafe(no_mangle)]
4989pub unsafe extern "C" fn rkr_frame_metatensor_atom_energies_block(
4990    _frame_handle: *const RKRConFrame,
4991    out_block: *mut *mut mts_block_t,
4992) -> RKRStatus {
4993    if !out_block.is_null() {
4994        unsafe { *out_block = std::ptr::null_mut() };
4995    }
4996    note(RKRStatus::RKR_STATUS_FEATURE_DISABLED)
4997}
4998// ----- Frame section buffers (no CFrame AoS required) -------------------------
4999/// Number of atoms on the frame (atom_data order).
5000/// # Safety
5001///
5002/// A non-null pointer argument must point at a live value of its declared
5003/// type for this call. A null pointer is handled inside the function.
5004#[unsafe(no_mangle)]
5005pub unsafe extern "C" fn rkr_frame_atom_count(frame_handle: *const RKRConFrame) -> usize {
5006    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
5007        return 0;
5008    };
5009    frame.atom_data.len()
5010}
5011/// Borrow positions SoA. `out->data` is valid until `free_rkr_frame`.
5012/// # Safety
5013///
5014/// A non-null pointer argument must point at a live value of its declared
5015/// type for this call. A null pointer is handled inside the function.
5016#[unsafe(no_mangle)]
5017pub unsafe extern "C" fn rkr_frame_xyz_view(
5018    frame_handle: *const RKRConFrame,
5019    out: *mut RKRArrayView,
5020) -> RKRStatus {
5021    fill_array2_view(frame_handle, out, |f| &f.positions, false)
5022}
5023
5024/// Borrow velocities SoA, or `SECTION_ABSENT`.
5025/// # Safety
5026///
5027/// A non-null pointer argument must point at a live value of its declared
5028/// type for this call. A null pointer is handled inside the function.
5029#[unsafe(no_mangle)]
5030pub unsafe extern "C" fn rkr_frame_velocities_view(
5031    frame_handle: *const RKRConFrame,
5032    out: *mut RKRArrayView,
5033) -> RKRStatus {
5034    fill_array2_view(frame_handle, out, |f| &f.velocities, true)
5035}
5036
5037/// Borrow forces SoA, or `SECTION_ABSENT`.
5038/// # Safety
5039///
5040/// A non-null pointer argument must point at a live value of its declared
5041/// type for this call. A null pointer is handled inside the function.
5042#[unsafe(no_mangle)]
5043pub unsafe extern "C" fn rkr_frame_forces_view(
5044    frame_handle: *const RKRConFrame,
5045    out: *mut RKRArrayView,
5046) -> RKRStatus {
5047    fill_array2_view(frame_handle, out, |f| &f.forces, true)
5048}
5049
5050/// True when the frame carries a `"displacements"` section. False for a
5051/// NULL handle.
5052///
5053/// # Safety
5054/// `frame_handle` is NULL or a valid frame handle.
5055#[unsafe(no_mangle)]
5056pub unsafe extern "C" fn rkr_frame_has_displacements(frame_handle: *const RKRConFrame) -> bool {
5057    match unsafe { (frame_handle as *const ConFrame).as_ref() } {
5058        Some(f) => f.has_displacements(),
5059        None => false,
5060    }
5061}
5062
5063/// Borrow displacements SoA, or `SECTION_ABSENT`.
5064///
5065/// # Safety
5066/// `frame_handle` must be a valid frame handle and `out` a writable view.
5067#[unsafe(no_mangle)]
5068pub unsafe extern "C" fn rkr_frame_displacements_view(
5069    frame_handle: *const RKRConFrame,
5070    out: *mut RKRArrayView,
5071) -> RKRStatus {
5072    fill_array2_view(frame_handle, out, |f| &f.displacements, true)
5073}
5074
5075/// True when the frame carries a `"spreads"` section. False for a
5076/// NULL handle.
5077///
5078/// # Safety
5079/// `frame_handle` is NULL or a valid frame handle.
5080#[unsafe(no_mangle)]
5081pub unsafe extern "C" fn rkr_frame_has_spreads(frame_handle: *const RKRConFrame) -> bool {
5082    match unsafe { (frame_handle as *const ConFrame).as_ref() } {
5083        Some(f) => f.has_spreads(),
5084        None => false,
5085    }
5086}
5087
5088/// Borrow spreads SoA, or `SECTION_ABSENT`.
5089///
5090/// # Safety
5091/// `frame_handle` must be a valid frame handle and `out` a writable view.
5092#[unsafe(no_mangle)]
5093pub unsafe extern "C" fn rkr_frame_spreads_view(
5094    frame_handle: *const RKRConFrame,
5095    out: *mut RKRArrayView,
5096) -> RKRStatus {
5097    fill_array2_view(frame_handle, out, |f| &f.spreads, true)
5098}
5099
5100/// Borrow per-atom energies, or `SECTION_ABSENT`.
5101/// # Safety
5102///
5103/// A non-null pointer argument must point at a live value of its declared
5104/// type for this call. A null pointer is handled inside the function.
5105#[unsafe(no_mangle)]
5106pub unsafe extern "C" fn rkr_frame_energies_view(
5107    frame_handle: *const RKRConFrame,
5108    out: *mut RKRArrayView,
5109) -> RKRStatus {
5110    fill_array1_view(frame_handle, out, |f| &f.atom_energies, true)
5111}
5112
5113/// Borrow per-atom masses.
5114/// # Safety
5115///
5116/// A non-null pointer argument must point at a live value of its declared
5117/// type for this call. A null pointer is handled inside the function.
5118#[unsafe(no_mangle)]
5119pub unsafe extern "C" fn rkr_frame_masses_view(
5120    frame_handle: *const RKRConFrame,
5121    out: *mut RKRArrayView,
5122) -> RKRStatus {
5123    fill_array1_view(frame_handle, out, |f| &f.masses, false)
5124}
5125
5126/// Borrow `atom_id` column (always u64).
5127/// # Safety
5128///
5129/// A non-null pointer argument must point at a live value of its declared
5130/// type for this call. A null pointer is handled inside the function.
5131#[unsafe(no_mangle)]
5132pub unsafe extern "C" fn rkr_frame_atom_ids_view(
5133    frame_handle: *const RKRConFrame,
5134    out: *mut RKRArrayView,
5135) -> RKRStatus {
5136    if frame_handle.is_null() || out.is_null() {
5137        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5138    }
5139    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
5140        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5141    };
5142    let slice = frame.atom_ids.as_slice_memory_order();
5143    unsafe {
5144        *out = RKRArrayView {
5145            data: slice
5146                .map(|s| s.as_ptr() as *const std::ffi::c_void)
5147                .unwrap_or(std::ptr::null()),
5148            n: frame.atom_ids.len(),
5149            cols: 1,
5150            dtype_code: 1, // kDLUInt
5151            dtype_bits: 64,
5152        };
5153    }
5154    note(RKRStatus::RKR_STATUS_SUCCESS)
5155}
5156
5157/// Row-major f64 xyz pointer, or NULL if storage is not float64.
5158/// `*n` receives the atom count. Pointer is valid until `free_rkr_frame`.
5159/// # Safety
5160///
5161/// A non-null pointer argument must point at a live value of its declared
5162/// type for this call. A null pointer is handled inside the function.
5163#[unsafe(no_mangle)]
5164pub unsafe extern "C" fn rkr_frame_xyz_f64(
5165    frame_handle: *const RKRConFrame,
5166    n: *mut usize,
5167) -> *const f64 {
5168    f64_col_ptr(frame_handle, n, |f| f.positions.f64_slice())
5169}
5170
5171/// Row-major f64 velocities pointer, or NULL if absent / not float64.
5172/// # Safety
5173///
5174/// A non-null pointer argument must point at a live value of its declared
5175/// type for this call. A null pointer is handled inside the function.
5176#[unsafe(no_mangle)]
5177pub unsafe extern "C" fn rkr_frame_velocities_f64(
5178    frame_handle: *const RKRConFrame,
5179    n: *mut usize,
5180) -> *const f64 {
5181    f64_col_ptr(frame_handle, n, |f| f.velocities.f64_slice())
5182}
5183
5184/// Row-major f64 forces pointer, or NULL if absent / not float64.
5185/// # Safety
5186///
5187/// A non-null pointer argument must point at a live value of its declared
5188/// type for this call. A null pointer is handled inside the function.
5189#[unsafe(no_mangle)]
5190pub unsafe extern "C" fn rkr_frame_forces_f64(
5191    frame_handle: *const RKRConFrame,
5192    n: *mut usize,
5193) -> *const f64 {
5194    f64_col_ptr(frame_handle, n, |f| f.forces.f64_slice())
5195}
5196
5197/// Row-major f64 displacements pointer, or NULL if absent / not float64.
5198///
5199/// # Safety
5200/// `frame_handle` must be a valid frame handle; `n` is NULL or writable.
5201#[unsafe(no_mangle)]
5202pub unsafe extern "C" fn rkr_frame_displacements_f64(
5203    frame_handle: *const RKRConFrame,
5204    n: *mut usize,
5205) -> *const f64 {
5206    f64_col_ptr(frame_handle, n, |f| f.displacements.f64_slice())
5207}
5208
5209/// Row-major f64 spreads pointer, or NULL if absent / not float64.
5210///
5211/// # Safety
5212/// `frame_handle` must be a valid frame handle; `n` is NULL or writable.
5213#[unsafe(no_mangle)]
5214pub unsafe extern "C" fn rkr_frame_spreads_f64(
5215    frame_handle: *const RKRConFrame,
5216    n: *mut usize,
5217) -> *const f64 {
5218    f64_col_ptr(frame_handle, n, |f| f.spreads.f64_slice())
5219}
5220
5221fn fill_array2_view(
5222    frame_handle: *const RKRConFrame,
5223    out: *mut RKRArrayView,
5224    get: impl FnOnce(&ConFrame) -> &crate::storage_dtype::FloatArray2,
5225    section: bool,
5226) -> RKRStatus {
5227    if frame_handle.is_null() || out.is_null() {
5228        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5229    }
5230    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
5231        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5232    };
5233    let arr = get(frame);
5234    if section && arr.nrows() == 0 {
5235        unsafe { *out = RKRArrayView::empty() };
5236        return note(RKRStatus::RKR_STATUS_SECTION_ABSENT);
5237    }
5238    unsafe { *out = RKRArrayView::from_array2(arr) };
5239    note(RKRStatus::RKR_STATUS_SUCCESS)
5240}
5241
5242fn fill_array1_view(
5243    frame_handle: *const RKRConFrame,
5244    out: *mut RKRArrayView,
5245    get: impl FnOnce(&ConFrame) -> &crate::storage_dtype::FloatArray1,
5246    section: bool,
5247) -> RKRStatus {
5248    if frame_handle.is_null() || out.is_null() {
5249        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5250    }
5251    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
5252        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5253    };
5254    let arr = get(frame);
5255    if section && arr.is_empty() {
5256        unsafe { *out = RKRArrayView::empty() };
5257        return note(RKRStatus::RKR_STATUS_SECTION_ABSENT);
5258    }
5259    unsafe { *out = RKRArrayView::from_array1(arr) };
5260    note(RKRStatus::RKR_STATUS_SUCCESS)
5261}
5262
5263fn f64_col_ptr(
5264    frame_handle: *const RKRConFrame,
5265    n: *mut usize,
5266    get: impl FnOnce(&ConFrame) -> Option<&[f64]>,
5267) -> *const f64 {
5268    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
5269        if !n.is_null() {
5270            unsafe { *n = 0 };
5271        }
5272        return std::ptr::null();
5273    };
5274    match get(frame) {
5275        Some(s) if !s.is_empty() => {
5276            if !n.is_null() {
5277                unsafe { *n = s.len() / 3 };
5278            }
5279            s.as_ptr()
5280        }
5281        _ => {
5282            if !n.is_null() {
5283                unsafe { *n = 0 };
5284            }
5285            std::ptr::null()
5286        }
5287    }
5288}
5289
5290/// Copy positions as row-major `[x0,y0,z0,...]` into `out` (length >= 3*N).
5291/// Prefers a memcpy from the SoA column; falls back to AoS only if SoA is empty.
5292/// # Safety
5293///
5294/// A non-null pointer argument must point at a live value of its declared
5295/// type for this call. A null pointer is handled inside the function.
5296#[unsafe(no_mangle)]
5297pub unsafe extern "C" fn rkr_frame_copy_positions(
5298    frame_handle: *const RKRConFrame,
5299    out: *mut f64,
5300    out_len: usize,
5301) -> RKRStatus {
5302    copy_array2_f64(frame_handle, out, out_len, |f| &f.positions, false)
5303}
5304fn copy_array2_f64(
5305    frame_handle: *const RKRConFrame,
5306    out: *mut f64,
5307    out_len: usize,
5308    get: impl FnOnce(&ConFrame) -> &crate::storage_dtype::FloatArray2,
5309    section: bool,
5310) -> RKRStatus {
5311    if frame_handle.is_null() || out.is_null() {
5312        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5313    }
5314    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
5315        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5316    };
5317    let arr = get(frame);
5318    let n = if arr.nrows() > 0 {
5319        arr.nrows()
5320    } else {
5321        frame.atom_data.len()
5322    };
5323    if section && arr.nrows() == 0 {
5324        return note(RKRStatus::RKR_STATUS_SECTION_ABSENT);
5325    }
5326    let need = n.saturating_mul(3);
5327    if out_len < need {
5328        return note(RKRStatus::RKR_STATUS_BUFFER_TOO_SMALL);
5329    }
5330    let dest = unsafe { std::slice::from_raw_parts_mut(out, need) };
5331    if arr.nrows() == n {
5332        if let Some(src) = arr.f64_slice() {
5333            dest.copy_from_slice(&src[..need.min(src.len())]);
5334            return note(RKRStatus::RKR_STATUS_SUCCESS);
5335        }
5336        for i in 0..n {
5337            let row = arr.as_f64_row(i);
5338            dest[i * 3] = row[0];
5339            dest[i * 3 + 1] = row[1];
5340            dest[i * 3 + 2] = row[2];
5341        }
5342        return note(RKRStatus::RKR_STATUS_SUCCESS);
5343    }
5344    for (i, a) in frame.atom_data.iter().enumerate() {
5345        dest[i * 3] = a.x;
5346        dest[i * 3 + 1] = a.y;
5347        dest[i * 3 + 2] = a.z;
5348    }
5349    note(RKRStatus::RKR_STATUS_SUCCESS)
5350}
5351
5352fn copy_array1_f64(
5353    frame_handle: *const RKRConFrame,
5354    out: *mut f64,
5355    out_len: usize,
5356    get: impl FnOnce(&ConFrame) -> &crate::storage_dtype::FloatArray1,
5357    section: bool,
5358) -> RKRStatus {
5359    if frame_handle.is_null() || out.is_null() {
5360        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5361    }
5362    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
5363        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5364    };
5365    let arr = get(frame);
5366    let n = if !arr.is_empty() {
5367        arr.len()
5368    } else {
5369        frame.atom_data.len()
5370    };
5371    if section && arr.is_empty() {
5372        return note(RKRStatus::RKR_STATUS_SECTION_ABSENT);
5373    }
5374    if out_len < n {
5375        return note(RKRStatus::RKR_STATUS_BUFFER_TOO_SMALL);
5376    }
5377    let dest = unsafe { std::slice::from_raw_parts_mut(out, n) };
5378    if let Some(src) = arr.f64_slice() {
5379        dest.copy_from_slice(&src[..n.min(src.len())]);
5380        return note(RKRStatus::RKR_STATUS_SUCCESS);
5381    }
5382    for (slot, dest_i) in dest.iter_mut().enumerate() {
5383        *dest_i = arr.get_f64(slot);
5384    }
5385    note(RKRStatus::RKR_STATUS_SUCCESS)
5386}
5387
5388/// # Safety
5389///
5390/// A non-null pointer argument must point at a live value of its declared
5391/// type for this call. A null pointer is handled inside the function.
5392#[unsafe(no_mangle)]
5393pub unsafe extern "C" fn rkr_frame_copy_velocities(
5394    frame_handle: *const RKRConFrame,
5395    out: *mut f64,
5396    out_len: usize,
5397) -> RKRStatus {
5398    copy_array2_f64(frame_handle, out, out_len, |f| &f.velocities, true)
5399}
5400/// # Safety
5401///
5402/// A non-null pointer argument must point at a live value of its declared
5403/// type for this call. A null pointer is handled inside the function.
5404#[unsafe(no_mangle)]
5405pub unsafe extern "C" fn rkr_frame_copy_forces(
5406    frame_handle: *const RKRConFrame,
5407    out: *mut f64,
5408    out_len: usize,
5409) -> RKRStatus {
5410    copy_array2_f64(frame_handle, out, out_len, |f| &f.forces, true)
5411}
5412/// Copy displacements into row-major `out` (length >= `3 * N`), or
5413/// `SECTION_ABSENT`.
5414///
5415/// # Safety
5416/// `frame_handle` must be a valid frame handle; `out` must hold `out_len` f64.
5417#[unsafe(no_mangle)]
5418pub unsafe extern "C" fn rkr_frame_copy_displacements(
5419    frame_handle: *const RKRConFrame,
5420    out: *mut f64,
5421    out_len: usize,
5422) -> RKRStatus {
5423    copy_array2_f64(frame_handle, out, out_len, |f| &f.displacements, true)
5424}
5425/// Copy spreads into row-major `out` (length >= `3 * N`), or
5426/// `SECTION_ABSENT`.
5427///
5428/// # Safety
5429/// `frame_handle` must be a valid frame handle; `out` must hold `out_len` f64.
5430#[unsafe(no_mangle)]
5431pub unsafe extern "C" fn rkr_frame_copy_spreads(
5432    frame_handle: *const RKRConFrame,
5433    out: *mut f64,
5434    out_len: usize,
5435) -> RKRStatus {
5436    copy_array2_f64(frame_handle, out, out_len, |f| &f.spreads, true)
5437}
5438/// # Safety
5439///
5440/// A non-null pointer argument must point at a live value of its declared
5441/// type for this call. A null pointer is handled inside the function.
5442#[unsafe(no_mangle)]
5443pub unsafe extern "C" fn rkr_frame_copy_atom_energies(
5444    frame_handle: *const RKRConFrame,
5445    out: *mut f64,
5446    out_len: usize,
5447) -> RKRStatus {
5448    copy_array1_f64(frame_handle, out, out_len, |f| &f.atom_energies, true)
5449}
5450/// # Safety
5451///
5452/// A non-null pointer argument must point at a live value of its declared
5453/// type for this call. A null pointer is handled inside the function.
5454#[unsafe(no_mangle)]
5455pub unsafe extern "C" fn rkr_frame_copy_masses(
5456    frame_handle: *const RKRConFrame,
5457    out: *mut f64,
5458    out_len: usize,
5459) -> RKRStatus {
5460    copy_array1_f64(frame_handle, out, out_len, |f| &f.masses, false)
5461}
5462/// # Safety
5463///
5464/// A non-null pointer argument must point at a live value of its declared
5465/// type for this call. A null pointer is handled inside the function.
5466#[unsafe(no_mangle)]
5467pub unsafe extern "C" fn rkr_frame_copy_atom_ids(
5468    frame_handle: *const RKRConFrame,
5469    out: *mut u64,
5470    out_len: usize,
5471) -> RKRStatus {
5472    if frame_handle.is_null() || out.is_null() {
5473        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5474    }
5475    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
5476        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5477    };
5478    let n = frame.atom_ids.len().max(frame.atom_data.len());
5479    if out_len < n {
5480        return note(RKRStatus::RKR_STATUS_BUFFER_TOO_SMALL);
5481    }
5482    let dest = unsafe { std::slice::from_raw_parts_mut(out, n) };
5483    if let Some(src) = frame.atom_ids.as_slice_memory_order() {
5484        dest[..src.len().min(n)].copy_from_slice(&src[..src.len().min(n)]);
5485        return note(RKRStatus::RKR_STATUS_SUCCESS);
5486    }
5487    for (i, a) in frame.atom_data.iter().enumerate() {
5488        dest[i] = a.atom_id;
5489    }
5490    note(RKRStatus::RKR_STATUS_SUCCESS)
5491}
5492fn frame_positions_arc(frame: &ConFrame) -> ndarray::ArcArray2<f64> {
5493    let n = frame.atom_data.len();
5494    let mut data = Vec::with_capacity(n * 3);
5495    for a in &frame.atom_data {
5496        data.extend_from_slice(&[a.x, a.y, a.z]);
5497    }
5498    ndarray::ArcArray2::from_shape_vec((n, 3), data)
5499        .unwrap_or_else(|_| ndarray::ArcArray2::zeros((0, 3)))
5500}
5501
5502/// Metatensor-style: export positions as they are stored (CPU f64), with
5503/// explicit device request. Non-CPU → `FEATURE_DISABLED`. Prefer this over
5504/// dtype-cast `*_dlpack_ex` for new code.
5505///
5506/// `stream` and `max_version_*` are accepted for ABI alignment with
5507/// metatensor `as_dlpack`; CPU ignores stream / version negotiation for now.
5508///
5509/// # Safety
5510/// Handles and `out_tensor` must be valid.
5511#[unsafe(no_mangle)]
5512pub unsafe extern "C" fn rkr_frame_positions_as_dlpack(
5513    frame_handle: *const RKRConFrame,
5514    device_type: i32,
5515    device_id: i32,
5516    _stream: i64,
5517    _max_version_major: u32,
5518    _max_version_minor: u32,
5519    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
5520) -> RKRStatus {
5521    if frame_handle.is_null() || out_tensor.is_null() {
5522        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5523    }
5524    unsafe { *out_tensor = std::ptr::null_mut() };
5525    let dl_device = if device_type == rkr_dl_device_type::RKR_DL_CPU {
5526        dlpk::sys::DLDevice::cpu()
5527    } else if device_type == rkr_dl_device_type::RKR_DL_CUDA {
5528        #[cfg(feature = "cuda")]
5529        {
5530            dlpk::sys::DLDevice::cuda(device_id)
5531        }
5532        #[cfg(not(feature = "cuda"))]
5533        {
5534            let _ = device_id;
5535            return note(RKRStatus::RKR_STATUS_FEATURE_DISABLED);
5536        }
5537    } else {
5538        return note(RKRStatus::RKR_STATUS_FEATURE_DISABLED);
5539    };
5540    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
5541        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5542    };
5543    // Opaque SoA storage → DLPack; CUDA requests H2D via storage_dtype / cuda_array.
5544    match frame.positions_as_dlpack(dl_device) {
5545        Ok(tensor) => {
5546            let raw = tensor.into_raw();
5547            unsafe {
5548                *out_tensor = raw.as_ptr();
5549            }
5550            note(RKRStatus::RKR_STATUS_SUCCESS)
5551        }
5552        Err(e) => map_dlpack_err(e),
5553    }
5554}
5555
5556/// Ingest positions from a DLManagedTensorVersioned (CPU float32/64, shape (N,3)
5557/// or length 3N). Metatensor-style write path symmetry.
5558///
5559/// # Safety
5560/// `frame` must be a valid mutable frame; `tensor` non-null managed tensor.
5561#[unsafe(no_mangle)]
5562pub unsafe extern "C" fn rkr_frame_positions_from_dlpack(
5563    frame_handle: *mut RKRConFrame,
5564    tensor: *const RKRDLManagedTensorVersioned,
5565) -> RKRStatus {
5566    if frame_handle.is_null() || tensor.is_null() {
5567        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5568    }
5569    let frame = unsafe { &mut *(frame_handle as *mut ConFrame) };
5570    let dl = unsafe { &(*tensor).dl_tensor };
5571    if dl.device.device_type != dlpk::sys::DLDeviceType::kDLCPU {
5572        return note(RKRStatus::RKR_STATUS_FEATURE_DISABLED);
5573    }
5574    let n = frame.atom_data.len();
5575    let need = n.saturating_mul(3);
5576    let ndim = dl.ndim as usize;
5577    let shape = if dl.shape.is_null() {
5578        return note(RKRStatus::RKR_STATUS_VALIDATION_ERROR);
5579    } else {
5580        unsafe { std::slice::from_raw_parts(dl.shape, ndim) }
5581    };
5582    let shape_ok = (ndim == 2 && shape[0] == n as i64 && shape[1] == 3)
5583        || (ndim == 1 && shape[0] == need as i64);
5584    if !shape_ok {
5585        return note(RKRStatus::RKR_STATUS_VALIDATION_ERROR);
5586    }
5587    let nelem = need;
5588    let code = dl.dtype.code as u8;
5589    let bits = dl.dtype.bits;
5590    if dl.data.is_null() {
5591        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5592    }
5593    let vals: Vec<f64> = if code == rkr_dl_type_code::RKR_DL_FLOAT && bits == 64 {
5594        let s = unsafe { std::slice::from_raw_parts(dl.data as *const f64, nelem) };
5595        s.to_vec()
5596    } else if code == rkr_dl_type_code::RKR_DL_FLOAT && bits == 32 {
5597        let s = unsafe { std::slice::from_raw_parts(dl.data as *const f32, nelem) };
5598        s.iter().map(|&x| x as f64).collect()
5599    } else {
5600        return note(RKRStatus::RKR_STATUS_VALIDATION_ERROR);
5601    };
5602    if frame.positions.nrows() != n {
5603        return note(RKRStatus::RKR_STATUS_VALIDATION_ERROR);
5604    }
5605    for i in 0..n {
5606        frame
5607            .positions
5608            .set_f64_row(i, [vals[i * 3], vals[i * 3 + 1], vals[i * 3 + 2]]);
5609    }
5610    frame.sync_atom_data_from_arrays();
5611    note(RKRStatus::RKR_STATUS_SUCCESS)
5612}
5613
5614/// DLPack positions from a frame (default float64 / CPU). Prefer
5615/// [`rkr_frame_positions_as_dlpack`] for metatensor-style device negotiation.
5616/// # Safety
5617///
5618/// A non-null pointer argument must point at a live value of its declared
5619/// type for this call. A null pointer is handled inside the function.
5620#[unsafe(no_mangle)]
5621pub unsafe extern "C" fn rkr_frame_positions_dlpack(
5622    frame_handle: *const RKRConFrame,
5623    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
5624) -> RKRStatus {
5625    unsafe {
5626        rkr_frame_positions_as_dlpack(
5627            frame_handle,
5628            rkr_dl_device_type::RKR_DL_CPU,
5629            0,
5630            0,
5631            1,
5632            0,
5633            out_tensor,
5634        )
5635    }
5636}
5637
5638/// Frame positions with [`RKRDlpackExportOptions`] (`opts` NULL → f64/CPU).
5639///
5640/// # Safety
5641/// `frame_handle` / `out_tensor` valid; `opts` null or valid.
5642#[unsafe(no_mangle)]
5643pub unsafe extern "C" fn rkr_frame_positions_dlpack_ex(
5644    frame_handle: *const RKRConFrame,
5645    opts: *const RKRDlpackExportOptions,
5646    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
5647) -> RKRStatus {
5648    if frame_handle.is_null() || out_tensor.is_null() {
5649        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5650    }
5651    unsafe { *out_tensor = std::ptr::null_mut() };
5652    let o = match resolve_dlpack_opts(opts) {
5653        Ok(o) => o,
5654        Err(st) => return st,
5655    };
5656    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
5657        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5658    };
5659    let arr = frame_positions_arc(frame);
5660    export_owned_array2_dlpack_opts(&arr, &o, out_tensor)
5661}
5662
5663/// DLPack velocities from a frame, or `SECTION_ABSENT` if missing (f64/CPU).
5664/// # Safety
5665///
5666/// A non-null pointer argument must point at a live value of its declared
5667/// type for this call. A null pointer is handled inside the function.
5668#[unsafe(no_mangle)]
5669pub unsafe extern "C" fn rkr_frame_velocities_dlpack(
5670    frame_handle: *const RKRConFrame,
5671    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
5672) -> RKRStatus {
5673    unsafe { rkr_frame_velocities_dlpack_ex(frame_handle, std::ptr::null(), out_tensor) }
5674}
5675
5676/// # Safety
5677///
5678/// A non-null pointer argument must point at a live value of its declared
5679/// type for this call. A null pointer is handled inside the function.
5680#[unsafe(no_mangle)]
5681pub unsafe extern "C" fn rkr_frame_velocities_dlpack_ex(
5682    frame_handle: *const RKRConFrame,
5683    opts: *const RKRDlpackExportOptions,
5684    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
5685) -> RKRStatus {
5686    if frame_handle.is_null() || out_tensor.is_null() {
5687        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5688    }
5689    unsafe { *out_tensor = std::ptr::null_mut() };
5690    let o = match resolve_dlpack_opts(opts) {
5691        Ok(o) => o,
5692        Err(st) => return st,
5693    };
5694    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
5695        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5696    };
5697    if !frame.has_velocities() {
5698        return note(RKRStatus::RKR_STATUS_SECTION_ABSENT);
5699    }
5700    let n = frame.atom_data.len();
5701    let mut data = Vec::with_capacity(n * 3);
5702    for a in &frame.atom_data {
5703        let v = a.velocity().unwrap_or([0.0; 3]);
5704        data.extend_from_slice(&v);
5705    }
5706    let arr = ndarray::ArcArray2::from_shape_vec((n, 3), data)
5707        .unwrap_or_else(|_| ndarray::ArcArray2::zeros((0, 3)));
5708    export_owned_array2_dlpack_opts(&arr, &o, out_tensor)
5709}
5710
5711/// DLPack forces from a frame, or `SECTION_ABSENT` if missing (f64/CPU default).
5712/// # Safety
5713///
5714/// A non-null pointer argument must point at a live value of its declared
5715/// type for this call. A null pointer is handled inside the function.
5716#[unsafe(no_mangle)]
5717pub unsafe extern "C" fn rkr_frame_forces_dlpack(
5718    frame_handle: *const RKRConFrame,
5719    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
5720) -> RKRStatus {
5721    unsafe { rkr_frame_forces_dlpack_ex(frame_handle, std::ptr::null(), out_tensor) }
5722}
5723
5724/// # Safety
5725///
5726/// A non-null pointer argument must point at a live value of its declared
5727/// type for this call. A null pointer is handled inside the function.
5728#[unsafe(no_mangle)]
5729pub unsafe extern "C" fn rkr_frame_forces_dlpack_ex(
5730    frame_handle: *const RKRConFrame,
5731    opts: *const RKRDlpackExportOptions,
5732    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
5733) -> RKRStatus {
5734    if frame_handle.is_null() || out_tensor.is_null() {
5735        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5736    }
5737    unsafe { *out_tensor = std::ptr::null_mut() };
5738    let o = match resolve_dlpack_opts(opts) {
5739        Ok(o) => o,
5740        Err(st) => return st,
5741    };
5742    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
5743        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5744    };
5745    if !frame.has_forces() {
5746        return note(RKRStatus::RKR_STATUS_SECTION_ABSENT);
5747    }
5748    let n = frame.atom_data.len();
5749    let mut data = Vec::with_capacity(n * 3);
5750    for a in &frame.atom_data {
5751        let f = a.force().unwrap_or([0.0; 3]);
5752        data.extend_from_slice(&f);
5753    }
5754    let arr = ndarray::ArcArray2::from_shape_vec((n, 3), data)
5755        .unwrap_or_else(|_| ndarray::ArcArray2::zeros((0, 3)));
5756    export_owned_array2_dlpack_opts(&arr, &o, out_tensor)
5757}
5758
5759/// DLPack displacements from a frame, or `SECTION_ABSENT` if missing
5760/// (f64/CPU default).
5761///
5762/// # Safety
5763/// `frame_handle` must be a valid frame handle; `out_tensor` must be a
5764/// writable pointer. Free the tensor with `rkr_dlpack_delete`.
5765#[unsafe(no_mangle)]
5766pub unsafe extern "C" fn rkr_frame_displacements_dlpack(
5767    frame_handle: *const RKRConFrame,
5768    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
5769) -> RKRStatus {
5770    unsafe { rkr_frame_displacements_dlpack_ex(frame_handle, std::ptr::null(), out_tensor) }
5771}
5772
5773/// Like [`rkr_frame_displacements_dlpack`] with export options (NULL
5774/// `opts` selects float64 on CPU).
5775///
5776/// # Safety
5777/// Same contract as [`rkr_frame_displacements_dlpack`]; `opts` is NULL or
5778/// points to a valid `RKRDlpackExportOptions`.
5779#[unsafe(no_mangle)]
5780pub unsafe extern "C" fn rkr_frame_displacements_dlpack_ex(
5781    frame_handle: *const RKRConFrame,
5782    opts: *const RKRDlpackExportOptions,
5783    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
5784) -> RKRStatus {
5785    if frame_handle.is_null() || out_tensor.is_null() {
5786        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5787    }
5788    unsafe { *out_tensor = std::ptr::null_mut() };
5789    let o = match resolve_dlpack_opts(opts) {
5790        Ok(o) => o,
5791        Err(st) => return st,
5792    };
5793    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
5794        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5795    };
5796    if !frame.has_displacements() {
5797        return note(RKRStatus::RKR_STATUS_SECTION_ABSENT);
5798    }
5799    let n = frame.atom_data.len();
5800    let mut data = Vec::with_capacity(n * 3);
5801    for a in &frame.atom_data {
5802        let d = a.displacement().unwrap_or([0.0; 3]);
5803        data.extend_from_slice(&d);
5804    }
5805    let arr = ndarray::ArcArray2::from_shape_vec((n, 3), data)
5806        .unwrap_or_else(|_| ndarray::ArcArray2::zeros((0, 3)));
5807    export_owned_array2_dlpack_opts(&arr, &o, out_tensor)
5808}
5809
5810/// DLPack spreads from a frame, or `SECTION_ABSENT` if missing
5811/// (f64/CPU default).
5812///
5813/// # Safety
5814/// `frame_handle` must be a valid frame handle; `out_tensor` must be a
5815/// writable pointer. Free the tensor with `rkr_dlpack_delete`.
5816#[unsafe(no_mangle)]
5817pub unsafe extern "C" fn rkr_frame_spreads_dlpack(
5818    frame_handle: *const RKRConFrame,
5819    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
5820) -> RKRStatus {
5821    unsafe { rkr_frame_spreads_dlpack_ex(frame_handle, std::ptr::null(), out_tensor) }
5822}
5823
5824/// Like [`rkr_frame_spreads_dlpack`] with export options (NULL
5825/// `opts` selects float64 on CPU).
5826///
5827/// # Safety
5828/// Same contract as [`rkr_frame_spreads_dlpack`]; `opts` is NULL or
5829/// points to a valid `RKRDlpackExportOptions`.
5830#[unsafe(no_mangle)]
5831pub unsafe extern "C" fn rkr_frame_spreads_dlpack_ex(
5832    frame_handle: *const RKRConFrame,
5833    opts: *const RKRDlpackExportOptions,
5834    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
5835) -> RKRStatus {
5836    if frame_handle.is_null() || out_tensor.is_null() {
5837        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5838    }
5839    unsafe { *out_tensor = std::ptr::null_mut() };
5840    let o = match resolve_dlpack_opts(opts) {
5841        Ok(o) => o,
5842        Err(st) => return st,
5843    };
5844    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
5845        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5846    };
5847    if !frame.has_spreads() {
5848        return note(RKRStatus::RKR_STATUS_SECTION_ABSENT);
5849    }
5850    let n = frame.atom_data.len();
5851    let mut data = Vec::with_capacity(n * 3);
5852    for a in &frame.atom_data {
5853        let d = a.spread().unwrap_or([0.0; 3]);
5854        data.extend_from_slice(&d);
5855    }
5856    let arr = ndarray::ArcArray2::from_shape_vec((n, 3), data)
5857        .unwrap_or_else(|_| ndarray::ArcArray2::zeros((0, 3)));
5858    export_owned_array2_dlpack_opts(&arr, &o, out_tensor)
5859}
5860
5861/// DLPack per-atom energies, or `SECTION_ABSENT` if missing (f64/CPU default).
5862/// # Safety
5863///
5864/// A non-null pointer argument must point at a live value of its declared
5865/// type for this call. A null pointer is handled inside the function.
5866#[unsafe(no_mangle)]
5867pub unsafe extern "C" fn rkr_frame_atom_energies_dlpack(
5868    frame_handle: *const RKRConFrame,
5869    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
5870) -> RKRStatus {
5871    unsafe { rkr_frame_atom_energies_dlpack_ex(frame_handle, std::ptr::null(), out_tensor) }
5872}
5873
5874/// # Safety
5875///
5876/// A non-null pointer argument must point at a live value of its declared
5877/// type for this call. A null pointer is handled inside the function.
5878#[unsafe(no_mangle)]
5879pub unsafe extern "C" fn rkr_frame_atom_energies_dlpack_ex(
5880    frame_handle: *const RKRConFrame,
5881    opts: *const RKRDlpackExportOptions,
5882    out_tensor: *mut *mut RKRDLManagedTensorVersioned,
5883) -> RKRStatus {
5884    if frame_handle.is_null() || out_tensor.is_null() {
5885        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5886    }
5887    unsafe { *out_tensor = std::ptr::null_mut() };
5888    let o = match resolve_dlpack_opts(opts) {
5889        Ok(o) => o,
5890        Err(st) => return st,
5891    };
5892    let Some(frame) = (unsafe { (frame_handle as *const ConFrame).as_ref() }) else {
5893        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5894    };
5895    if !frame.has_energies() {
5896        return note(RKRStatus::RKR_STATUS_SECTION_ABSENT);
5897    }
5898    let data: Vec<f64> = frame
5899        .atom_data
5900        .iter()
5901        .map(|a| a.energy().unwrap_or(0.0))
5902        .collect();
5903    let arr = ndarray::ArcArray1::from_vec(data);
5904    export_owned_array1_f64_dlpack_opts(&arr, &o, out_tensor)
5905}
5906
5907// Chemfiles selection (always linked; real impl needs --features chemfiles)
5908//=============================================================================
5909/// Opaque handle for a cached selection evaluation result.
5910pub struct RKRSelectionResult;
5911/// Evaluate a chemfiles selection-language string on an `RKRConFrame`.
5912///
5913/// On success writes a heap-allocated result handle to `*out_result` (caller
5914/// frees with [`rkr_selection_result_free`]). Returns
5915/// `RKR_STATUS_SELECTION_ERROR` for invalid grammar, evaluation failure, or
5916/// when this build was compiled without the `chemfiles` feature.
5917///
5918/// # Safety
5919/// `frame_handle`, `selection`, and `out_result` must be non-null; `selection`
5920/// must point to a valid UTF-8 C string.
5921#[unsafe(no_mangle)]
5922pub unsafe extern "C" fn rkr_frame_select(
5923    frame_handle: *const RKRConFrame,
5924    selection: *const c_char,
5925    out_result: *mut *mut RKRSelectionResult,
5926) -> RKRStatus {
5927    if frame_handle.is_null() || selection.is_null() || out_result.is_null() {
5928        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5929    }
5930    let frame = unsafe { &*(frame_handle as *const ConFrame) };
5931    let sel_str = match unsafe { CStr::from_ptr(selection) }.to_str() {
5932        Ok(s) => s,
5933        Err(_) => return note(RKRStatus::RKR_STATUS_INVALID_UTF8),
5934    };
5935    match crate::chemfiles_selection::evaluate_selection_on_con_frame(sel_str, frame) {
5936        Ok(result) => {
5937            let boxed = Box::new(result);
5938            unsafe {
5939                *out_result = Box::into_raw(boxed) as *mut RKRSelectionResult;
5940            }
5941            note(RKRStatus::RKR_STATUS_SUCCESS)
5942        }
5943        Err(_) => note(RKRStatus::RKR_STATUS_SELECTION_ERROR),
5944    }
5945}
5946/// Number of matches in a selection result.
5947///
5948/// # Safety
5949/// `result_handle` must be a valid handle from [`rkr_frame_select`] or NULL.
5950#[unsafe(no_mangle)]
5951pub unsafe extern "C" fn rkr_selection_result_match_count(
5952    result_handle: *const RKRSelectionResult,
5953) -> u64 {
5954    if result_handle.is_null() {
5955        return 0;
5956    }
5957    let result = unsafe { &*(result_handle as *const crate::chemfiles_selection::SelectionResult) };
5958    result.matches.len() as u64
5959}
5960/// Selection context size (1=atom, 2=pair, 3=angle, 4=dihedral).
5961///
5962/// # Safety
5963/// `result_handle` must be valid or NULL (returns 0).
5964#[unsafe(no_mangle)]
5965pub unsafe extern "C" fn rkr_selection_result_context_size(
5966    result_handle: *const RKRSelectionResult,
5967) -> u32 {
5968    if result_handle.is_null() {
5969        return 0;
5970    }
5971    let result = unsafe { &*(result_handle as *const crate::chemfiles_selection::SelectionResult) };
5972    result.context_size as u32
5973}
5974/// Copy match `match_index` atom indices into `out_atoms` (up to 4 slots).
5975/// Writes actual arity to `*out_size` when non-null.
5976///
5977/// # Safety
5978/// Handles and `out_atoms` must be valid; `out_atoms` needs space for 4 `uint64_t`.
5979#[unsafe(no_mangle)]
5980pub unsafe extern "C" fn rkr_selection_result_match_at(
5981    result_handle: *const RKRSelectionResult,
5982    match_index: u64,
5983    out_atoms: *mut u64,
5984    out_size: *mut u32,
5985) -> RKRStatus {
5986    if result_handle.is_null() || out_atoms.is_null() {
5987        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
5988    }
5989    let result = unsafe { &*(result_handle as *const crate::chemfiles_selection::SelectionResult) };
5990    let idx = match_index as usize;
5991    if idx >= result.matches.len() {
5992        return note(RKRStatus::RKR_STATUS_INDEX_OUT_OF_BOUNDS);
5993    }
5994    let m = &result.matches[idx];
5995    unsafe {
5996        for i in 0..4 {
5997            *out_atoms.add(i) = if i < m.size {
5998                m.atoms[i] as u64
5999            } else {
6000                u64::MAX
6001            };
6002        }
6003        if !out_size.is_null() {
6004            *out_size = m.size as u32;
6005        }
6006    }
6007    note(RKRStatus::RKR_STATUS_SUCCESS)
6008}
6009/// Fill `out_indices` with primary atom indices for each match (length =
6010/// match count). Returns `RKR_STATUS_BUFFER_TOO_SMALL` if `capacity` is too small.
6011///
6012/// # Safety
6013/// `result_handle` and `out_indices` must be valid when capacity > 0.
6014#[unsafe(no_mangle)]
6015pub unsafe extern "C" fn rkr_selection_result_primary_indices(
6016    result_handle: *const RKRSelectionResult,
6017    out_indices: *mut u64,
6018    capacity: u64,
6019    out_written: *mut u64,
6020) -> RKRStatus {
6021    if result_handle.is_null() {
6022        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
6023    }
6024    let result = unsafe { &*(result_handle as *const crate::chemfiles_selection::SelectionResult) };
6025    let n = result.matches.len() as u64;
6026    if !out_written.is_null() {
6027        unsafe {
6028            *out_written = n;
6029        }
6030    }
6031    if n == 0 {
6032        return note(RKRStatus::RKR_STATUS_SUCCESS);
6033    }
6034    if out_indices.is_null() {
6035        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
6036    }
6037    if capacity < n {
6038        return note(RKRStatus::RKR_STATUS_BUFFER_TOO_SMALL);
6039    }
6040    unsafe {
6041        for (i, m) in result.matches.iter().enumerate() {
6042            *out_indices.add(i) = m.atoms[0] as u64;
6043        }
6044    }
6045    note(RKRStatus::RKR_STATUS_SUCCESS)
6046}
6047/// Free a selection result from [`rkr_frame_select`]. Safe with NULL.
6048///
6049/// # Safety
6050/// `result_handle` must be from `rkr_frame_select` or NULL.
6051#[unsafe(no_mangle)]
6052pub unsafe extern "C" fn rkr_selection_result_free(result_handle: *mut RKRSelectionResult) {
6053    if result_handle.is_null() {
6054        return;
6055    }
6056    unsafe {
6057        drop(Box::from_raw(
6058            result_handle as *mut crate::chemfiles_selection::SelectionResult,
6059        ));
6060    }
6061}
6062/// Returns 1 when this library build includes chemfiles selection support.
6063#[unsafe(no_mangle)]
6064pub extern "C" fn rkr_has_chemfiles_support() -> u8 {
6065    #[cfg(feature = "chemfiles")]
6066    {
6067        1
6068    }
6069    #[cfg(not(feature = "chemfiles"))]
6070    {
6071        0
6072    }
6073}
6074
6075/// Returns 1 when this library build includes Rayon multi-frame parse.
6076#[unsafe(no_mangle)]
6077pub extern "C" fn rkr_has_parallel_support() -> u8 {
6078    #[cfg(feature = "parallel")]
6079    {
6080        1
6081    }
6082    #[cfg(not(feature = "parallel"))]
6083    {
6084        0
6085    }
6086}
6087/// Read the first frame from a chemfiles-supported path (XYZ, PDB, GRO, …).
6088/// Returns NULL on error or without the `chemfiles` feature. Caller: `free_rkr_frame`.
6089///
6090/// # Safety
6091/// `path_c` must be a valid NUL-terminated UTF-8 path.
6092#[unsafe(no_mangle)]
6093pub unsafe extern "C" fn rkr_read_chemfiles_first(path_c: *const c_char) -> *mut RKRConFrame {
6094    if path_c.is_null() {
6095        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
6096    }
6097    let Ok(path_str) = unsafe { CStr::from_ptr(path_c) }.to_str() else {
6098        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
6099    };
6100    match crate::chemfiles_import::con_frame_from_trajectory_path(path_str) {
6101        Ok(frame) => Box::into_raw(Box::new(frame)) as *mut RKRConFrame,
6102        Err(_) => null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER),
6103    }
6104}
6105
6106/// Read every step from a chemfiles-supported path. Sets `*num_frames`.
6107/// Free with `free_rkr_frame_array`. NULL on error / without chemfiles.
6108///
6109/// # Safety
6110/// `path_c` valid UTF-8; `num_frames` non-null.
6111#[unsafe(no_mangle)]
6112pub unsafe extern "C" fn rkr_read_chemfiles(
6113    path_c: *const c_char,
6114    num_frames: *mut usize,
6115) -> *mut *mut RKRConFrame {
6116    if path_c.is_null() || num_frames.is_null() {
6117        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
6118    }
6119    let Ok(path_str) = unsafe { CStr::from_ptr(path_c) }.to_str() else {
6120        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
6121    };
6122    match crate::chemfiles_import::con_frames_from_trajectory_path(path_str) {
6123        Ok(frames) => pack_frame_handles(frames, num_frames),
6124        Err(_) => null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER),
6125    }
6126}
6127
6128/// Read step `index` via chemfiles `Trajectory::read_step`.
6129/// Returns NULL on error, out of range, or without the `chemfiles` feature.
6130///
6131/// # Safety
6132/// `path_c` must be a valid NUL-terminated UTF-8 path.
6133#[unsafe(no_mangle)]
6134pub unsafe extern "C" fn rkr_read_chemfiles_nth(
6135    path_c: *const c_char,
6136    index: usize,
6137) -> *mut RKRConFrame {
6138    if path_c.is_null() {
6139        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
6140    }
6141    let Ok(path_str) = unsafe { CStr::from_ptr(path_c) }.to_str() else {
6142        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
6143    };
6144    match crate::chemfiles_import::con_frame_from_trajectory_path_nth(path_str, index) {
6145        Ok(frame) => Box::into_raw(Box::new(frame)) as *mut RKRConFrame,
6146        Err(_) => null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER),
6147    }
6148}
6149
6150/// Number of steps in a chemfiles trajectory (`Trajectory::nsteps`).
6151/// Returns `usize::MAX` on error or without the `chemfiles` feature.
6152///
6153/// # Safety
6154/// `path_c` must be a valid NUL-terminated UTF-8 path.
6155#[unsafe(no_mangle)]
6156pub unsafe extern "C" fn rkr_chemfiles_nsteps(path_c: *const c_char) -> usize {
6157    if path_c.is_null() {
6158        return usize::MAX;
6159    }
6160    let Ok(path_str) = unsafe { CStr::from_ptr(path_c) }.to_str() else {
6161        return usize::MAX;
6162    };
6163    crate::chemfiles_import::nsteps_from_trajectory_path(path_str).unwrap_or(usize::MAX)
6164}
6165
6166/// Read a chemfiles window: steps `start, start+step, … < stop`.
6167/// `stop == usize::MAX` means `nsteps`. `guess_bonds != 0` guesses topology
6168/// when the frame has no bonds. Sets `*num_frames`.
6169/// Free with `free_rkr_frame_array`. NULL on error / without chemfiles.
6170///
6171/// # Safety
6172/// `path_c` valid UTF-8; `num_frames` non-null. `topology_c` may be NULL.
6173#[unsafe(no_mangle)]
6174pub unsafe extern "C" fn rkr_read_chemfiles_range(
6175    path_c: *const c_char,
6176    start: usize,
6177    step: usize,
6178    stop: usize,
6179    topology_c: *const c_char,
6180    guess_bonds: u8,
6181    num_frames: *mut usize,
6182) -> *mut *mut RKRConFrame {
6183    if path_c.is_null() || num_frames.is_null() {
6184        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
6185    }
6186    let Ok(path_str) = unsafe { CStr::from_ptr(path_c) }.to_str() else {
6187        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
6188    };
6189    let topology = if topology_c.is_null() {
6190        None
6191    } else {
6192        match unsafe { CStr::from_ptr(topology_c) }.to_str() {
6193            Ok(s) if !s.is_empty() => Some(std::path::PathBuf::from(s)),
6194            _ => return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER),
6195        }
6196    };
6197    let opts = crate::chemfiles_import::ChemfilesReadOpts {
6198        start,
6199        step,
6200        stop: if stop == usize::MAX { None } else { Some(stop) },
6201        format: None,
6202        topology,
6203        topology_format: None,
6204        guess_bonds: guess_bonds != 0,
6205    };
6206    match crate::chemfiles_import::con_frames_from_trajectory_path_with(path_str, &opts) {
6207        Ok(frames) => pack_frame_handles(frames, num_frames),
6208        Err(_) => null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
6209    }
6210}
6211/// Read all frames from memory with chemfiles `format` (e.g. `"XYZ"`).
6212/// Sets `*num_frames`. Free frames with `free_rkr_frame` and the array with
6213/// `free_rkr_frame_array`. NULL on error / without chemfiles.
6214///
6215/// # Safety
6216/// `data_c`, `format_c` valid UTF-8 C strings; `num_frames` non-null.
6217#[unsafe(no_mangle)]
6218pub unsafe extern "C" fn rkr_read_chemfiles_memory(
6219    data_c: *const c_char,
6220    format_c: *const c_char,
6221    num_frames: *mut usize,
6222) -> *mut *mut RKRConFrame {
6223    if data_c.is_null() || format_c.is_null() || num_frames.is_null() {
6224        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
6225    }
6226    let Ok(data) = unsafe { CStr::from_ptr(data_c) }.to_str() else {
6227        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
6228    };
6229    let Ok(format) = unsafe { CStr::from_ptr(format_c) }.to_str() else {
6230        return null_err::<_>(RKRStatus::RKR_STATUS_NULL_POINTER);
6231    };
6232    match crate::chemfiles_import::con_frames_from_memory(data, format) {
6233        Ok(frames) => {
6234            let n = frames.len();
6235            unsafe { *num_frames = n };
6236            let mut ptrs: Vec<*mut RKRConFrame> = frames
6237                .into_iter()
6238                .map(|f| Box::into_raw(Box::new(f)) as *mut RKRConFrame)
6239                .collect();
6240            let p = ptrs.as_mut_ptr();
6241            std::mem::forget(ptrs);
6242            p
6243        }
6244        Err(_) => null_err::<_>(RKRStatus::RKR_STATUS_INTERNAL_ERROR),
6245    }
6246}
6247/// Free a DLPack tensor from `rkr_frame_builder_*_dlpack` (calls deleter). Safe with NULL.
6248///
6249/// # Safety
6250/// `tensor` must be NULL or a pointer from a dlpack export of this library.
6251#[unsafe(no_mangle)]
6252pub unsafe extern "C" fn rkr_dlpack_delete(tensor: *mut RKRDLManagedTensorVersioned) {
6253    if tensor.is_null() {
6254        return;
6255    }
6256    unsafe {
6257        let t = &mut *tensor;
6258        if let Some(del) = t.deleter {
6259            del(tensor);
6260        }
6261    }
6262}
6263
6264/// Pack a frame as RCSO bytes for a caller-side `MPI_Bcast`.
6265///
6266/// `buf == NULL` writes the required size to `*out_len` and returns
6267/// success. If `buf` is non-null and `buflen` is too small, returns
6268/// `BUFFER_TOO_SMALL` and still writes the need to `*out_len`.
6269/// This function does not call MPI.
6270///
6271/// # Safety
6272/// `frame_handle` valid. `out_len` non-null. `buf` valid for `buflen` if non-null.
6273#[unsafe(no_mangle)]
6274pub unsafe extern "C" fn rkr_pack_rcso(
6275    frame_handle: *const RKRConFrame,
6276    buf: *mut u8,
6277    buflen: usize,
6278    out_len: *mut usize,
6279) -> RKRStatus {
6280    if out_len.is_null() {
6281        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
6282    }
6283    let frame = match unsafe { (frame_handle as *const ConFrame).as_ref() } {
6284        Some(f) => f,
6285        None => return note(RKRStatus::RKR_STATUS_NULL_POINTER),
6286    };
6287    let bytes = match crate::rcso::Rcso::encode_frame(frame) {
6288        Ok(b) => b,
6289        Err(_) => return note(RKRStatus::RKR_STATUS_VALIDATION_ERROR),
6290    };
6291    unsafe { *out_len = bytes.len() };
6292    if buf.is_null() {
6293        return note(RKRStatus::RKR_STATUS_SUCCESS);
6294    }
6295    if buflen < bytes.len() {
6296        return note(RKRStatus::RKR_STATUS_BUFFER_TOO_SMALL);
6297    }
6298    unsafe {
6299        ptr::copy_nonoverlapping(bytes.as_ptr(), buf, bytes.len());
6300    }
6301    note(RKRStatus::RKR_STATUS_SUCCESS)
6302}
6303
6304/// Read `natoms` from an RCSO blob. No MPI.
6305///
6306/// # Safety
6307/// `buf` valid for `buflen`. `out_natoms` non-null.
6308#[unsafe(no_mangle)]
6309pub unsafe extern "C" fn rkr_unpack_rcso_natoms(
6310    buf: *const u8,
6311    buflen: usize,
6312    out_natoms: *mut u32,
6313) -> RKRStatus {
6314    if buf.is_null() || out_natoms.is_null() {
6315        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
6316    }
6317    let bytes = unsafe { std::slice::from_raw_parts(buf, buflen) };
6318    match crate::rcso::Rcso::decode(bytes) {
6319        Ok(s) => {
6320            unsafe { *out_natoms = s.natoms };
6321            note(RKRStatus::RKR_STATUS_SUCCESS)
6322        }
6323        Err(_) => note(RKRStatus::RKR_STATUS_VALIDATION_ERROR),
6324    }
6325}
6326
6327/// Copy RCSO positions into row-major `dest` (`natoms * 3` doubles).
6328///
6329/// # Safety
6330/// `buf` valid for `buflen`. `dest` valid for `dest_natoms * 3` f64.
6331#[unsafe(no_mangle)]
6332pub unsafe extern "C" fn rkr_unpack_rcso_positions(
6333    buf: *const u8,
6334    buflen: usize,
6335    dest: *mut f64,
6336    dest_natoms: u32,
6337) -> RKRStatus {
6338    if buf.is_null() || dest.is_null() {
6339        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
6340    }
6341    let bytes = unsafe { std::slice::from_raw_parts(buf, buflen) };
6342    let soa = match crate::rcso::Rcso::decode(bytes) {
6343        Ok(s) => s,
6344        Err(_) => return note(RKRStatus::RKR_STATUS_VALIDATION_ERROR),
6345    };
6346    if soa.natoms != dest_natoms {
6347        return note(RKRStatus::RKR_STATUS_BUFFER_TOO_SMALL);
6348    }
6349    let out = unsafe { std::slice::from_raw_parts_mut(dest, dest_natoms as usize * 3) };
6350    for (i, p) in soa.positions.iter().enumerate() {
6351        out[i * 3] = p[0];
6352        out[i * 3 + 1] = p[1];
6353        out[i * 3 + 2] = p[2];
6354    }
6355    note(RKRStatus::RKR_STATUS_SUCCESS)
6356}
6357
6358/// Copy RCSO forces into row-major `dest`. `SECTION_ABSENT` if the blob
6359/// has no force block.
6360///
6361/// # Safety
6362/// `buf` valid for `buflen`. `dest` valid for `dest_natoms * 3` f64.
6363#[unsafe(no_mangle)]
6364pub unsafe extern "C" fn rkr_unpack_rcso_forces(
6365    buf: *const u8,
6366    buflen: usize,
6367    dest: *mut f64,
6368    dest_natoms: u32,
6369) -> RKRStatus {
6370    if buf.is_null() || dest.is_null() {
6371        return note(RKRStatus::RKR_STATUS_NULL_POINTER);
6372    }
6373    let bytes = unsafe { std::slice::from_raw_parts(buf, buflen) };
6374    let soa = match crate::rcso::Rcso::decode(bytes) {
6375        Ok(s) => s,
6376        Err(_) => return note(RKRStatus::RKR_STATUS_VALIDATION_ERROR),
6377    };
6378    let Some(forces) = soa.forces else {
6379        return note(RKRStatus::RKR_STATUS_SECTION_ABSENT);
6380    };
6381    if soa.natoms != dest_natoms {
6382        return note(RKRStatus::RKR_STATUS_BUFFER_TOO_SMALL);
6383    }
6384    let out = unsafe { std::slice::from_raw_parts_mut(dest, dest_natoms as usize * 3) };
6385    for (i, f) in forces.iter().enumerate() {
6386        out[i * 3] = f[0];
6387        out[i * 3 + 1] = f[1];
6388        out[i * 3 + 2] = f[2];
6389    }
6390    note(RKRStatus::RKR_STATUS_SUCCESS)
6391}
6392
6393#[cfg(test)]
6394mod tests {
6395    use super::*;
6396    use std::ffi::{CStr, CString};
6397    #[test]
6398    fn frame_copy_positions_without_cframe() {
6399        let handle = test_frame_handle();
6400        let n = unsafe { rkr_frame_atom_count(handle) };
6401        assert_eq!(n, 1);
6402        let mut buf = vec![0.0f64; n * 3];
6403        assert_eq!(
6404            unsafe { rkr_frame_copy_positions(handle, buf.as_mut_ptr(), buf.len()) },
6405            note(RKRStatus::RKR_STATUS_SUCCESS)
6406        );
6407        let mut tensor: *mut RKRDLManagedTensorVersioned = std::ptr::null_mut();
6408        assert_eq!(
6409            unsafe { rkr_frame_positions_dlpack(handle, &mut tensor) },
6410            note(RKRStatus::RKR_STATUS_SUCCESS)
6411        );
6412        assert!(!tensor.is_null());
6413        unsafe { rkr_dlpack_delete(tensor) };
6414        assert_eq!(
6415            unsafe { rkr_frame_copy_velocities(handle, buf.as_mut_ptr(), buf.len()) },
6416            note(RKRStatus::RKR_STATUS_SECTION_ABSENT)
6417        );
6418        unsafe { free_rkr_frame(handle) };
6419    }
6420    #[test]
6421    fn c_read_uses_the_cached_unit_table() {
6422        let text = "\
6423v3
6424{\"con_spec_version\":3,\"con_spec_minor\":1,\"units\":{\"length\":\"angstrom\",\"energy\":\"eV\"}}
642510 10 10
642690 90 90
6427
6428
64291
64301
64311.0
6432H
6433Coordinates of Component 1
64340.5 0.25 0.125 0 7
6435";
6436        let dir = tempfile::tempdir().unwrap();
6437        let path = dir.path().join("v3.con");
6438        std::fs::write(&path, text).unwrap();
6439        let serial = crate::iterators::read_all_frames(&path).unwrap();
6440        let addr = crate::units::cached_unit_table_addr();
6441        let c_path = std::ffi::CString::new(path.to_str().unwrap()).unwrap();
6442        let mut n: usize = 0;
6443        let arr = unsafe { rkr_read_all_frames(c_path.as_ptr(), &mut n) };
6444        assert!(!arr.is_null() && n == 1);
6445        assert_eq!(crate::units::cached_unit_table_addr(), addr);
6446        let nat = unsafe { rkr_frame_atom_count(*arr) };
6447        assert_eq!(nat, serial[0].atom_data.len());
6448        let mut buf = vec![0.0f64; nat * 3];
6449        assert_eq!(
6450            unsafe { rkr_frame_copy_positions(*arr, buf.as_mut_ptr(), buf.len()) },
6451            RKRStatus::RKR_STATUS_SUCCESS
6452        );
6453        assert_eq!(
6454            buf[0].to_bits(),
6455            serial[0].positions.as_f64_row(0)[0].to_bits()
6456        );
6457        unsafe { free_rkr_frame_array(arr, n) };
6458        let bad = dir.path().join("bad.con");
6459        std::fs::write(&bad, text.replace("angstrom", "not-a-unit")).unwrap();
6460        let bad_c = std::ffi::CString::new(bad.to_str().unwrap()).unwrap();
6461        let mut n_bad = 0usize;
6462        assert!(unsafe { rkr_read_all_frames(bad_c.as_ptr(), &mut n_bad) }.is_null());
6463        assert_eq!(crate::units::cached_unit_table_addr(), addr);
6464    }
6465
6466    #[test]
6467    fn read_all_frames_c_abi_tiny() {
6468        let path = std::ffi::CString::new("resources/test/tiny_cuh2.con").unwrap();
6469        let mut n: usize = 0;
6470        let arr = unsafe { rkr_read_all_frames(path.as_ptr(), &mut n) };
6471        assert!(!arr.is_null() && n >= 1);
6472        let first = unsafe { *arr };
6473        let nat = unsafe { rkr_frame_atom_count(first) };
6474        let mut buf = vec![0.0f64; nat * 3];
6475        assert_eq!(
6476            unsafe { rkr_frame_copy_positions(first, buf.as_mut_ptr(), buf.len()) },
6477            note(RKRStatus::RKR_STATUS_SUCCESS)
6478        );
6479        unsafe { free_rkr_frame_array(arr, n) };
6480    }
6481
6482    #[test]
6483    fn read_all_frames_n_threads_matches_auto() {
6484        let path = std::ffi::CString::new("resources/test/tiny_cuh2.con").unwrap();
6485        let mut n_auto: usize = 0;
6486        let mut n_one: usize = 0;
6487        let auto = unsafe { rkr_read_all_frames_n_threads(path.as_ptr(), &mut n_auto, 0) };
6488        let one = unsafe { rkr_read_all_frames_n_threads(path.as_ptr(), &mut n_one, 1) };
6489        assert!(!auto.is_null() && !one.is_null());
6490        assert_eq!(n_auto, n_one);
6491        assert_eq!(n_auto, 1);
6492        let nat_auto = unsafe { rkr_frame_atom_count(*auto) };
6493        let nat_one = unsafe { rkr_frame_atom_count(*one) };
6494        assert_eq!(nat_auto, nat_one);
6495        unsafe { free_rkr_frame_array(auto, n_auto) };
6496        unsafe { free_rkr_frame_array(one, n_one) };
6497    }
6498
6499    #[test]
6500    fn free_rkr_frame_ptr_array_keeps_frames() {
6501        let path = std::ffi::CString::new("resources/test/tiny_cuh2.con").unwrap();
6502        let mut n: usize = 0;
6503        let arr = unsafe { rkr_read_all_frames(path.as_ptr(), &mut n) };
6504        assert!(!arr.is_null() && n >= 1);
6505        let first = unsafe { *arr };
6506        // free only outer array; first frame remains owned
6507        let rest: Vec<*mut RKRConFrame> = (1..n).map(|i| unsafe { *arr.add(i) }).collect();
6508        unsafe { free_rkr_frame_ptr_array(arr, n) };
6509        assert!(unsafe { rkr_frame_atom_count(first) } >= 1);
6510        unsafe { free_rkr_frame(first) };
6511        for h in rest {
6512            if !h.is_null() {
6513                unsafe { free_rkr_frame(h) };
6514            }
6515        }
6516    }
6517    fn test_frame_handle() -> *mut RKRConFrame {
6518        let mut builder = ConFrameBuilder::new([10.0, 10.0, 10.0], [90.0, 90.0, 90.0]);
6519        builder
6520            .prebox_header("Generated by test")
6521            .postbox_header(["0 0".to_string(), "0 0 0".to_string()]);
6522        builder.add_atom("Cu", 0.0, 0.0, 0.0, [false, false, false], 0, 63.546);
6523        Box::into_raw(Box::new(builder.build().unwrap())) as *mut RKRConFrame
6524    }
6525    #[test]
6526    fn header_line_rejects_null_buffer() {
6527        let frame = test_frame_handle();
6528        let status = unsafe { rkr_frame_get_header_line(frame, true, 0, std::ptr::null_mut(), 16) };
6529        unsafe { free_rkr_frame(frame) };
6530        assert_eq!(status, RKRStatus::RKR_STATUS_NULL_POINTER);
6531    }
6532    #[test]
6533    fn header_line_rejects_empty_buffer() {
6534        let frame = test_frame_handle();
6535        let mut buffer = [0 as c_char; 1];
6536        let status = unsafe { rkr_frame_get_header_line(frame, true, 0, buffer.as_mut_ptr(), 0) };
6537        unsafe { free_rkr_frame(frame) };
6538        assert_eq!(status, RKRStatus::RKR_STATUS_BUFFER_TOO_SMALL);
6539    }
6540    #[test]
6541    fn header_line_truncates_and_terminates_buffer() {
6542        let frame = test_frame_handle();
6543        let mut buffer = [0 as c_char; 10];
6544        let status =
6545            unsafe { rkr_frame_get_header_line(frame, true, 0, buffer.as_mut_ptr(), buffer.len()) };
6546        unsafe { free_rkr_frame(frame) };
6547        assert_eq!(status, RKRStatus::RKR_STATUS_SUCCESS);
6548        let copied = unsafe { CStr::from_ptr(buffer.as_ptr()) };
6549        assert_eq!(copied.to_str().unwrap(), "Generated");
6550    }
6551
6552    #[test]
6553    fn pack_rcso_size_query_then_dest() {
6554        let path = std::ffi::CString::new("resources/test/tiny_cuh2_forces.con").unwrap();
6555        let frame = unsafe { rkr_read_nth_frame(path.as_ptr(), 0) };
6556        assert!(!frame.is_null());
6557        let mut need = 0usize;
6558        let st = unsafe { rkr_pack_rcso(frame, std::ptr::null_mut(), 0, &mut need) };
6559        assert_eq!(st, RKRStatus::RKR_STATUS_SUCCESS);
6560        assert!(need >= 24);
6561        let mut buf = vec![0u8; need];
6562        let mut wrote = 0usize;
6563        let st = unsafe { rkr_pack_rcso(frame, buf.as_mut_ptr(), buf.len(), &mut wrote) };
6564        assert_eq!(st, RKRStatus::RKR_STATUS_SUCCESS);
6565        assert_eq!(wrote, need);
6566        assert_eq!(&buf[0..4], b"RCSO");
6567        let mut natoms = 0u32;
6568        let st = unsafe { rkr_unpack_rcso_natoms(buf.as_ptr(), buf.len(), &mut natoms) };
6569        assert_eq!(st, RKRStatus::RKR_STATUS_SUCCESS);
6570        assert_eq!(natoms, unsafe { rkr_frame_atom_count(frame) } as u32);
6571        let mut xyz = vec![0.0f64; natoms as usize * 3];
6572        let st =
6573            unsafe { rkr_unpack_rcso_positions(buf.as_ptr(), buf.len(), xyz.as_mut_ptr(), natoms) };
6574        assert_eq!(st, RKRStatus::RKR_STATUS_SUCCESS);
6575        let mut frc = vec![0.0f64; natoms as usize * 3];
6576        let st =
6577            unsafe { rkr_unpack_rcso_forces(buf.as_ptr(), buf.len(), frc.as_mut_ptr(), natoms) };
6578        assert_eq!(st, RKRStatus::RKR_STATUS_SUCCESS);
6579        unsafe { free_rkr_frame(frame) };
6580    }
6581
6582    fn test_builder_handle() -> *mut RKRConFrameBuilder {
6583        let cell = [10.0, 11.0, 12.0];
6584        let angles = [90.0, 91.0, 92.0];
6585        unsafe {
6586            rkr_frame_new(
6587                cell.as_ptr(),
6588                angles.as_ptr(),
6589                ptr::null(),
6590                ptr::null(),
6591                ptr::null(),
6592                ptr::null(),
6593            )
6594        }
6595    }
6596    fn c_string(s: &str) -> CString {
6597        CString::new(s).unwrap()
6598    }
6599    #[test]
6600    fn builder_set_units_c_abi_stores_the_object() {
6601        let builder = test_builder_handle();
6602        let units = c_string(
6603            r#"{"length":"A","energy":"ev","mass":"amu","time":"(amu*angstrom^2/eV)^0.5"}"#,
6604        );
6605        let status = unsafe { rkr_frame_builder_set_units(builder, units.as_ptr()) };
6606        assert_eq!(status, RKRStatus::RKR_STATUS_SUCCESS);
6607        let symbol = c_string("H");
6608        assert_eq!(
6609            unsafe { rkr_frame_add_atom(builder, symbol.as_ptr(), 0.0, 0.0, 0.0, false, 0, 1.0) },
6610            RKRStatus::RKR_STATUS_SUCCESS
6611        );
6612        let frame = unsafe { rkr_frame_builder_build(builder) };
6613        assert!(!frame.is_null());
6614        let json = unsafe { rkr_frame_metadata_json(frame) };
6615        assert!(!json.is_null());
6616        let text = unsafe { CStr::from_ptr(json) }.to_str().unwrap();
6617        assert!(text.contains(r#""length":"angstrom""#), "{text}");
6618        assert!(text.contains(r#""energy":"eV""#), "{text}");
6619        assert!(
6620            text.contains(r#""time":"(amu*angstrom^2/eV)^0.5""#),
6621            "{text}"
6622        );
6623        unsafe {
6624            rkr_free_string(json);
6625            free_rkr_frame(frame);
6626        }
6627    }
6628    #[test]
6629    fn builder_stamps_con_spec_minor_one_unless_set() {
6630        let builder = test_builder_handle();
6631        let symbol = c_string("H");
6632        assert_eq!(
6633            unsafe { rkr_frame_add_atom(builder, symbol.as_ptr(), 0.0, 0.0, 0.0, false, 0, 1.0) },
6634            RKRStatus::RKR_STATUS_SUCCESS
6635        );
6636        let frame = unsafe { rkr_frame_builder_build(builder) };
6637        let json = unsafe { rkr_frame_metadata_json(frame) };
6638        let text = unsafe { CStr::from_ptr(json) }
6639            .to_str()
6640            .unwrap()
6641            .to_string();
6642        assert!(text.contains(r#""con_spec_minor":1"#), "{text}");
6643        unsafe {
6644            rkr_free_string(json);
6645            free_rkr_frame(frame);
6646        }
6647
6648        let builder = test_builder_handle();
6649        assert_eq!(
6650            unsafe { rkr_frame_builder_set_con_spec_minor(builder, 4) },
6651            RKRStatus::RKR_STATUS_SUCCESS
6652        );
6653        let symbol = c_string("H");
6654        assert_eq!(
6655            unsafe { rkr_frame_add_atom(builder, symbol.as_ptr(), 0.0, 0.0, 0.0, false, 0, 1.0) },
6656            RKRStatus::RKR_STATUS_SUCCESS
6657        );
6658        let frame = unsafe { rkr_frame_builder_build(builder) };
6659        let json = unsafe { rkr_frame_metadata_json(frame) };
6660        let text = unsafe { CStr::from_ptr(json) }
6661            .to_str()
6662            .unwrap()
6663            .to_string();
6664        assert!(text.contains(r#""con_spec_minor":4"#), "{text}");
6665        unsafe {
6666            rkr_free_string(json);
6667            free_rkr_frame(frame);
6668        }
6669    }
6670    unsafe fn assert_single_atom(
6671        frame: *mut RKRConFrame,
6672        fixed: [bool; 3],
6673        velocity: Option<[f64; 3]>,
6674        forces: Option<[f64; 3]>,
6675    ) {
6676        let c_frame = unsafe { rkr_frame_to_c_frame(frame) };
6677        assert!(!c_frame.is_null());
6678        let c_frame_ref = unsafe { &*c_frame };
6679        assert_eq!(c_frame_ref.num_atoms, 1);
6680        assert_eq!(c_frame_ref.has_velocities, velocity.is_some());
6681        assert_eq!(c_frame_ref.has_forces, forces.is_some());
6682        let atom = unsafe { &*c_frame_ref.atoms };
6683        assert_eq!(atom.fixed_x, fixed[0]);
6684        assert_eq!(atom.fixed_y, fixed[1]);
6685        assert_eq!(atom.fixed_z, fixed[2]);
6686        assert_eq!(atom.is_fixed, fixed.iter().any(|&value| value));
6687        assert_eq!(atom.has_velocity, velocity.is_some());
6688        assert_eq!(atom.has_forces, forces.is_some());
6689        if let Some([vx, vy, vz]) = velocity {
6690            assert_eq!([atom.vx, atom.vy, atom.vz], [vx, vy, vz]);
6691        }
6692        if let Some([fx, fy, fz]) = forces {
6693            assert_eq!([atom.fx, atom.fy, atom.fz], [fx, fy, fz]);
6694        }
6695        unsafe { free_c_frame(c_frame) };
6696        unsafe { free_rkr_frame(frame) };
6697    }
6698    #[test]
6699    fn builder_preserves_fixed_mask_for_atom_without_velocity_or_forces() {
6700        let builder = test_builder_handle();
6701        let symbol = c_string("Cu");
6702        let status = unsafe {
6703            rkr_frame_add_atom_with_fixed_mask(
6704                builder,
6705                symbol.as_ptr(),
6706                1.0,
6707                2.0,
6708                3.0,
6709                true,
6710                false,
6711                true,
6712                7,
6713                63.546,
6714            )
6715        };
6716        assert_eq!(status, RKRStatus::RKR_STATUS_SUCCESS);
6717        let frame = unsafe { rkr_frame_builder_build(builder) };
6718        unsafe { assert_single_atom(frame, [true, false, true], None, None) };
6719    }
6720    #[test]
6721    fn builder_preserves_fixed_mask_for_atom_with_velocity() {
6722        let builder = test_builder_handle();
6723        let symbol = c_string("H");
6724        let status = unsafe {
6725            rkr_frame_add_atom_with_velocity_fixed_mask(
6726                builder,
6727                symbol.as_ptr(),
6728                1.0,
6729                2.0,
6730                3.0,
6731                false,
6732                true,
6733                false,
6734                9,
6735                1.008,
6736                0.1,
6737                0.2,
6738                0.3,
6739            )
6740        };
6741        assert_eq!(status, RKRStatus::RKR_STATUS_SUCCESS);
6742        let frame = unsafe { rkr_frame_builder_build(builder) };
6743        unsafe { assert_single_atom(frame, [false, true, false], Some([0.1, 0.2, 0.3]), None) };
6744    }
6745    #[test]
6746    fn builder_preserves_fixed_mask_for_atom_with_forces() {
6747        let builder = test_builder_handle();
6748        let symbol = c_string("O");
6749        let status = unsafe {
6750            rkr_frame_add_atom_with_forces_fixed_mask(
6751                builder,
6752                symbol.as_ptr(),
6753                1.0,
6754                2.0,
6755                3.0,
6756                true,
6757                true,
6758                false,
6759                11,
6760                15.999,
6761                -0.1,
6762                -0.2,
6763                -0.3,
6764            )
6765        };
6766        assert_eq!(status, RKRStatus::RKR_STATUS_SUCCESS);
6767        let frame = unsafe { rkr_frame_builder_build(builder) };
6768        unsafe { assert_single_atom(frame, [true, true, false], None, Some([-0.1, -0.2, -0.3])) };
6769    }
6770    #[test]
6771    fn builder_preserves_fixed_mask_for_atom_with_velocity_and_forces() {
6772        let builder = test_builder_handle();
6773        let symbol = c_string("N");
6774        let status = unsafe {
6775            rkr_frame_add_atom_with_velocity_and_forces_fixed_mask(
6776                builder,
6777                symbol.as_ptr(),
6778                1.0,
6779                2.0,
6780                3.0,
6781                false,
6782                true,
6783                true,
6784                13,
6785                14.007,
6786                0.4,
6787                0.5,
6788                0.6,
6789                -0.4,
6790                -0.5,
6791                -0.6,
6792            )
6793        };
6794        assert_eq!(status, RKRStatus::RKR_STATUS_SUCCESS);
6795        let frame = unsafe { rkr_frame_builder_build(builder) };
6796        unsafe {
6797            assert_single_atom(
6798                frame,
6799                [false, true, true],
6800                Some([0.4, 0.5, 0.6]),
6801                Some([-0.4, -0.5, -0.6]),
6802            )
6803        };
6804    }
6805    #[test]
6806    fn builder_bool_fixed_functions_set_all_axes_together() {
6807        let builder = test_builder_handle();
6808        let cu = c_string("Cu");
6809        let h = c_string("H");
6810        let atom_status =
6811            unsafe { rkr_frame_add_atom(builder, cu.as_ptr(), 1.0, 2.0, 3.0, true, 1, 63.546) };
6812        assert_eq!(atom_status, RKRStatus::RKR_STATUS_SUCCESS);
6813        let velocity_status = unsafe {
6814            rkr_frame_add_atom_with_velocity(
6815                builder,
6816                h.as_ptr(),
6817                4.0,
6818                5.0,
6819                6.0,
6820                false,
6821                2,
6822                1.008,
6823                0.7,
6824                0.8,
6825                0.9,
6826            )
6827        };
6828        assert_eq!(velocity_status, RKRStatus::RKR_STATUS_SUCCESS);
6829        let frame = unsafe { rkr_frame_builder_build(builder) };
6830        let c_frame = unsafe { rkr_frame_to_c_frame(frame) };
6831        assert!(!c_frame.is_null());
6832        let c_frame_ref = unsafe { &*c_frame };
6833        assert_eq!(c_frame_ref.num_atoms, 2);
6834        let atoms = unsafe { std::slice::from_raw_parts(c_frame_ref.atoms, c_frame_ref.num_atoms) };
6835        assert_eq!(
6836            [atoms[0].fixed_x, atoms[0].fixed_y, atoms[0].fixed_z],
6837            [true, true, true]
6838        );
6839        assert_eq!(
6840            [atoms[1].fixed_x, atoms[1].fixed_y, atoms[1].fixed_z],
6841            [false, false, false]
6842        );
6843        unsafe { free_c_frame(c_frame) };
6844        unsafe { free_rkr_frame(frame) };
6845    }
6846    #[test]
6847    fn status_message_returns_static_strings_for_all_status_values() {
6848        let cases = [
6849            (RKRStatus::RKR_STATUS_SUCCESS, "success"),
6850            (RKRStatus::RKR_STATUS_NULL_POINTER, "null pointer"),
6851            (RKRStatus::RKR_STATUS_INVALID_UTF8, "invalid UTF-8"),
6852            (RKRStatus::RKR_STATUS_INVALID_JSON, "invalid JSON"),
6853            (RKRStatus::RKR_STATUS_IO_ERROR, "I/O error"),
6854            (
6855                RKRStatus::RKR_STATUS_INDEX_OUT_OF_BOUNDS,
6856                "index out of bounds",
6857            ),
6858            (RKRStatus::RKR_STATUS_BUFFER_TOO_SMALL, "buffer too small"),
6859            (RKRStatus::RKR_STATUS_INTERNAL_ERROR, "internal error"),
6860            (RKRStatus::RKR_STATUS_SECTION_ABSENT, "section absent"),
6861            (RKRStatus::RKR_STATUS_VALIDATION_ERROR, "validation error"),
6862            (RKRStatus::RKR_STATUS_SELECTION_ERROR, "selection error"),
6863            (
6864                RKRStatus::RKR_STATUS_FEATURE_DISABLED,
6865                "feature disabled in this build",
6866            ),
6867        ];
6868        for (status, expected) in cases {
6869            let message = unsafe { CStr::from_ptr(rkr_status_message(status)) };
6870            assert_eq!(message.to_str().unwrap(), expected);
6871        }
6872    }
6873    // ----- DLPack FFI smoke tests ----------------------------------------------
6874    /// Assert DLPack tensor layout without assuming the host language uses f64
6875    /// buffers — consumers must read `dtype` / `ndim` / `shape` from the tensor.
6876    unsafe fn assert_dlpack_cpu_float(
6877        t: *mut RKRDLManagedTensorVersioned,
6878        expect_ndim: i32,
6879        expect_shape: &[i64],
6880        expect_bits: u8,
6881    ) {
6882        assert!(!t.is_null());
6883        let dl = unsafe { &(*t).dl_tensor };
6884        assert_eq!(dl.ndim, expect_ndim);
6885        let shape = unsafe { std::slice::from_raw_parts(dl.shape, expect_ndim as usize) };
6886        assert_eq!(shape, expect_shape);
6887        assert_eq!(dl.dtype.code, dlpk::sys::DLDataTypeCode::kDLFloat);
6888        assert_eq!(dl.dtype.bits, expect_bits);
6889        assert_eq!(dl.dtype.lanes, 1);
6890        assert_eq!(dl.device, dlpk::sys::DLDevice::cpu());
6891        assert!(!dl.data.is_null());
6892    }
6893
6894    #[test]
6895    fn frame_optional_section_dlpack_present_and_absent() {
6896        // Absent on coordinate-only frame
6897        let handle = test_frame_handle();
6898        let mut t: *mut RKRDLManagedTensorVersioned = std::ptr::null_mut();
6899        assert_eq!(
6900            unsafe { rkr_frame_velocities_dlpack(handle, &mut t) },
6901            note(RKRStatus::RKR_STATUS_SECTION_ABSENT)
6902        );
6903        assert!(t.is_null());
6904        assert_eq!(
6905            unsafe { rkr_frame_forces_dlpack(handle, &mut t) },
6906            note(RKRStatus::RKR_STATUS_SECTION_ABSENT)
6907        );
6908        assert_eq!(
6909            unsafe { rkr_frame_atom_energies_dlpack(handle, &mut t) },
6910            note(RKRStatus::RKR_STATUS_SECTION_ABSENT)
6911        );
6912        unsafe { free_rkr_frame(handle) };
6913
6914        // Present on .convel fixture — (N, 3) float, N from atom_count
6915        let path = CString::new("resources/test/tiny_cuh2.convel").unwrap();
6916        let fr = unsafe { rkr_read_first_frame(path.as_ptr()) };
6917        assert!(!fr.is_null());
6918        let n = unsafe { rkr_frame_atom_count(fr) } as i64;
6919        assert!(n > 0);
6920        let mut vel: *mut RKRDLManagedTensorVersioned = std::ptr::null_mut();
6921        let st = unsafe { rkr_frame_velocities_dlpack(fr, &mut vel) };
6922        assert_eq!(st, RKRStatus::RKR_STATUS_SUCCESS);
6923        unsafe {
6924            assert_dlpack_cpu_float(vel, 2, &[n, 3], 64);
6925            rkr_dlpack_delete(vel);
6926            free_rkr_frame(fr);
6927        }
6928
6929        // Forces (N,3) + energies (N,) via builder → frame
6930        let cell = [10.0f64; 3];
6931        let ang = [90.0f64; 3];
6932        let b = unsafe {
6933            rkr_frame_new(
6934                cell.as_ptr(),
6935                ang.as_ptr(),
6936                std::ptr::null(),
6937                std::ptr::null(),
6938                std::ptr::null(),
6939                std::ptr::null(),
6940            )
6941        };
6942        assert!(!b.is_null());
6943        let sym = CString::new("H").unwrap();
6944        unsafe {
6945            rkr_frame_add_atom_with_velocity_and_forces_fixed_mask(
6946                b,
6947                sym.as_ptr(),
6948                0.0,
6949                0.0,
6950                0.0,
6951                false,
6952                false,
6953                false,
6954                0,
6955                1.0,
6956                0.1,
6957                0.0,
6958                0.0,
6959                0.0,
6960                0.0,
6961                -1.0,
6962            );
6963            rkr_frame_builder_set_last_energy(b, -0.5);
6964        }
6965        let built = unsafe { rkr_frame_builder_build(b) };
6966        assert!(!built.is_null());
6967        let n_built = unsafe { rkr_frame_atom_count(built) } as i64;
6968        let mut frc: *mut RKRDLManagedTensorVersioned = std::ptr::null_mut();
6969        let mut eng: *mut RKRDLManagedTensorVersioned = std::ptr::null_mut();
6970        assert_eq!(
6971            unsafe { rkr_frame_forces_dlpack(built, &mut frc) },
6972            note(RKRStatus::RKR_STATUS_SUCCESS)
6973        );
6974        unsafe { assert_dlpack_cpu_float(frc, 2, &[n_built, 3], 64) };
6975        assert_eq!(
6976            unsafe { rkr_frame_atom_energies_dlpack(built, &mut eng) },
6977            note(RKRStatus::RKR_STATUS_SUCCESS)
6978        );
6979        unsafe { assert_dlpack_cpu_float(eng, 1, &[n_built], 64) };
6980        // Explicit f32 via DLPack-shaped DLDataType (code=kDLFloat=2, bits=32)
6981        let opts32 = RKRDlpackExportOptions {
6982            dtype: RKRDLDataType {
6983                code: rkr_dl_type_code::RKR_DL_FLOAT,
6984                bits: 32,
6985                lanes: 1,
6986            },
6987            device: RKRDLDevice {
6988                device_type: rkr_dl_device_type::RKR_DL_CPU,
6989                device_id: 0,
6990            },
6991        };
6992        let mut pos32: *mut RKRDLManagedTensorVersioned = std::ptr::null_mut();
6993        assert_eq!(
6994            unsafe { rkr_frame_positions_dlpack_ex(built, &opts32, &mut pos32) },
6995            note(RKRStatus::RKR_STATUS_SUCCESS)
6996        );
6997        unsafe {
6998            assert_dlpack_cpu_float(pos32, 2, &[n_built, 3], 32);
6999            rkr_dlpack_delete(pos32);
7000        }
7001        // CUDA device requests: FEATURE_DISABLED without --features cuda;
7002        // with cuda, H2D export succeeds (kDLCUDA).
7003        let cuda_dev = RKRDlpackExportOptions {
7004            dtype: RKRDLDataType {
7005                code: rkr_dl_type_code::RKR_DL_FLOAT,
7006                bits: 64,
7007                lanes: 1,
7008            },
7009            device: RKRDLDevice {
7010                device_type: rkr_dl_device_type::RKR_DL_CUDA,
7011                device_id: 0,
7012            },
7013        };
7014        let mut junk: *mut RKRDLManagedTensorVersioned = std::ptr::null_mut();
7015        #[cfg(not(feature = "cuda"))]
7016        assert_eq!(
7017            unsafe { rkr_frame_positions_dlpack_ex(built, &cuda_dev, &mut junk) },
7018            note(RKRStatus::RKR_STATUS_FEATURE_DISABLED)
7019        );
7020        #[cfg(feature = "cuda")]
7021        {
7022            assert_eq!(
7023                unsafe { rkr_frame_positions_dlpack_ex(built, &cuda_dev, &mut junk) },
7024                note(RKRStatus::RKR_STATUS_SUCCESS)
7025            );
7026            assert!(!junk.is_null());
7027            let dl = unsafe { &(*junk).dl_tensor };
7028            assert_eq!(dl.device.device_type, dlpk::sys::DLDeviceType::kDLCUDA);
7029            assert!(!dl.data.is_null());
7030            unsafe { rkr_dlpack_delete(junk) };
7031            // Also rkr_frame_positions_as_dlpack with CUDA
7032            let mut as_cuda: *mut RKRDLManagedTensorVersioned = std::ptr::null_mut();
7033            assert_eq!(
7034                unsafe {
7035                    rkr_frame_positions_as_dlpack(
7036                        built,
7037                        rkr_dl_device_type::RKR_DL_CUDA,
7038                        0,
7039                        0,
7040                        1,
7041                        0,
7042                        &mut as_cuda,
7043                    )
7044                },
7045                note(RKRStatus::RKR_STATUS_SUCCESS)
7046            );
7047            assert!(!as_cuda.is_null());
7048            unsafe {
7049                assert_eq!(
7050                    (*as_cuda).dl_tensor.device.device_type,
7051                    dlpk::sys::DLDeviceType::kDLCUDA
7052                );
7053                rkr_dlpack_delete(as_cuda);
7054            }
7055        }
7056        // Unsupported dtype bits on CPU
7057        let bad_bits = RKRDlpackExportOptions {
7058            dtype: RKRDLDataType {
7059                code: rkr_dl_type_code::RKR_DL_FLOAT,
7060                bits: 16,
7061                lanes: 1,
7062            },
7063            device: RKRDLDevice {
7064                device_type: rkr_dl_device_type::RKR_DL_CPU,
7065                device_id: 0,
7066            },
7067        };
7068        assert_eq!(
7069            unsafe { rkr_frame_positions_dlpack_ex(built, &bad_bits, &mut junk) },
7070            note(RKRStatus::RKR_STATUS_VALIDATION_ERROR)
7071        );
7072        // Metatensor-style as_dlpack reflects storage (f64 CPU), not a cast target
7073        let mut as_t: *mut RKRDLManagedTensorVersioned = std::ptr::null_mut();
7074        assert_eq!(
7075            unsafe {
7076                rkr_frame_positions_as_dlpack(
7077                    built,
7078                    rkr_dl_device_type::RKR_DL_CPU,
7079                    0,
7080                    0,
7081                    1,
7082                    0,
7083                    &mut as_t,
7084                )
7085            },
7086            note(RKRStatus::RKR_STATUS_SUCCESS)
7087        );
7088        unsafe {
7089            assert_dlpack_cpu_float(as_t, 2, &[n_built, 3], 64);
7090        }
7091        // Mutate frame positions, then ingest tensor and require values restored
7092        {
7093            let fr = unsafe { &mut *(built as *mut ConFrame) };
7094            for a in fr.atom_data.iter_mut() {
7095                a.x = -99.0;
7096                a.y = -99.0;
7097                a.z = -99.0;
7098            }
7099        }
7100        assert_eq!(
7101            unsafe { rkr_frame_positions_from_dlpack(built, as_t) },
7102            note(RKRStatus::RKR_STATUS_SUCCESS)
7103        );
7104        {
7105            let fr = unsafe { &*(built as *const ConFrame) };
7106            assert!((fr.atom_data[0].x - 0.0).abs() < 1e-12);
7107            assert!((fr.atom_data[0].y - 0.0).abs() < 1e-12);
7108            assert!((fr.atom_data[0].z - 0.0).abs() < 1e-12);
7109        }
7110        // Re-export must match ingested coordinates (not zeros / garbage)
7111        let mut again: *mut RKRDLManagedTensorVersioned = std::ptr::null_mut();
7112        assert_eq!(
7113            unsafe {
7114                rkr_frame_positions_as_dlpack(
7115                    built,
7116                    rkr_dl_device_type::RKR_DL_CPU,
7117                    0,
7118                    0,
7119                    1,
7120                    0,
7121                    &mut again,
7122                )
7123            },
7124            note(RKRStatus::RKR_STATUS_SUCCESS)
7125        );
7126        unsafe {
7127            let dl = &(*again).dl_tensor;
7128            let data = std::slice::from_raw_parts(dl.data as *const f64, 3);
7129            assert!((data[0] - 0.0).abs() < 1e-12);
7130            assert!((data[1] - 0.0).abs() < 1e-12);
7131            assert!((data[2] - 0.0).abs() < 1e-12);
7132            rkr_dlpack_delete(again);
7133            rkr_dlpack_delete(as_t);
7134            rkr_dlpack_delete(frc);
7135            rkr_dlpack_delete(eng);
7136            free_rkr_frame(built);
7137        }
7138    }
7139
7140    #[test]
7141    fn ffi_positions_dlpack_round_trip() {
7142        let handle = test_builder_handle();
7143        let sym = c_string("Cu");
7144        unsafe {
7145            rkr_frame_add_atom_full(
7146                handle,
7147                sym.as_ptr(),
7148                1.0,
7149                2.0,
7150                3.0,
7151                false,
7152                false,
7153                false,
7154                7,
7155                63.5,
7156                ptr::null(),
7157                ptr::null(),
7158            )
7159        };
7160        let mut t: *mut RKRDLManagedTensorVersioned = ptr::null_mut();
7161        let status = unsafe { rkr_frame_builder_positions_dlpack(handle, &mut t) };
7162        assert_eq!(status, RKRStatus::RKR_STATUS_SUCCESS);
7163        assert!(!t.is_null());
7164        // Inspect the DLPack tensor: shape (1, 3), dtype kDLFloat / 64, CPU.
7165        let dl = unsafe { &(*t).dl_tensor };
7166        assert_eq!(dl.ndim, 2);
7167        let shape = unsafe { std::slice::from_raw_parts(dl.shape, 2) };
7168        assert_eq!(shape, &[1, 3]);
7169        assert_eq!(dl.dtype.code, dlpk::sys::DLDataTypeCode::kDLFloat);
7170        assert_eq!(dl.dtype.bits, 64);
7171        assert_eq!(dl.dtype.lanes, 1);
7172        assert_eq!(dl.device, dlpk::sys::DLDevice::cpu());
7173        let data = unsafe { std::slice::from_raw_parts(dl.data as *const f64, 3) };
7174        assert_eq!(data, &[1.0, 2.0, 3.0]);
7175        // Invoke the deleter the same way a C consumer would.
7176        let deleter = unsafe { (*t).deleter };
7177        if let Some(del) = deleter {
7178            unsafe { del(t) };
7179        }
7180        unsafe { free_rkr_frame_builder(handle) };
7181    }
7182    #[test]
7183    fn ffi_velocities_dlpack_section_absent() {
7184        let handle = test_builder_handle();
7185        let sym = c_string("Cu");
7186        unsafe {
7187            rkr_frame_add_atom_full(
7188                handle,
7189                sym.as_ptr(),
7190                0.0,
7191                0.0,
7192                0.0,
7193                false,
7194                false,
7195                false,
7196                0,
7197                63.5,
7198                ptr::null(),
7199                ptr::null(),
7200            )
7201        };
7202        let mut t: *mut RKRDLManagedTensorVersioned = ptr::null_mut();
7203        let status = unsafe { rkr_frame_builder_velocities_dlpack(handle, &mut t) };
7204        assert_eq!(status, RKRStatus::RKR_STATUS_SECTION_ABSENT);
7205        assert!(t.is_null());
7206        unsafe { free_rkr_frame_builder(handle) };
7207    }
7208    #[test]
7209    fn ffi_dlpack_null_handle_rejects() {
7210        let mut t: *mut RKRDLManagedTensorVersioned = ptr::null_mut();
7211        let status = unsafe { rkr_frame_builder_positions_dlpack(ptr::null(), &mut t) };
7212        assert_eq!(status, RKRStatus::RKR_STATUS_NULL_POINTER);
7213        assert!(t.is_null());
7214    }
7215    #[cfg(feature = "chemfiles")]
7216    #[test]
7217    fn rkr_frame_select_finds_oxygen() {
7218        use crate::types::ConFrameBuilder;
7219        let mut b = ConFrameBuilder::new([10.0; 3], [90.0; 3]);
7220        b.add_atom("O", 0.0, 0.0, 0.0, [false; 3], 0, 16.0);
7221        b.add_atom("H", 1.0, 0.0, 0.0, [false; 3], 1, 1.0);
7222        let frame = b.build().unwrap();
7223        let frame_ptr = Box::into_raw(Box::new(frame)) as *mut RKRConFrame;
7224        let sel = CString::new("name O").unwrap();
7225        let mut out: *mut RKRSelectionResult = ptr::null_mut();
7226        let st = unsafe { rkr_frame_select(frame_ptr, sel.as_ptr(), &mut out) };
7227        assert_eq!(st, RKRStatus::RKR_STATUS_SUCCESS);
7228        assert!(!out.is_null());
7229        let n = unsafe { rkr_selection_result_match_count(out) };
7230        assert_eq!(n, 1);
7231        let mut atoms = [u64::MAX; 4];
7232        let mut size = 0u32;
7233        let st2 = unsafe { rkr_selection_result_match_at(out, 0, atoms.as_mut_ptr(), &mut size) };
7234        assert_eq!(st2, RKRStatus::RKR_STATUS_SUCCESS);
7235        assert_eq!(size, 1);
7236        assert_eq!(atoms[0], 0);
7237        unsafe {
7238            rkr_selection_result_free(out);
7239            free_rkr_frame(frame_ptr);
7240        }
7241    }
7242    /// C surface: chemfiles selection.cpp chain topology via `rkr_frame_select`.
7243    #[cfg(feature = "chemfiles")]
7244    #[test]
7245    fn rkr_frame_select_cpp_topology_bonds_angles_dihedrals() {
7246        use crate::types::{Bond, ConFrameBuilder};
7247        // H-O-O-H chain (chemfiles testing_frame topology), bonds in atom_data order.
7248        let mut b = ConFrameBuilder::new([10.0; 3], [90.0; 3]);
7249        b.add_atom("H", 0.0, 1.0, 2.0, [false; 3], 0, 1.0);
7250        b.add_atom("O", 1.0, 2.0, 3.0, [false; 3], 1, 16.0);
7251        b.add_atom("O", 2.0, 3.0, 4.0, [false; 3], 2, 16.0);
7252        b.add_atom("H", 3.0, 4.0, 5.0, [false; 3], 3, 1.0);
7253        let mut frame = b.build().unwrap();
7254        let id_to = |id: u64| {
7255            frame
7256                .atom_data
7257                .iter()
7258                .position(|a| a.atom_id == id)
7259                .unwrap() as u32
7260        };
7261        frame.header.set_bonds(&[
7262            Bond::new(id_to(0), id_to(1)),
7263            Bond::new(id_to(1), id_to(2)),
7264            Bond::new(id_to(2), id_to(3)),
7265        ]);
7266        let frame_ptr = Box::into_raw(Box::new(frame)) as *mut RKRConFrame;
7267        let run = |sel: &str| -> (u64, u32) {
7268            let csel = CString::new(sel).unwrap();
7269            let mut out: *mut RKRSelectionResult = ptr::null_mut();
7270            let st = unsafe { rkr_frame_select(frame_ptr, csel.as_ptr(), &mut out) };
7271            assert_eq!(st, RKRStatus::RKR_STATUS_SUCCESS, "select failed: {sel}");
7272            let n = unsafe { rkr_selection_result_match_count(out) };
7273            let ctx = unsafe { rkr_selection_result_context_size(out) };
7274            unsafe { rkr_selection_result_free(out) };
7275            (n, ctx)
7276        };
7277        assert_eq!(run("bonds: all"), (3, 2));
7278        assert_eq!(run("angles: all"), (2, 3));
7279        assert_eq!(run("dihedrals: all"), (1, 4));
7280        assert_eq!(run("bonds: name(#1) O and type(#2) H").0, 2);
7281        assert_eq!(
7282            run("two: type(#1) H and name(#2) O and is_bonded(#1, #2)").0,
7283            run("bonds: type(#1) H and name(#2) O").0
7284        );
7285        unsafe { free_rkr_frame(frame_ptr) };
7286    }
7287    #[cfg(feature = "metatensor")]
7288    fn assert_mts_block_shape(block: *mut metatensor::c_api::mts_block_t, n: usize, props: usize) {
7289        assert!(!block.is_null());
7290        let mut array = unsafe { std::mem::zeroed::<metatensor::c_api::mts_array_t>() };
7291        let status = unsafe { metatensor::c_api::mts_block_data(block, &mut array) };
7292        assert_eq!(status, metatensor::c_api::MTS_SUCCESS);
7293        let shape_fn = array
7294            .shape
7295            .expect("mts_array_t.shape from metatensor C API");
7296        let mut shape_ptr: *const usize = std::ptr::null();
7297        let mut shape_count: usize = 0;
7298        let st_shape = unsafe { shape_fn(array.ptr, &mut shape_ptr, &mut shape_count) };
7299        assert_eq!(st_shape, metatensor::c_api::MTS_SUCCESS);
7300        assert_eq!(shape_count, 2);
7301        let shape = unsafe { std::slice::from_raw_parts(shape_ptr, shape_count) };
7302        assert_eq!(shape[0], n);
7303        assert_eq!(shape[1], props);
7304        let samples = unsafe { metatensor::c_api::mts_block_labels(block, 0) };
7305        let prop_lab = unsafe { metatensor::c_api::mts_block_labels(block, 1) };
7306        assert!(!samples.is_null() && !prop_lab.is_null());
7307    }
7308    #[cfg(feature = "metatensor")]
7309    #[test]
7310    fn metatensor_positions_via_c_abi() {
7311        let handle = test_frame_handle();
7312        let mut out: *mut metatensor::c_api::mts_block_t = std::ptr::null_mut();
7313        let st = unsafe { rkr_frame_metatensor_positions_block(handle, &mut out) };
7314        assert_eq!(st, RKRStatus::RKR_STATUS_SUCCESS);
7315        assert_mts_block_shape(out, 1, 3);
7316        unsafe { rkr_mts_block_free(out) };
7317        for (name, export) in [
7318            (
7319                "velocities",
7320                rkr_frame_metatensor_velocities_block
7321                    as unsafe extern "C" fn(
7322                        *const RKRConFrame,
7323                        *mut *mut metatensor::c_api::mts_block_t,
7324                    ) -> RKRStatus,
7325            ),
7326            (
7327                "forces",
7328                rkr_frame_metatensor_forces_block
7329                    as unsafe extern "C" fn(
7330                        *const RKRConFrame,
7331                        *mut *mut metatensor::c_api::mts_block_t,
7332                    ) -> RKRStatus,
7333            ),
7334            (
7335                "atom_energies",
7336                rkr_frame_metatensor_atom_energies_block
7337                    as unsafe extern "C" fn(
7338                        *const RKRConFrame,
7339                        *mut *mut metatensor::c_api::mts_block_t,
7340                    ) -> RKRStatus,
7341            ),
7342        ] {
7343            let mut o: *mut metatensor::c_api::mts_block_t = std::ptr::null_mut();
7344            let st_abs = unsafe { export(handle, &mut o) };
7345            assert_eq!(
7346                st_abs,
7347                RKRStatus::RKR_STATUS_SECTION_ABSENT,
7348                "{name} must be SECTION_ABSENT on minimal test frame"
7349            );
7350            assert!(o.is_null());
7351        }
7352        unsafe { free_rkr_frame(handle) };
7353    }
7354
7355    #[cfg(feature = "metatensor")]
7356    #[test]
7357    fn metatensor_optional_sections_via_c_abi() {
7358        // Frame with velocities, forces, and per-atom energies — all four block exports
7359        let mut builder = ConFrameBuilder::new([10.0, 10.0, 10.0], [90.0, 90.0, 90.0]);
7360        builder.add_atom("H", 0.0, 0.0, 0.0, [false; 3], 1, 1.0);
7361        builder.add_atom("O", 1.0, 0.0, 0.0, [false; 3], 2, 16.0);
7362        builder.set_atom_velocity(0, [0.1, 0.2, 0.3]).unwrap();
7363        builder.set_atom_velocity(1, [0.0, 0.1, 0.0]).unwrap();
7364        builder.set_atom_force(0, [1.0, 0.0, 0.0]).unwrap();
7365        builder.set_atom_force(1, [0.0, 1.0, 0.0]).unwrap();
7366        builder.set_atom_energy(0, -0.5).unwrap();
7367        builder.set_atom_energy(1, -1.0).unwrap();
7368        let frame = builder.build().unwrap();
7369        let handle = Box::into_raw(Box::new(frame)) as *mut RKRConFrame;
7370        let mut pos: *mut metatensor::c_api::mts_block_t = std::ptr::null_mut();
7371        assert_eq!(
7372            unsafe { rkr_frame_metatensor_positions_block(handle, &mut pos) },
7373            note(RKRStatus::RKR_STATUS_SUCCESS)
7374        );
7375        assert_mts_block_shape(pos, 2, 3);
7376        unsafe { rkr_mts_block_free(pos) };
7377        let mut vel: *mut metatensor::c_api::mts_block_t = std::ptr::null_mut();
7378        assert_eq!(
7379            unsafe { rkr_frame_metatensor_velocities_block(handle, &mut vel) },
7380            note(RKRStatus::RKR_STATUS_SUCCESS)
7381        );
7382        assert_mts_block_shape(vel, 2, 3);
7383        unsafe { rkr_mts_block_free(vel) };
7384        let mut frc: *mut metatensor::c_api::mts_block_t = std::ptr::null_mut();
7385        assert_eq!(
7386            unsafe { rkr_frame_metatensor_forces_block(handle, &mut frc) },
7387            note(RKRStatus::RKR_STATUS_SUCCESS)
7388        );
7389        assert_mts_block_shape(frc, 2, 3);
7390        unsafe { rkr_mts_block_free(frc) };
7391        let mut eng: *mut metatensor::c_api::mts_block_t = std::ptr::null_mut();
7392        assert_eq!(
7393            unsafe { rkr_frame_metatensor_atom_energies_block(handle, &mut eng) },
7394            note(RKRStatus::RKR_STATUS_SUCCESS)
7395        );
7396        assert_mts_block_shape(eng, 2, 1);
7397        unsafe { rkr_mts_block_free(eng) };
7398        unsafe { free_rkr_frame(handle) };
7399    }
7400
7401    #[test]
7402    fn string_iterator_yields_frames_from_buffer() {
7403        let text =
7404            std::fs::read_to_string("resources/test/tiny_cuh2.con").expect("fixture tiny_cuh2.con");
7405        let c_text = CString::new(text.as_str()).unwrap();
7406        let it = unsafe { read_con_string_iterator(c_text.as_ptr()) };
7407        assert!(!it.is_null());
7408        let mut n = 0usize;
7409        loop {
7410            let fr = unsafe { con_frame_iterator_next(it) };
7411            if fr.is_null() {
7412                break;
7413            }
7414            n += 1;
7415            unsafe { free_rkr_frame(fr) };
7416        }
7417        unsafe { free_con_frame_iterator(it) };
7418        assert!(n >= 1, "string iterator should yield >=1 frame");
7419
7420        let bytes = text.as_bytes();
7421        let it2 = unsafe { read_con_buffer_iterator(bytes.as_ptr(), bytes.len()) };
7422        assert!(!it2.is_null());
7423        let fr2 = unsafe { con_frame_iterator_next(it2) };
7424        assert!(!fr2.is_null());
7425        unsafe {
7426            free_rkr_frame(fr2);
7427            free_con_frame_iterator(it2);
7428        }
7429    }
7430
7431    #[test]
7432    fn file_iterator_reads_gzip_when_present() {
7433        use flate2::Compression;
7434        use flate2::write::GzEncoder;
7435        use std::io::Write;
7436        let plain = std::fs::read("resources/test/tiny_cuh2.con").expect("fixture");
7437        let dir = tempfile::tempdir().expect("tempdir");
7438        let gz_path = dir.path().join("tiny_cuh2.con.gz");
7439        {
7440            let f = std::fs::File::create(&gz_path).unwrap();
7441            let mut enc = GzEncoder::new(f, Compression::default());
7442            enc.write_all(&plain).unwrap();
7443            enc.finish().unwrap();
7444        }
7445        let c_path = CString::new(gz_path.to_str().unwrap()).unwrap();
7446        let it = unsafe { read_con_file_iterator(c_path.as_ptr()) };
7447        assert!(
7448            !it.is_null(),
7449            "path iterator must decompress .con.gz transparently"
7450        );
7451        let fr = unsafe { con_frame_iterator_next(it) };
7452        assert!(!fr.is_null());
7453        let n = unsafe { rkr_frame_atom_count(fr) };
7454        assert!(n > 0);
7455        unsafe {
7456            free_rkr_frame(fr);
7457            free_con_frame_iterator(it);
7458        }
7459    }
7460
7461    #[test]
7462    fn mpi_read_failure_keeps_the_file_line_and_frame() {
7463        let located = crate::error::LocatedParseError::new(
7464            crate::error::ParseError::InvalidMetadataJson("{not-json".into()),
7465            14,
7466            1,
7467        );
7468        rkr_clear_error();
7469        record_mpi_failure(&located);
7470        let err = rkr_last_error();
7471        assert!(!err.is_null());
7472        let err = unsafe { &*err };
7473        assert_eq!(err.line, 14);
7474        assert_eq!(err.frame_index, 1);
7475        assert_eq!(err.code, RKRStatus::RKR_STATUS_INVALID_JSON as i32);
7476        let message = unsafe { CStr::from_ptr(err.message) }.to_string_lossy();
7477        assert!(message.contains("InvalidMetadataJson"), "{message}");
7478
7479        let io = std::io::Error::new(std::io::ErrorKind::NotFound, "missing file");
7480        record_mpi_failure(&io);
7481        let err = unsafe { &*rkr_last_error() };
7482        assert_eq!(err.code, RKRStatus::RKR_STATUS_IO_ERROR as i32);
7483        assert_eq!(err.line, 0);
7484        assert_eq!(err.frame_index, 0);
7485        let message = unsafe { CStr::from_ptr(err.message) }.to_string_lossy();
7486        assert!(message.contains("missing file"), "{message}");
7487    }
7488}