Skip to main content

cadkit_capi/
lib.rs

1//! Stable C ABI over the `cadkit` facade.
2//!
3//! The public contract is `include/cadkit.h` (hand-maintained; `tests/header.rs` checks that
4//! every exported symbol is declared there) and the header-only C++17 wrapper
5//! `include/cadkit.hpp`.
6//!
7//! Design rules:
8//!
9//! * Every function returns a [`cadkit_status`]; output goes through out-pointers.
10//! * Every pointer argument is null-checked; no panic crosses the FFI boundary
11//!   (`catch_unwind` turns it into [`cadkit_status::Panic`]).
12//! * The last error message is thread-local and owned by the library.
13//! * Documents are immutable after creation. Live handles are tracked in a registry so that a
14//!   second `cadkit_document_free` or a use after free is reported as
15//!   [`cadkit_status::InvalidHandle`] instead of corrupting memory (best effort: a freed
16//!   address that is reused by a new document is indistinguishable from the new one).
17
18#![allow(non_camel_case_types)]
19
20use std::cell::RefCell;
21use std::collections::{BTreeMap, HashSet};
22use std::ffi::{CStr, CString, c_char};
23use std::panic::{AssertUnwindSafe, catch_unwind};
24use std::sync::{Mutex, MutexGuard, OnceLock};
25
26use cadkit::{Document, DxfVersion, Error, Format, Limits, ReadOptions, SvgOptions};
27
28pub use cadkit;
29
30/// Library version as a NUL-terminated string.
31static VERSION: &CStr =
32    match CStr::from_bytes_with_nul(concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes()) {
33        Ok(v) => v,
34        Err(_) => c"unknown",
35    };
36
37/// Result code of every fallible call. Values are part of the ABI.
38#[repr(C)]
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum cadkit_status {
41    /// Success.
42    Ok = 0,
43    /// A required pointer argument was NULL.
44    NullPointer = 1,
45    /// An argument was out of range or not valid UTF-8.
46    InvalidArgument = 2,
47    /// File could not be read.
48    Io = 3,
49    /// Input ended early.
50    Truncated = 4,
51    /// Input violates the format.
52    InvalidData = 5,
53    /// Valid input using a feature that is not implemented.
54    Unsupported = 6,
55    /// A configured resource limit was exceeded.
56    LimitExceeded = 7,
57    /// Input is not a recognized drawing format.
58    UnknownFormat = 8,
59    /// An internal panic was caught at the boundary (a bug; please report).
60    Panic = 9,
61    /// Unexpected internal failure.
62    Internal = 10,
63    /// The document handle is not (or no longer) a live document.
64    InvalidHandle = 11,
65}
66
67/// Detected file format. Values are part of the ABI.
68#[repr(C)]
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum cadkit_format {
71    /// Not recognized.
72    Unknown = 0,
73    /// DWG.
74    Dwg = 1,
75    /// DXF (ASCII or binary).
76    Dxf = 2,
77    /// DGN V7.
78    DgnV7 = 3,
79    /// DGN V8.
80    DgnV8 = 4,
81    /// CityGML 2.0.
82    CityGml = 5,
83}
84
85/// DXF output version. Values are part of the ABI.
86#[repr(C)]
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub enum cadkit_dxf_version {
89    /// R12 (AC1009).
90    R12 = 0,
91    /// 2000 (AC1015).
92    R2000 = 1,
93    /// 2004 (AC1018).
94    R2004 = 2,
95    /// 2007 (AC1021).
96    R2007 = 3,
97    /// 2010 (AC1024).
98    R2010 = 4,
99    /// 2013 (AC1027).
100    R2013 = 5,
101    /// 2018 (AC1032).
102    R2018 = 6,
103}
104
105/// Read options. Zero in a numeric field selects the library default; `NULL` options select
106/// all defaults. Initialize with [`cadkit_options_init`] to be forward compatible.
107#[repr(C)]
108#[derive(Debug, Clone, Copy)]
109pub struct cadkit_options {
110    /// Largest accepted input in bytes (0 = default).
111    pub max_input_bytes: u64,
112    /// Largest total decompressed size in bytes (0 = default).
113    pub max_decompressed_bytes: u64,
114    /// Most records per document (0 = default).
115    pub max_objects: u64,
116    /// Deepest nesting (0 = default).
117    pub max_depth: u32,
118    /// Longest single string in bytes (0 = default).
119    pub max_string_bytes: u32,
120    /// Most vertices in one entity (0 = default).
121    pub max_vertices: u32,
122    /// Non-zero keeps original record bytes in the model.
123    pub keep_raw: i32,
124    /// Code page label for 8-bit text without a declared one, e.g. `"windows-1254"`; may be NULL.
125    pub fallback_codepage: *const c_char,
126}
127
128/// SVG options. Initialize with [`cadkit_svg_options_init`].
129#[repr(C)]
130#[derive(Debug, Clone, Copy)]
131pub struct cadkit_svg_options {
132    /// Index of the model to render.
133    pub model_index: u32,
134    /// Output width in CSS pixels (> 0).
135    pub width_px: f64,
136    /// Stroke width in CSS pixels (> 0).
137    pub stroke_px: f64,
138    /// CSS background color, or NULL for transparent.
139    pub background: *const c_char,
140    /// Non-zero renders text entities.
141    pub text: i32,
142    /// Non-zero expands block references.
143    pub expand_blocks: i32,
144}
145
146/// Summary of a document (plain data, no ownership).
147#[repr(C)]
148#[derive(Debug, Clone, Copy)]
149pub struct cadkit_info {
150    /// Source format.
151    pub format: cadkit_format,
152    /// Number of models (model space, layouts, DGN models).
153    pub model_count: u64,
154    /// Number of layers / levels.
155    pub layer_count: u64,
156    /// Number of block definitions.
157    pub block_count: u64,
158    /// Number of top-level entities over all models.
159    pub entity_count: u64,
160    /// Number of reader warnings.
161    pub warning_count: u64,
162}
163
164/// Opaque document handle. Create with `cadkit_read_*`, release with [`cadkit_document_free`].
165pub struct cadkit_document {
166    doc: Document,
167}
168
169// ---------------------------------------------------------------------------------------------
170// internal state
171
172thread_local! {
173    static LAST_ERROR: RefCell<CString> = RefCell::new(CString::default());
174}
175
176fn live_handles() -> MutexGuard<'static, HashSet<usize>> {
177    static LIVE: OnceLock<Mutex<HashSet<usize>>> = OnceLock::new();
178    LIVE.get_or_init(|| Mutex::new(HashSet::new()))
179        .lock()
180        .unwrap_or_else(|p| p.into_inner())
181}
182
183fn set_error(message: &str) {
184    let cleaned: Vec<u8> = message.bytes().filter(|b| *b != 0).collect();
185    let c = CString::new(cleaned).unwrap_or_default();
186    LAST_ERROR.with(|e| *e.borrow_mut() = c);
187}
188
189fn clear_error() {
190    LAST_ERROR.with(|e| *e.borrow_mut() = CString::default());
191}
192
193fn fail(status: cadkit_status, message: &str) -> cadkit_status {
194    set_error(message);
195    status
196}
197
198fn map_error(err: &Error) -> cadkit_status {
199    let status = match err {
200        Error::Truncated { .. } => cadkit_status::Truncated,
201        Error::Invalid { .. } => cadkit_status::InvalidData,
202        Error::Unsupported(_) => cadkit_status::Unsupported,
203        Error::LimitExceeded { .. } => cadkit_status::LimitExceeded,
204        Error::UnknownFormat => cadkit_status::UnknownFormat,
205        Error::Io(_) => cadkit_status::Io,
206        _ => cadkit_status::Internal,
207    };
208    fail(status, &err.to_string())
209}
210
211/// Runs `f`, clearing the last error first and converting panics into a status.
212fn guarded(f: impl FnOnce() -> cadkit_status) -> cadkit_status {
213    clear_error();
214    match catch_unwind(AssertUnwindSafe(f)) {
215        Ok(status) => status,
216        Err(_) => fail(
217            cadkit_status::Panic,
218            "internal panic caught at the FFI boundary",
219        ),
220    }
221}
222
223fn into_c_string(s: String) -> CString {
224    // JSON/SVG/DXF output should not contain NUL, but the C side cannot represent it.
225    CString::new(s).unwrap_or_else(|e| {
226        let cleaned: Vec<u8> = e.into_vec().into_iter().filter(|b| *b != 0).collect();
227        CString::new(cleaned).unwrap_or_default()
228    })
229}
230
231/// Reads an optional NUL-terminated UTF-8 string.
232///
233/// # Safety
234/// `p` must be NULL or point to a NUL-terminated string that outlives `'a`.
235unsafe fn opt_str<'a>(p: *const c_char, what: &str) -> Result<Option<&'a str>, cadkit_status> {
236    if p.is_null() {
237        return Ok(None);
238    }
239    // SAFETY: non-null and NUL-terminated per the function contract.
240    let c = unsafe { CStr::from_ptr(p) };
241    match c.to_str() {
242        Ok(s) => Ok(Some(s)),
243        Err(_) => Err(fail(
244            cadkit_status::InvalidArgument,
245            &format!("{what} is not valid UTF-8"),
246        )),
247    }
248}
249
250/// Converts C options to the facade's.
251///
252/// # Safety
253/// `opts` must be NULL or point to a readable `cadkit_options` whose string is valid.
254unsafe fn convert_options(opts: *const cadkit_options) -> Result<ReadOptions, cadkit_status> {
255    let mut out = ReadOptions::default();
256    // SAFETY: NULL is handled by `as_ref`; otherwise readable per the function contract.
257    let Some(o) = (unsafe { opts.as_ref() }) else {
258        return Ok(out);
259    };
260    let d = Limits::default();
261    out.limits = Limits::default()
262        .with_max_input_bytes(if o.max_input_bytes == 0 {
263            d.max_input_bytes
264        } else {
265            o.max_input_bytes
266        })
267        .with_max_decompressed_bytes(if o.max_decompressed_bytes == 0 {
268            d.max_decompressed_bytes
269        } else {
270            o.max_decompressed_bytes
271        })
272        .with_max_objects(if o.max_objects == 0 {
273            d.max_objects
274        } else {
275            o.max_objects
276        })
277        .with_max_depth(if o.max_depth == 0 {
278            d.max_depth
279        } else {
280            o.max_depth
281        })
282        .with_max_string_bytes(if o.max_string_bytes == 0 {
283            d.max_string_bytes
284        } else {
285            o.max_string_bytes
286        })
287        .with_max_vertices(if o.max_vertices == 0 {
288            d.max_vertices
289        } else {
290            o.max_vertices
291        })
292        .with_max_total_vertices(d.max_total_vertices);
293    out.keep_raw = o.keep_raw != 0;
294    // SAFETY: the string pointer is NULL or NUL-terminated per the function contract.
295    out.fallback_codepage =
296        unsafe { opt_str(o.fallback_codepage, "fallback_codepage") }?.map(str::to_owned);
297    Ok(out)
298}
299
300fn to_c_format(f: Option<Format>) -> cadkit_format {
301    match f {
302        Some(Format::Dwg) => cadkit_format::Dwg,
303        Some(Format::Dxf) => cadkit_format::Dxf,
304        Some(Format::DgnV7) => cadkit_format::DgnV7,
305        Some(Format::DgnV8) => cadkit_format::DgnV8,
306        Some(Format::CityGml) => cadkit_format::CityGml,
307        _ => cadkit_format::Unknown,
308    }
309}
310
311/// Boxes `doc`, records the handle as live and stores it in `*out`.
312///
313/// # Safety
314/// `out` must be non-null and writable.
315unsafe fn register(doc: Document, out: *mut *mut cadkit_document) {
316    let ptr = Box::into_raw(Box::new(cadkit_document { doc }));
317    live_handles().insert(ptr as usize);
318    // SAFETY: `out` is non-null and writable per the function contract.
319    unsafe { *out = ptr };
320}
321
322/// Looks up a live document.
323///
324/// # Safety
325/// `doc` must be NULL, a pointer returned by `cadkit_read_*` and not yet freed, or a stale
326/// pointer (which is rejected through the registry without being dereferenced).
327unsafe fn doc_ref<'a>(doc: *const cadkit_document) -> Result<&'a Document, cadkit_status> {
328    if doc.is_null() {
329        return Err(fail(cadkit_status::NullPointer, "document is NULL"));
330    }
331    if !live_handles().contains(&(doc as usize)) {
332        return Err(fail(
333            cadkit_status::InvalidHandle,
334            "document handle is not live (already freed or never created)",
335        ));
336    }
337    // SAFETY: the registry proves `doc` came from `Box::into_raw` and has not been freed.
338    Ok(unsafe { &(*doc).doc })
339}
340
341/// Shared body of the string-returning getters.
342///
343/// # Safety
344/// `doc` must satisfy [`doc_ref`]'s contract; `out` must be NULL or writable.
345unsafe fn string_getter(
346    doc: *const cadkit_document,
347    out: *mut *mut c_char,
348    f: impl FnOnce(&Document) -> Result<String, Error>,
349) -> cadkit_status {
350    if !out.is_null() {
351        // SAFETY: non-null and writable per the function contract.
352        unsafe { *out = std::ptr::null_mut() };
353    }
354    guarded(|| {
355        if out.is_null() {
356            return fail(cadkit_status::NullPointer, "out pointer is NULL");
357        }
358        // SAFETY: handle validity is checked by `doc_ref`.
359        let d = match unsafe { doc_ref(doc) } {
360            Ok(d) => d,
361            Err(s) => return s,
362        };
363        match f(d) {
364            Ok(s) => {
365                // SAFETY: `out` is non-null and writable per the function contract.
366                unsafe { *out = into_c_string(s).into_raw() };
367                cadkit_status::Ok
368            }
369            Err(e) => map_error(&e),
370        }
371    })
372}
373
374// ---------------------------------------------------------------------------------------------
375// public API
376
377/// Returns the library version, e.g. `"0.1.0"`. Static; never NULL; do not free.
378#[unsafe(no_mangle)]
379pub extern "C" fn cadkit_version() -> *const c_char {
380    VERSION.as_ptr()
381}
382
383/// Returns a static description of a `cadkit_status` value. Never NULL; do not free.
384#[unsafe(no_mangle)]
385pub extern "C" fn cadkit_status_string(status: i32) -> *const c_char {
386    // `i32` instead of the enum: an out-of-range value from C would be undefined behavior.
387    let s: &CStr = match status {
388        0 => c"ok",
389        1 => c"null pointer argument",
390        2 => c"invalid argument",
391        3 => c"I/O error",
392        4 => c"truncated input",
393        5 => c"invalid data",
394        6 => c"unsupported feature",
395        7 => c"limit exceeded",
396        8 => c"unrecognized file format",
397        9 => c"internal panic",
398        10 => c"internal error",
399        11 => c"invalid document handle",
400        _ => c"unknown status",
401    };
402    s.as_ptr()
403}
404
405/// Returns the message of the last failed call on this thread, or an empty string.
406///
407/// The pointer is owned by the library and valid until the next cadkit call on the same
408/// thread. Never NULL.
409#[unsafe(no_mangle)]
410pub extern "C" fn cadkit_last_error_message() -> *const c_char {
411    LAST_ERROR.with(|e| e.borrow().as_ptr())
412}
413
414/// Fills `options` with defaults.
415///
416/// # Safety
417/// `options` must be NULL or point to writable memory for one `cadkit_options`.
418#[unsafe(no_mangle)]
419pub unsafe extern "C" fn cadkit_options_init(options: *mut cadkit_options) {
420    // SAFETY: NULL is handled by `as_mut`; otherwise writable per the contract.
421    if let Some(o) = unsafe { options.as_mut() } {
422        *o = cadkit_options {
423            max_input_bytes: 0,
424            max_decompressed_bytes: 0,
425            max_objects: 0,
426            max_depth: 0,
427            max_string_bytes: 0,
428            max_vertices: 0,
429            keep_raw: 0,
430            fallback_codepage: std::ptr::null(),
431        };
432    }
433}
434
435/// Fills `options` with defaults (model 0, 1600 px wide, white background, text and blocks on).
436///
437/// # Safety
438/// `options` must be NULL or point to writable memory for one `cadkit_svg_options`.
439#[unsafe(no_mangle)]
440pub unsafe extern "C" fn cadkit_svg_options_init(options: *mut cadkit_svg_options) {
441    let d = SvgOptions::default();
442    // SAFETY: NULL is handled by `as_mut`; otherwise writable per the contract.
443    if let Some(o) = unsafe { options.as_mut() } {
444        *o = cadkit_svg_options {
445            model_index: 0,
446            width_px: d.width_px,
447            stroke_px: d.stroke_px,
448            background: c"#ffffff".as_ptr(),
449            text: 1,
450            expand_blocks: 1,
451        };
452    }
453}
454
455/// Detects the format from the header. Returns `CADKIT_FORMAT_UNKNOWN` for NULL data.
456///
457/// # Safety
458/// `data` must be NULL or point to `len` readable bytes.
459#[unsafe(no_mangle)]
460pub unsafe extern "C" fn cadkit_detect(data: *const u8, len: usize) -> cadkit_format {
461    if data.is_null() {
462        return cadkit_format::Unknown;
463    }
464    // SAFETY: non-null and `len` readable bytes per the contract.
465    let bytes = unsafe { std::slice::from_raw_parts(data, len) };
466    catch_unwind(|| to_c_format(cadkit::detect(bytes))).unwrap_or(cadkit_format::Unknown)
467}
468
469/// Reads a drawing from a UTF-8 file path. On success `*out` owns a document to free with
470/// [`cadkit_document_free`]; on failure `*out` is NULL.
471///
472/// # Safety
473/// `utf8_path` must be NULL or NUL-terminated; `options` NULL or valid; `out` NULL or writable.
474#[unsafe(no_mangle)]
475pub unsafe extern "C" fn cadkit_read_file(
476    utf8_path: *const c_char,
477    options: *const cadkit_options,
478    out: *mut *mut cadkit_document,
479) -> cadkit_status {
480    if !out.is_null() {
481        // SAFETY: non-null and writable per the contract.
482        unsafe { *out = std::ptr::null_mut() };
483    }
484    guarded(|| {
485        if out.is_null() || utf8_path.is_null() {
486            return fail(cadkit_status::NullPointer, "path or out pointer is NULL");
487        }
488        // SAFETY: `utf8_path` is non-null and NUL-terminated per the contract.
489        let path = match unsafe { opt_str(utf8_path, "path") } {
490            Ok(Some(p)) => p,
491            Ok(None) => return fail(cadkit_status::NullPointer, "path is NULL"),
492            Err(s) => return s,
493        };
494        // SAFETY: `options` is NULL or valid per the contract.
495        let opts = match unsafe { convert_options(options) } {
496            Ok(o) => o,
497            Err(s) => return s,
498        };
499        match cadkit::open_with(path, &opts) {
500            Ok(doc) => {
501                // SAFETY: `out` was checked non-null above and is writable per the contract.
502                unsafe { register(doc, out) };
503                cadkit_status::Ok
504            }
505            Err(e) => map_error(&e),
506        }
507    })
508}
509
510/// Reads a drawing from memory. The buffer is not retained.
511///
512/// # Safety
513/// `data` must point to `len` readable bytes (it may be NULL only when `len` is 0);
514/// `options` NULL or valid; `out` NULL or writable.
515#[unsafe(no_mangle)]
516pub unsafe extern "C" fn cadkit_read_bytes(
517    data: *const u8,
518    len: usize,
519    options: *const cadkit_options,
520    out: *mut *mut cadkit_document,
521) -> cadkit_status {
522    if !out.is_null() {
523        // SAFETY: non-null and writable per the contract.
524        unsafe { *out = std::ptr::null_mut() };
525    }
526    guarded(|| {
527        if out.is_null() {
528            return fail(cadkit_status::NullPointer, "out pointer is NULL");
529        }
530        let bytes: &[u8] = if data.is_null() {
531            if len != 0 {
532                return fail(cadkit_status::NullPointer, "data is NULL but len is not 0");
533            }
534            &[]
535        } else {
536            // SAFETY: non-null and `len` readable bytes per the contract.
537            unsafe { std::slice::from_raw_parts(data, len) }
538        };
539        // SAFETY: `options` is NULL or valid per the contract.
540        let opts = match unsafe { convert_options(options) } {
541            Ok(o) => o,
542            Err(s) => return s,
543        };
544        match cadkit::read_with(bytes, &opts) {
545            Ok(doc) => {
546                // SAFETY: `out` was checked non-null above and is writable per the contract.
547                unsafe { register(doc, out) };
548                cadkit_status::Ok
549            }
550            Err(e) => map_error(&e),
551        }
552    })
553}
554
555/// Releases a document. NULL is a no-op; a handle that is not live returns
556/// `CADKIT_INVALID_HANDLE` and frees nothing. The handle must not be used afterwards.
557///
558/// # Safety
559/// `doc` must be NULL or a handle from `cadkit_read_*`; no other thread may use it concurrently.
560#[unsafe(no_mangle)]
561pub unsafe extern "C" fn cadkit_document_free(doc: *mut cadkit_document) -> cadkit_status {
562    if doc.is_null() {
563        return cadkit_status::Ok;
564    }
565    guarded(|| {
566        if !live_handles().remove(&(doc as usize)) {
567            return fail(
568                cadkit_status::InvalidHandle,
569                "document handle is not live (double free?)",
570            );
571        }
572        // SAFETY: the registry proved `doc` came from `Box::into_raw` and removed it, so this is
573        // the single owner releasing it.
574        drop(unsafe { Box::from_raw(doc) });
575        cadkit_status::Ok
576    })
577}
578
579/// Fills `out` with a summary of `doc`.
580///
581/// # Safety
582/// `doc` must be a live handle; `out` writable.
583#[unsafe(no_mangle)]
584pub unsafe extern "C" fn cadkit_document_info(
585    doc: *const cadkit_document,
586    out: *mut cadkit_info,
587) -> cadkit_status {
588    guarded(|| {
589        if out.is_null() {
590            return fail(cadkit_status::NullPointer, "out pointer is NULL");
591        }
592        // SAFETY: handle validity is checked by `doc_ref`.
593        let d = match unsafe { doc_ref(doc) } {
594            Ok(d) => d,
595            Err(s) => return s,
596        };
597        let info = cadkit_info {
598            format: to_c_format(Some(d.source.format)),
599            model_count: d.models.len() as u64,
600            layer_count: d.layers.len() as u64,
601            block_count: d.blocks.len() as u64,
602            entity_count: d.models.iter().map(|m| m.entities.len() as u64).sum(),
603            warning_count: d.warnings.len() as u64,
604        };
605        // SAFETY: `out` is non-null and writable per the contract.
606        unsafe { *out = info };
607        cadkit_status::Ok
608    })
609}
610
611/// Returns the summary as a JSON object (format, version, application, counts, per-kind entity
612/// counts). `*out` is an owned string; free with [`cadkit_string_free`].
613///
614/// # Safety
615/// `doc` must be a live handle; `out` writable.
616#[unsafe(no_mangle)]
617pub unsafe extern "C" fn cadkit_document_info_json(
618    doc: *const cadkit_document,
619    out: *mut *mut c_char,
620) -> cadkit_status {
621    // SAFETY: forwarded contract.
622    unsafe {
623        string_getter(doc, out, |d| {
624            let mut kinds: BTreeMap<String, u64> = BTreeMap::new();
625            for e in d.models.iter().flat_map(|m| m.entities.iter()) {
626                let name = e.kind.type_name().to_owned();
627                *kinds.entry(name).or_insert(0) += 1;
628            }
629            let v = serde_json::json!({
630                "format": d.source.format,
631                "version": d.source.version,
632                "application": d.source.application,
633                "models": d.models.len(),
634                "layers": d.layers.len(),
635                "blocks": d.blocks.len(),
636                "entities": d.models.iter().map(|m| m.entities.len()).sum::<usize>(),
637                "warnings": d.warnings.len(),
638                "entity_kinds": kinds,
639            });
640            Ok(v.to_string())
641        })
642    }
643}
644
645/// Serializes the document to JSON (UTF-8). `*out` is owned; free with [`cadkit_string_free`].
646///
647/// # Safety
648/// `doc` must be a live handle; `out` writable.
649#[unsafe(no_mangle)]
650pub unsafe extern "C" fn cadkit_document_to_json(
651    doc: *const cadkit_document,
652    pretty: i32,
653    out: *mut *mut c_char,
654) -> cadkit_status {
655    // SAFETY: forwarded contract.
656    unsafe { string_getter(doc, out, |d| cadkit::to_json(d, pretty != 0)) }
657}
658
659/// Converts C SVG options to the facade's, validating them.
660///
661/// # Safety
662/// `options` must be NULL or readable with a valid `background` string.
663unsafe fn convert_svg_options(
664    options: *const cadkit_svg_options,
665) -> Result<SvgOptions, cadkit_status> {
666    // SAFETY: NULL is handled by `as_ref`; otherwise readable per the function contract.
667    let Some(o) = (unsafe { options.as_ref() }) else {
668        return Ok(SvgOptions::default());
669    };
670    // SAFETY: the background pointer is NULL or NUL-terminated per the function contract.
671    let bg = unsafe { opt_str(o.background, "background") }?;
672    if !(o.width_px.is_finite() && o.width_px > 0.0 && o.stroke_px.is_finite() && o.stroke_px > 0.0)
673    {
674        return Err(fail(
675            cadkit_status::InvalidArgument,
676            "width_px and stroke_px must be finite and > 0",
677        ));
678    }
679    Ok({
680        let mut options = SvgOptions::default()
681            .with_model(o.model_index as usize)
682            .with_width_px(o.width_px)
683            .with_stroke_px(o.stroke_px)
684            .with_text(o.text != 0)
685            .with_expand_blocks(o.expand_blocks != 0);
686        options.background = bg.map(str::to_owned);
687        options
688    })
689}
690
691/// Renders one model as SVG. `options` may be NULL for defaults.
692///
693/// # Safety
694/// `doc` must be a live handle; `options` NULL or valid; `out` writable.
695#[unsafe(no_mangle)]
696pub unsafe extern "C" fn cadkit_document_to_svg(
697    doc: *const cadkit_document,
698    options: *const cadkit_svg_options,
699    out: *mut *mut c_char,
700) -> cadkit_status {
701    clear_error();
702    // SAFETY: `options` is NULL or valid per the contract.
703    match unsafe { convert_svg_options(options) } {
704        // SAFETY: forwarded contract.
705        Ok(opts) => unsafe { string_getter(doc, out, |d| Ok(cadkit::to_svg(d, &opts))) },
706        Err(status) => {
707            if !out.is_null() {
708                // SAFETY: non-null and writable per the contract.
709                unsafe { *out = std::ptr::null_mut() };
710            }
711            status
712        }
713    }
714}
715
716/// Writes the document as ASCII DXF of the given `cadkit_dxf_version`.
717///
718/// # Safety
719/// `doc` must be a live handle; `out` writable.
720#[unsafe(no_mangle)]
721pub unsafe extern "C" fn cadkit_document_to_dxf(
722    doc: *const cadkit_document,
723    version: i32,
724    out: *mut *mut c_char,
725) -> cadkit_status {
726    // `i32` instead of the enum: an out-of-range value from C would be undefined behavior.
727    let v = match version {
728        0 => DxfVersion::R12,
729        1 => DxfVersion::R2000,
730        2 => DxfVersion::R2004,
731        3 => DxfVersion::R2007,
732        4 => DxfVersion::R2010,
733        5 => DxfVersion::R2013,
734        6 => DxfVersion::R2018,
735        _ => {
736            if !out.is_null() {
737                // SAFETY: non-null and writable per the contract.
738                unsafe { *out = std::ptr::null_mut() };
739            }
740            return fail(cadkit_status::InvalidArgument, "unknown DXF version");
741        }
742    };
743    // SAFETY: forwarded contract.
744    unsafe { string_getter(doc, out, |d| cadkit::to_dxf(d, v)) }
745}
746
747/// Frees a string returned by a `cadkit_document_*` getter. NULL is a no-op.
748///
749/// # Safety
750/// `s` must be NULL or a string returned by this library that has not been freed yet.
751#[unsafe(no_mangle)]
752pub unsafe extern "C" fn cadkit_string_free(s: *mut c_char) {
753    if s.is_null() {
754        return;
755    }
756    // SAFETY: per the contract `s` came from `CString::into_raw` in this library and is freed once.
757    drop(unsafe { CString::from_raw(s) });
758}
759
760fn live_buffers() -> MutexGuard<'static, std::collections::HashMap<usize, Vec<u8>>> {
761    static BUFFERS: OnceLock<Mutex<std::collections::HashMap<usize, Vec<u8>>>> = OnceLock::new();
762    BUFFERS
763        .get_or_init(|| Mutex::new(std::collections::HashMap::new()))
764        .lock()
765        .unwrap_or_else(|p| p.into_inner())
766}
767
768/// Releases a binary buffer returned by this library; NULL and previously freed pointers are no-ops.
769#[unsafe(no_mangle)]
770pub extern "C" fn cadkit_bytes_free(data: *mut u8) {
771    live_buffers().remove(&(data as usize));
772}
773
774unsafe fn options_json<T: serde::de::DeserializeOwned + Default>(
775    text: *const c_char,
776) -> Result<T, cadkit_status> {
777    // SAFETY: The caller guarantees `text` is NULL or a valid NUL-terminated C string.
778    match unsafe { opt_str(text, "options_json") }? {
779        None => Ok(T::default()),
780        Some(s) => serde_json::from_str(s)
781            .map_err(|e| fail(cadkit_status::InvalidArgument, &e.to_string())),
782    }
783}
784
785fn register_live_buffer(mut bytes: Vec<u8>) -> (*mut u8, usize) {
786    let len = bytes.len();
787    // Ensure a unique heap allocation even for 0-byte buffers so `NonNull::dangling()` never collides.
788    if bytes.capacity() == 0 {
789        bytes.reserve_exact(1);
790    }
791    let ptr = bytes.as_mut_ptr();
792    live_buffers().insert(ptr as usize, bytes);
793    (ptr, len)
794}
795
796unsafe fn binary_getter(
797    doc: *const cadkit_document,
798    out: *mut *mut u8,
799    out_len: *mut usize,
800    f: impl FnOnce(&Document) -> Result<Vec<u8>, Error>,
801) -> cadkit_status {
802    // SAFETY: Non-null out-pointers are writable per the caller's contract.
803    unsafe {
804        if !out.is_null() {
805            *out = std::ptr::null_mut();
806        }
807        if !out_len.is_null() {
808            *out_len = 0;
809        }
810    }
811    guarded(|| {
812        if out.is_null() || out_len.is_null() {
813            return fail(cadkit_status::NullPointer, "binary output pointer is NULL");
814        }
815        // SAFETY: `doc_ref` validates `doc` against the live-handle registry before dereferencing.
816        let d = match unsafe { doc_ref(doc) } {
817            Ok(d) => d,
818            Err(s) => return s,
819        };
820        match f(d) {
821            Ok(bytes) => {
822                let (ptr, len) = register_live_buffer(bytes);
823                // SAFETY: Both `out` and `out_len` were checked non-null above and are writable per the contract.
824                unsafe {
825                    *out = ptr;
826                    *out_len = len;
827                }
828                cadkit_status::Ok
829            }
830            Err(e) => map_error(&e),
831        }
832    })
833}
834
835/// Constructs a format-neutral document from its JSON representation.
836///
837/// # Safety
838/// `json` must be NULL or a valid NUL-terminated C string; `out` must be NULL or writable.
839#[unsafe(no_mangle)]
840pub unsafe extern "C" fn cadkit_document_from_json(
841    json: *const c_char,
842    out: *mut *mut cadkit_document,
843) -> cadkit_status {
844    // SAFETY: Non-null `out` is writable per the caller's contract.
845    unsafe {
846        if !out.is_null() {
847            *out = std::ptr::null_mut();
848        }
849    }
850    guarded(|| {
851        if out.is_null() {
852            return fail(cadkit_status::NullPointer, "out is NULL");
853        }
854        // SAFETY: `json` is NULL or a valid NUL-terminated C string per the caller's contract.
855        let text = match unsafe { opt_str(json, "json") } {
856            Ok(Some(s)) => s,
857            Ok(None) => return fail(cadkit_status::NullPointer, "json is NULL"),
858            Err(s) => return s,
859        };
860        match cadkit::export::document_from_json(text, &cadkit::Limits::default()) {
861            Ok(doc) => {
862                // SAFETY: `out` was verified non-null and writable; `register` records the new live handle.
863                unsafe {
864                    register(doc, out);
865                }
866                cadkit_status::Ok
867            }
868            Err(e) => map_error(&e),
869        }
870    })
871}
872
873/// Writes DGN V8 bytes using `seed`. Release `*out` with [`cadkit_bytes_free`].
874/// `options_json_text` follows the Rust `dgn::WriteOptions` JSON contract; NULL selects defaults.
875///
876/// # Safety
877/// `doc` must be a live handle and must not be freed concurrently; `seed` must be NULL or point to
878/// `seed_len` readable bytes; `options_json_text` must be NULL or a valid NUL-terminated C string;
879/// `out` and `out_len` must be NULL or writable.
880#[unsafe(no_mangle)]
881pub unsafe extern "C" fn cadkit_document_to_dgn(
882    doc: *const cadkit_document,
883    seed: *const u8,
884    seed_len: usize,
885    options_json_text: *const c_char,
886    out: *mut *mut u8,
887    out_len: *mut usize,
888) -> cadkit_status {
889    guarded(|| {
890        // SAFETY: Non-null out-pointers are writable per the caller's contract.
891        unsafe {
892            if !out.is_null() {
893                *out = std::ptr::null_mut();
894            }
895            if !out_len.is_null() {
896                *out_len = 0;
897            }
898        }
899        if seed.is_null() || seed_len > isize::MAX as usize {
900            return fail(cadkit_status::InvalidArgument, "invalid DGN seed buffer");
901        }
902        // SAFETY: `options_json_text` is NULL or a valid NUL-terminated C string per the caller's contract.
903        let options = match unsafe { options_json::<cadkit::dgn::WriteOptions>(options_json_text) }
904        {
905            Ok(o) => o,
906            Err(s) => return s,
907        };
908        // SAFETY: `seed` is non-null, readable for `seed_len` bytes, and `seed_len <= isize::MAX as usize`.
909        let bytes = unsafe { std::slice::from_raw_parts(seed, seed_len) };
910        // SAFETY: Document handle and out-pointer contracts are forwarded to `binary_getter`.
911        unsafe { binary_getter(doc, out, out_len, |d| cadkit::to_dgn(d, bytes, &options)) }
912    })
913}
914
915/// Copies a DGN V8 seed without the drawing content of its model and without the document
916/// properties that name people or organisations (`dgn::strip_seed_v8`). `options_json_text`
917/// follows the Rust `dgn::StripSeedOptions` JSON contract (an unknown field is
918/// `InvalidArgument`) and `options` sets the read limits; NULL selects the defaults of either. On success `*out` / `*out_len` hold the seed (release
919/// with [`cadkit_bytes_free`]) and `*report_json` the `dgn::StripSeedReport` JSON (release with
920/// [`cadkit_string_free`]); on failure all three are NULL / 0. Names in the kept tables remain
921/// and are counted in the report; the result is not anonymous.
922///
923/// # Safety
924/// `seed` must be NULL or point to `seed_len` readable bytes; `options_json_text` must be NULL
925/// or a valid NUL-terminated C string; `options` must be NULL or point to a valid
926/// `cadkit_options`; `out`, `out_len` and `report_json` must be NULL or writable.
927#[unsafe(no_mangle)]
928pub unsafe extern "C" fn cadkit_dgn_strip_seed(
929    seed: *const u8,
930    seed_len: usize,
931    options_json_text: *const c_char,
932    options: *const cadkit_options,
933    out: *mut *mut u8,
934    out_len: *mut usize,
935    report_json: *mut *mut c_char,
936) -> cadkit_status {
937    // SAFETY: Non-null out-pointers are writable per the caller's contract.
938    unsafe {
939        if !out.is_null() {
940            *out = std::ptr::null_mut();
941        }
942        if !out_len.is_null() {
943            *out_len = 0;
944        }
945        if !report_json.is_null() {
946            *report_json = std::ptr::null_mut();
947        }
948    }
949    guarded(|| {
950        if out.is_null() || out_len.is_null() || report_json.is_null() {
951            return fail(cadkit_status::NullPointer, "output pointer is NULL");
952        }
953        if seed.is_null() || seed_len > isize::MAX as usize {
954            return fail(cadkit_status::InvalidArgument, "invalid DGN seed buffer");
955        }
956        // SAFETY: `options_json_text` is NULL or a valid NUL-terminated C string per the caller's contract.
957        let strip =
958            match unsafe { options_json::<cadkit::dgn::StripSeedOptions>(options_json_text) } {
959                Ok(o) => o,
960                Err(s) => return s,
961            };
962        // SAFETY: `options` is NULL or valid per the caller's contract.
963        let read = match unsafe { convert_options(options) } {
964            Ok(o) => o,
965            Err(s) => return s,
966        };
967        // SAFETY: `seed` is non-null, readable for `seed_len` bytes, and `seed_len <= isize::MAX as usize`.
968        let bytes = unsafe { std::slice::from_raw_parts(seed, seed_len) };
969        let stripped = match cadkit::strip_dgn_seed(bytes, &strip, &read) {
970            Ok(s) => s,
971            Err(e) => return map_error(&e),
972        };
973        let report = match serde_json::to_string(&stripped.report) {
974            Ok(r) => r,
975            Err(e) => return fail(cadkit_status::Internal, &e.to_string()),
976        };
977        let (ptr, len) = register_live_buffer(stripped.bytes);
978        // SAFETY: The three out-pointers were checked non-null above and are writable per the contract.
979        unsafe {
980            *out = ptr;
981            *out_len = len;
982            *report_json = into_c_string(report).into_raw();
983        }
984        cadkit_status::Ok
985    })
986}
987
988/// Exports generic geometry as a UTF-8 CityGML 2.0 string; release `*out` with [`cadkit_string_free`].
989///
990/// # Safety
991/// `doc` must be a live handle; `srs_name` must be NULL or a valid NUL-terminated C string;
992/// `out` must be NULL or writable.
993#[unsafe(no_mangle)]
994pub unsafe extern "C" fn cadkit_document_to_citygml(
995    doc: *const cadkit_document,
996    srs_name: *const c_char,
997    lod: u8,
998    out: *mut *mut c_char,
999) -> cadkit_status {
1000    guarded(|| {
1001        // SAFETY: Non-null `out` is writable per the caller's contract.
1002        unsafe {
1003            if !out.is_null() {
1004                *out = std::ptr::null_mut();
1005            }
1006        }
1007        // SAFETY: `srs_name` is NULL or a valid NUL-terminated C string per the caller's contract.
1008        let srs = match unsafe { opt_str(srs_name, "srs_name") } {
1009            Ok(Some(s)) => s.to_owned(),
1010            Ok(None) => return fail(cadkit_status::InvalidArgument, "srs_name is required"),
1011            Err(s) => return s,
1012        };
1013        // SAFETY: Document handle and `out` pointer contracts are forwarded to `string_getter`.
1014        unsafe {
1015            string_getter(doc, out, |d| {
1016                String::from_utf8(cadkit::to_citygml(
1017                    d,
1018                    &cadkit::gml::ExportOptions::new(srs, lod)
1019                        .with_limits(cadkit::Limits::default()),
1020                )?)
1021                .map_err(|e| Error::invalid(0, e.to_string()))
1022            })
1023        }
1024    })
1025}
1026
1027/// Returns JSON containing `xml` and an `ExportReport`. Free it with `cadkit_string_free`.
1028/// `metadata_only` must be 0 (reject unsupported geometry) or 1 (retain it as metadata).
1029/// Coordinates use the supplied CRS without conversion. Metadata is not rendered geometry.
1030///
1031/// # Safety
1032/// `srs_name` must be a valid NUL-terminated UTF-8 string and `out` must be writable.
1033/// `doc` must be a live document handle. The output is NULL on failure.
1034#[unsafe(no_mangle)]
1035pub unsafe extern "C" fn cadkit_document_to_citygml_with_report(
1036    doc: *const cadkit_document,
1037    srs_name: *const c_char,
1038    lod: u8,
1039    metadata_only: i32,
1040    out: *mut *mut c_char,
1041) -> cadkit_status {
1042    // SAFETY: Output is NULL or writable according to the caller's contract.
1043    unsafe {
1044        if !out.is_null() {
1045            *out = std::ptr::null_mut();
1046        }
1047    }
1048    guarded(|| {
1049        let policy = match metadata_only {
1050            0 => cadkit::gml::UnsupportedGeometry::Reject,
1051            1 => cadkit::gml::UnsupportedGeometry::MetadataOnly,
1052            _ => {
1053                return fail(
1054                    cadkit_status::InvalidArgument,
1055                    "metadata_only must be 0 or 1",
1056                );
1057            }
1058        };
1059        // SAFETY: The CRS string is valid according to the caller's contract.
1060        let srs = match unsafe { opt_str(srs_name, "srs_name") } {
1061            Ok(Some(s)) => s.to_owned(),
1062            Ok(None) => return fail(cadkit_status::InvalidArgument, "srs_name is required"),
1063            Err(s) => return s,
1064        };
1065        // SAFETY: string_getter validates the handle and the output address.
1066        unsafe {
1067            string_getter(doc, out, |d| {
1068                let (bytes, report) = cadkit::gml::write_document_with_report(
1069                    d,
1070                    &cadkit::gml::ExportOptions::new(srs, lod)
1071                        .with_limits(cadkit::Limits::default()),
1072                    policy,
1073                )?;
1074                let xml = String::from_utf8(bytes).map_err(|e| Error::invalid(0, e.to_string()))?;
1075                serde_json::to_string(&serde_json::json!({"xml": xml, "report": report}))
1076                    .map_err(|e| Error::invalid(0, e.to_string()))
1077            })
1078        }
1079    })
1080}
1081
1082/// Reads a CityGML 2.0 XML buffer into its native object-graph JSON; release `*out` with [`cadkit_string_free`].
1083///
1084/// # Safety
1085/// `data` must be NULL or point to `len` readable bytes; `options` must be NULL or valid;
1086/// `out` must be NULL or writable.
1087#[unsafe(no_mangle)]
1088pub unsafe extern "C" fn cadkit_citygml_read_json(
1089    data: *const u8,
1090    len: usize,
1091    options: *const cadkit_options,
1092    out: *mut *mut c_char,
1093) -> cadkit_status {
1094    // SAFETY: Non-null `out` is writable per the caller's contract.
1095    unsafe {
1096        if !out.is_null() {
1097            *out = std::ptr::null_mut();
1098        }
1099    }
1100    guarded(|| {
1101        if data.is_null() || out.is_null() || len > isize::MAX as usize {
1102            return fail(
1103                cadkit_status::InvalidArgument,
1104                "invalid CityGML input/output buffer",
1105            );
1106        }
1107        // SAFETY: `options` is NULL or points to a valid `cadkit_options` per the caller's contract.
1108        let opts = match unsafe { convert_options(options) } {
1109            Ok(o) => o,
1110            Err(s) => return s,
1111        };
1112        // SAFETY: `data` is non-null, readable for `len` bytes, and `len <= isize::MAX as usize`.
1113        let bytes = unsafe { std::slice::from_raw_parts(data, len) };
1114        let result = cadkit::gml::read_native(bytes, &opts)
1115            .and_then(|d| serde_json::to_string(&d).map_err(|e| Error::invalid(0, e.to_string())));
1116        match result {
1117            Ok(s) => {
1118                // SAFETY: `out` was verified non-null and writable; CString ownership transfers to the caller.
1119                unsafe {
1120                    *out = into_c_string(s).into_raw();
1121                }
1122                cadkit_status::Ok
1123            }
1124            Err(e) => map_error(&e),
1125        }
1126    })
1127}
1128
1129/// Serializes native CityGML JSON to UTF-8 CityGML 2.0 XML; `validation_options` follows the
1130/// Rust `gml::ValidationOptions` JSON contract (NULL selects defaults). Release `*out` with [`cadkit_string_free`].
1131///
1132/// # Safety
1133/// `json` and `validation_options` must be NULL or valid NUL-terminated C strings;
1134/// `out` must be NULL or writable.
1135#[unsafe(no_mangle)]
1136pub unsafe extern "C" fn cadkit_citygml_write_json(
1137    json: *const c_char,
1138    validation_options: *const c_char,
1139    out: *mut *mut c_char,
1140) -> cadkit_status {
1141    // SAFETY: Non-null `out` is writable per the caller's contract.
1142    unsafe {
1143        if !out.is_null() {
1144            *out = std::ptr::null_mut();
1145        }
1146    }
1147    guarded(|| {
1148        if out.is_null() {
1149            return fail(cadkit_status::NullPointer, "out is NULL");
1150        }
1151        // SAFETY: `json` is NULL or a valid NUL-terminated C string per the caller's contract.
1152        let text = match unsafe { opt_str(json, "json") } {
1153            Ok(Some(s)) => s,
1154            Ok(None) => return fail(cadkit_status::NullPointer, "json is NULL"),
1155            Err(s) => return s,
1156        };
1157        // SAFETY: `validation_options` is NULL or a valid NUL-terminated C string per the caller's contract.
1158        let options =
1159            match unsafe { options_json::<cadkit::gml::ValidationOptions>(validation_options) } {
1160                Ok(o) => o,
1161                Err(s) => return s,
1162            };
1163        let result = cadkit::gml::read_native_json(
1164            text,
1165            &ReadOptions::default().with_limits(options.limits),
1166        )
1167        .and_then(|doc| cadkit::gml::write(&doc, &options))
1168        .and_then(|bytes| String::from_utf8(bytes).map_err(|e| Error::invalid(0, e.to_string())));
1169        match result {
1170            Ok(s) => {
1171                // SAFETY: `out` was verified non-null and writable; CString ownership transfers to the caller.
1172                unsafe {
1173                    *out = into_c_string(s).into_raw();
1174                }
1175                cadkit_status::Ok
1176            }
1177            Err(e) => map_error(&e),
1178        }
1179    })
1180}
1181
1182/// Returns the local TKGM preflight report for native CityGML JSON.
1183/// `profile` is required: `city-model-tender` or `digital-building-registration`.
1184/// This never establishes official acceptance. Free the output with `cadkit_string_free`.
1185///
1186/// # Safety
1187/// `json` and `profile` must be NUL-terminated UTF-8 and `out` must be writable.
1188#[unsafe(no_mangle)]
1189pub unsafe extern "C" fn cadkit_citygml_preflight_tkgm(
1190    json: *const c_char,
1191    profile: *const c_char,
1192    out: *mut *mut c_char,
1193) -> cadkit_status {
1194    // SAFETY: A non-NULL output is writable by contract.
1195    unsafe {
1196        if !out.is_null() {
1197            *out = std::ptr::null_mut();
1198        }
1199    }
1200    guarded(|| {
1201        if out.is_null() {
1202            return fail(cadkit_status::NullPointer, "out is NULL");
1203        }
1204        // SAFETY: The caller provides a valid C string or NULL.
1205        let text = match unsafe { opt_str(json, "json") } {
1206            Ok(Some(s)) => s,
1207            Ok(None) => return fail(cadkit_status::NullPointer, "json is NULL"),
1208            Err(s) => return s,
1209        };
1210        // SAFETY: The caller provides a valid C string or NULL.
1211        let profile = match unsafe { opt_str(profile, "profile") } {
1212            Ok(Some(s)) => match s.parse::<cadkit::gml::tkgm::Profile>() {
1213                Ok(p) => p,
1214                Err(e) => return map_error(&e),
1215            },
1216            Ok(None) => return fail(cadkit_status::NullPointer, "profile is NULL"),
1217            Err(s) => return s,
1218        };
1219        let options = ReadOptions::default();
1220        let result = cadkit::gml::read_native_json(text, &options)
1221            .and_then(|d| cadkit::gml::tkgm::preflight(&d, profile, &options.limits))
1222            .and_then(|report| {
1223                serde_json::to_string(&report).map_err(|e| Error::invalid(0, e.to_string()))
1224            });
1225        match result {
1226            Ok(s) => {
1227                // SAFETY: out was checked; ownership is transferred to the caller.
1228                unsafe {
1229                    *out = into_c_string(s).into_raw();
1230                }
1231                cadkit_status::Ok
1232            }
1233            Err(e) => map_error(&e),
1234        }
1235    })
1236}
1237
1238/// Inspects a file header and returns owned summary JSON; free with `cadkit_string_free`.
1239///
1240/// # Safety
1241/// `path` is NULL or NUL-terminated UTF-8, `options` NULL or valid, `out` NULL or writable.
1242#[unsafe(no_mangle)]
1243pub unsafe extern "C" fn cadkit_inspect_file(
1244    path: *const c_char,
1245    options: *const cadkit_options,
1246    out: *mut *mut c_char,
1247) -> cadkit_status {
1248    // SAFETY: Non-null output is writable per the contract.
1249    if !out.is_null() {
1250        unsafe { *out = std::ptr::null_mut() };
1251    }
1252    guarded(|| {
1253        if out.is_null() {
1254            return fail(cadkit_status::NullPointer, "out pointer is NULL");
1255        }
1256        // SAFETY: The string and options satisfy the caller's contract.
1257        let path = match unsafe { opt_str(path, "path") } {
1258            Ok(Some(p)) => p,
1259            Ok(None) => return fail(cadkit_status::NullPointer, "path is NULL"),
1260            Err(s) => return s,
1261        };
1262        // SAFETY: Options are NULL or valid per the contract.
1263        let opts = match unsafe { convert_options(options) } {
1264            Ok(o) => o,
1265            Err(s) => return s,
1266        };
1267        let summary = match cadkit::inspect_file_with(path, &opts) {
1268            Ok(s) => s,
1269            Err(e) => return map_error(&e),
1270        };
1271        match serde_json::to_string(&summary) {
1272            Ok(s) => {
1273                // SAFETY: Output was checked non-null and is writable.
1274                unsafe { *out = into_c_string(s).into_raw() };
1275                cadkit_status::Ok
1276            }
1277            Err(e) => fail(cadkit_status::Internal, &e.to_string()),
1278        }
1279    })
1280}
1281
1282/// Inspects an in-memory header and returns owned summary JSON; free with `cadkit_string_free`.
1283///
1284/// # Safety
1285/// `data` is NULL only for zero length, otherwise readable for `len` bytes;
1286/// `options` NULL or valid, `out` NULL or writable.
1287#[unsafe(no_mangle)]
1288pub unsafe extern "C" fn cadkit_inspect_bytes(
1289    data: *const u8,
1290    len: usize,
1291    options: *const cadkit_options,
1292    out: *mut *mut c_char,
1293) -> cadkit_status {
1294    // SAFETY: Non-null output is writable per the contract.
1295    if !out.is_null() {
1296        unsafe { *out = std::ptr::null_mut() };
1297    }
1298    guarded(|| {
1299        if out.is_null() || (data.is_null() && len != 0) {
1300            return fail(cadkit_status::NullPointer, "invalid data or output pointer");
1301        }
1302        let bytes = if len == 0 {
1303            &[]
1304        } else {
1305            // SAFETY: Non-null data is readable for len bytes per the contract.
1306            unsafe { std::slice::from_raw_parts(data, len) }
1307        };
1308        // SAFETY: Options are NULL or valid per the contract.
1309        let opts = match unsafe { convert_options(options) } {
1310            Ok(o) => o,
1311            Err(s) => return s,
1312        };
1313        let summary = match cadkit::inspect_with(bytes, &opts) {
1314            Ok(s) => s,
1315            Err(e) => return map_error(&e),
1316        };
1317        match serde_json::to_string(&summary) {
1318            Ok(s) => {
1319                // SAFETY: Output was checked non-null and is writable.
1320                unsafe { *out = into_c_string(s).into_raw() };
1321                cadkit_status::Ok
1322            }
1323            Err(e) => fail(cadkit_status::Internal, &e.to_string()),
1324        }
1325    })
1326}
1327
1328// SAFETY contract: doc satisfies doc_ref and out is NULL or writable.
1329unsafe fn transformed_document(
1330    doc: *const cadkit_document,
1331    out: *mut *mut cadkit_document,
1332    transform: impl FnOnce(&mut Document) -> Result<(), cadkit_status>,
1333) -> cadkit_status {
1334    // SAFETY: Non-null output is writable per the contract.
1335    if !out.is_null() {
1336        unsafe { *out = std::ptr::null_mut() };
1337    }
1338    guarded(|| {
1339        if out.is_null() {
1340            return fail(cadkit_status::NullPointer, "out pointer is NULL");
1341        }
1342        // SAFETY: doc_ref validates the handle before dereferencing.
1343        let source = match unsafe { doc_ref(doc) } {
1344            Ok(d) => d,
1345            Err(s) => return s,
1346        };
1347        let mut copy = source.clone();
1348        if let Err(status) = transform(&mut copy) {
1349            return status;
1350        }
1351        // SAFETY: Output was checked non-null and is writable.
1352        unsafe { register(copy, out) };
1353        cadkit_status::Ok
1354    })
1355}
1356
1357/// Returns a new immutable document with block references expanded up to `max_depth`.
1358/// Missing/cyclic/deeper references remain as inserts, as in Rust `Document::explode_inserts`.
1359///
1360/// # Safety
1361/// `doc` is a live handle, `out` NULL or writable; release the result with `cadkit_document_free`.
1362#[unsafe(no_mangle)]
1363pub unsafe extern "C" fn cadkit_document_explode_inserts(
1364    doc: *const cadkit_document,
1365    max_depth: u32,
1366    out: *mut *mut cadkit_document,
1367) -> cadkit_status {
1368    // SAFETY: Forwarded handle and output contract.
1369    unsafe {
1370        transformed_document(doc, out, |d| {
1371            if d.explode_inserts(max_depth).truncated {
1372                return Err(fail(
1373                    cadkit_status::LimitExceeded,
1374                    "block expansion work limit exceeded",
1375                ));
1376            }
1377            Ok(())
1378        })
1379    }
1380}
1381
1382/// Returns a new immutable document converted to the named length unit (e.g. "mm", "meter").
1383///
1384/// # Safety
1385/// `doc` is a live handle, `unit` NULL or NUL-terminated UTF-8, `out` NULL or writable.
1386#[unsafe(no_mangle)]
1387pub unsafe extern "C" fn cadkit_document_convert_units(
1388    doc: *const cadkit_document,
1389    unit: *const c_char,
1390    out: *mut *mut cadkit_document,
1391) -> cadkit_status {
1392    // SAFETY: Forwarded handle and output contract; unit is valid for this call.
1393    unsafe {
1394        transformed_document(doc, out, |d| {
1395            let name = opt_str(unit, "unit")?
1396                .ok_or_else(|| fail(cadkit_status::NullPointer, "unit is NULL"))?;
1397            let target = cadkit::LengthUnit::from_name(name)
1398                .ok_or_else(|| fail(cadkit_status::InvalidArgument, "unknown length unit"))?;
1399            d.convert_units(target)
1400                .map(|_| ())
1401                .map_err(|e| map_error(&e))
1402        })
1403    }
1404}
1405
1406/// Writes DXF bytes with optional legacy code page; release with `cadkit_bytes_free`.
1407///
1408/// # Safety
1409/// `doc` is a live handle, `codepage` NULL or NUL-terminated UTF-8;
1410/// `out` and `out_len` are NULL or writable.
1411#[unsafe(no_mangle)]
1412pub unsafe extern "C" fn cadkit_document_to_dxf_bytes(
1413    doc: *const cadkit_document,
1414    version: i32,
1415    codepage: *const c_char,
1416    out: *mut *mut u8,
1417    out_len: *mut usize,
1418) -> cadkit_status {
1419    // SAFETY: Each non-null output is writable per the contract.
1420    unsafe {
1421        if !out.is_null() {
1422            *out = std::ptr::null_mut();
1423        }
1424        if !out_len.is_null() {
1425            *out_len = 0;
1426        }
1427    }
1428    guarded(|| {
1429        let version = match version {
1430            0 => DxfVersion::R12,
1431            1 => DxfVersion::R2000,
1432            2 => DxfVersion::R2004,
1433            3 => DxfVersion::R2007,
1434            4 => DxfVersion::R2010,
1435            5 => DxfVersion::R2013,
1436            6 => DxfVersion::R2018,
1437            _ => return fail(cadkit_status::InvalidArgument, "unknown DXF version"),
1438        };
1439        // SAFETY: Optional string is valid for this call.
1440        let codepage = match unsafe { opt_str(codepage, "codepage") } {
1441            Ok(c) => c,
1442            Err(s) => return s,
1443        };
1444        let options =
1445            cadkit::dxf::WriteOptions::new(version).with_codepage(codepage.map(str::to_owned));
1446        // SAFETY: Forwarded handle and binary output contracts.
1447        unsafe { binary_getter(doc, out, out_len, |d| cadkit::to_dxf_bytes(d, &options)) }
1448    })
1449}
1450
1451#[cfg(test)]
1452mod tests {
1453    use super::*;
1454
1455    #[test]
1456    fn empty_buffers_get_distinct_addresses_in_live_buffers() {
1457        let (p1, l1) = register_live_buffer(Vec::new());
1458        let (p2, l2) = register_live_buffer(Vec::new());
1459        assert_eq!((l1, l2), (0, 0));
1460        assert_ne!(p1, p2);
1461        assert!(live_buffers().contains_key(&(p1 as usize)));
1462        assert!(live_buffers().contains_key(&(p2 as usize)));
1463        cadkit_bytes_free(p1);
1464        assert!(!live_buffers().contains_key(&(p1 as usize)));
1465        assert!(live_buffers().contains_key(&(p2 as usize)));
1466        cadkit_bytes_free(p2);
1467        assert!(!live_buffers().contains_key(&(p2 as usize)));
1468    }
1469}