1#![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
30static 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#[repr(C)]
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum cadkit_status {
41 Ok = 0,
43 NullPointer = 1,
45 InvalidArgument = 2,
47 Io = 3,
49 Truncated = 4,
51 InvalidData = 5,
53 Unsupported = 6,
55 LimitExceeded = 7,
57 UnknownFormat = 8,
59 Panic = 9,
61 Internal = 10,
63 InvalidHandle = 11,
65}
66
67#[repr(C)]
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum cadkit_format {
71 Unknown = 0,
73 Dwg = 1,
75 Dxf = 2,
77 DgnV7 = 3,
79 DgnV8 = 4,
81 CityGml = 5,
83}
84
85#[repr(C)]
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub enum cadkit_dxf_version {
89 R12 = 0,
91 R2000 = 1,
93 R2004 = 2,
95 R2007 = 3,
97 R2010 = 4,
99 R2013 = 5,
101 R2018 = 6,
103}
104
105#[repr(C)]
108#[derive(Debug, Clone, Copy)]
109pub struct cadkit_options {
110 pub max_input_bytes: u64,
112 pub max_decompressed_bytes: u64,
114 pub max_objects: u64,
116 pub max_depth: u32,
118 pub max_string_bytes: u32,
120 pub max_vertices: u32,
122 pub keep_raw: i32,
124 pub fallback_codepage: *const c_char,
126}
127
128#[repr(C)]
130#[derive(Debug, Clone, Copy)]
131pub struct cadkit_svg_options {
132 pub model_index: u32,
134 pub width_px: f64,
136 pub stroke_px: f64,
138 pub background: *const c_char,
140 pub text: i32,
142 pub expand_blocks: i32,
144}
145
146#[repr(C)]
148#[derive(Debug, Clone, Copy)]
149pub struct cadkit_info {
150 pub format: cadkit_format,
152 pub model_count: u64,
154 pub layer_count: u64,
156 pub block_count: u64,
158 pub entity_count: u64,
160 pub warning_count: u64,
162}
163
164pub struct cadkit_document {
166 doc: Document,
167}
168
169thread_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
211fn 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 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
231unsafe 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 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
250unsafe fn convert_options(opts: *const cadkit_options) -> Result<ReadOptions, cadkit_status> {
255 let mut out = ReadOptions::default();
256 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 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
311unsafe 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 unsafe { *out = ptr };
320}
321
322unsafe 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 Ok(unsafe { &(*doc).doc })
339}
340
341unsafe 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 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 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 unsafe { *out = into_c_string(s).into_raw() };
367 cadkit_status::Ok
368 }
369 Err(e) => map_error(&e),
370 }
371 })
372}
373
374#[unsafe(no_mangle)]
379pub extern "C" fn cadkit_version() -> *const c_char {
380 VERSION.as_ptr()
381}
382
383#[unsafe(no_mangle)]
385pub extern "C" fn cadkit_status_string(status: i32) -> *const c_char {
386 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#[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#[unsafe(no_mangle)]
419pub unsafe extern "C" fn cadkit_options_init(options: *mut cadkit_options) {
420 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#[unsafe(no_mangle)]
440pub unsafe extern "C" fn cadkit_svg_options_init(options: *mut cadkit_svg_options) {
441 let d = SvgOptions::default();
442 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#[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 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#[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 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 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 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 unsafe { register(doc, out) };
503 cadkit_status::Ok
504 }
505 Err(e) => map_error(&e),
506 }
507 })
508}
509
510#[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 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 unsafe { std::slice::from_raw_parts(data, len) }
538 };
539 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 unsafe { register(doc, out) };
548 cadkit_status::Ok
549 }
550 Err(e) => map_error(&e),
551 }
552 })
553}
554
555#[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 drop(unsafe { Box::from_raw(doc) });
575 cadkit_status::Ok
576 })
577}
578
579#[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 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 unsafe { *out = info };
607 cadkit_status::Ok
608 })
609}
610
611#[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 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#[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 unsafe { string_getter(doc, out, |d| cadkit::to_json(d, pretty != 0)) }
657}
658
659unsafe fn convert_svg_options(
664 options: *const cadkit_svg_options,
665) -> Result<SvgOptions, cadkit_status> {
666 let Some(o) = (unsafe { options.as_ref() }) else {
668 return Ok(SvgOptions::default());
669 };
670 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#[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 match unsafe { convert_svg_options(options) } {
704 Ok(opts) => unsafe { string_getter(doc, out, |d| Ok(cadkit::to_svg(d, &opts))) },
706 Err(status) => {
707 if !out.is_null() {
708 unsafe { *out = std::ptr::null_mut() };
710 }
711 status
712 }
713 }
714}
715
716#[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 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 unsafe { *out = std::ptr::null_mut() };
739 }
740 return fail(cadkit_status::InvalidArgument, "unknown DXF version");
741 }
742 };
743 unsafe { string_getter(doc, out, |d| cadkit::to_dxf(d, v)) }
745}
746
747#[unsafe(no_mangle)]
752pub unsafe extern "C" fn cadkit_string_free(s: *mut c_char) {
753 if s.is_null() {
754 return;
755 }
756 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#[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 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 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 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 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 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#[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 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 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 unsafe {
864 register(doc, out);
865 }
866 cadkit_status::Ok
867 }
868 Err(e) => map_error(&e),
869 }
870 })
871}
872
873#[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 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 let options = match unsafe { options_json::<cadkit::dgn::WriteOptions>(options_json_text) }
904 {
905 Ok(o) => o,
906 Err(s) => return s,
907 };
908 let bytes = unsafe { std::slice::from_raw_parts(seed, seed_len) };
910 unsafe { binary_getter(doc, out, out_len, |d| cadkit::to_dgn(d, bytes, &options)) }
912 })
913}
914
915#[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 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 let strip =
958 match unsafe { options_json::<cadkit::dgn::StripSeedOptions>(options_json_text) } {
959 Ok(o) => o,
960 Err(s) => return s,
961 };
962 let read = match unsafe { convert_options(options) } {
964 Ok(o) => o,
965 Err(s) => return s,
966 };
967 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 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#[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 unsafe {
1003 if !out.is_null() {
1004 *out = std::ptr::null_mut();
1005 }
1006 }
1007 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 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#[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 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 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 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#[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 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 let opts = match unsafe { convert_options(options) } {
1109 Ok(o) => o,
1110 Err(s) => return s,
1111 };
1112 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 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#[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 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 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 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 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#[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 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 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 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 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#[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 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 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 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 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#[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 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 unsafe { std::slice::from_raw_parts(data, len) }
1307 };
1308 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 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
1328unsafe 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 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 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 unsafe { register(copy, out) };
1353 cadkit_status::Ok
1354 })
1355}
1356
1357#[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 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#[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 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#[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 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 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 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}