undoc 0.1.20

High-performance Microsoft Office document extraction to Markdown
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
//! C-ABI Foreign Function Interface for undoc.
//!
//! This module provides C-compatible bindings for using undoc from other languages
//! such as C, C++, C#, Python, and any language with C FFI support.
//!
//! # Memory Management
//!
//! All strings returned by this library must be freed using `undoc_free_string`.
//! All document handles must be freed using `undoc_free_document`.
//!
//! # Error Handling
//!
//! Functions that can fail return a null pointer on error. Use `undoc_last_error`
//! to retrieve the error message.
//!
//! # Example (C)
//!
//! ```c
//! #include <stdio.h>
//! #include "undoc.h"
//!
//! int main() {
//!     UndocDocument* doc = undoc_parse_file("document.docx");
//!     if (!doc) {
//!         const char* error = undoc_last_error();
//!         fprintf(stderr, "Error: %s\n", error);
//!         return 1;
//!     }
//!
//!     char* markdown = undoc_to_markdown(doc, 0);
//!     if (markdown) {
//!         printf("%s\n", markdown);
//!         undoc_free_string(markdown);
//!     }
//!
//!     undoc_free_document(doc);
//!     return 0;
//! }
//! ```
//!
//! # Example (C#)
//!
//! ```csharp
//! using System;
//! using System.Runtime.InteropServices;
//!
//! public class Undoc {
//!     [DllImport("undoc")]
//!     public static extern IntPtr undoc_parse_file(string path);
//!
//!     [DllImport("undoc")]
//!     public static extern IntPtr undoc_to_markdown(IntPtr doc, int flags);
//!
//!     [DllImport("undoc")]
//!     public static extern void undoc_free_string(IntPtr str);
//!
//!     [DllImport("undoc")]
//!     public static extern void undoc_free_document(IntPtr doc);
//! }
//! ```

use std::cell::RefCell;
use std::ffi::{c_char, c_int, CStr, CString};
use std::panic::catch_unwind;
use std::ptr;

use crate::model::Document;
use crate::render::{JsonFormat, RenderOptions};

// Thread-local storage for the last error message.
thread_local! {
    static LAST_ERROR: RefCell<Option<CString>> = const { RefCell::new(None) };
}

/// Set the last error message.
fn set_last_error(msg: &str) {
    LAST_ERROR.with(|e| {
        *e.borrow_mut() = CString::new(msg).ok();
    });
}

/// Clear the last error message.
fn clear_last_error() {
    LAST_ERROR.with(|e| {
        *e.borrow_mut() = None;
    });
}

/// Opaque handle to a parsed document.
#[repr(C)]
pub struct UndocDocument {
    inner: Document,
}

/// Flags for markdown rendering.
pub const UNDOC_FLAG_FRONTMATTER: u32 = 1;
pub const UNDOC_FLAG_ESCAPE_SPECIAL: u32 = 2;
pub const UNDOC_FLAG_PARAGRAPH_SPACING: u32 = 4;

/// JSON format options.
pub const UNDOC_JSON_PRETTY: c_int = 0;
pub const UNDOC_JSON_COMPACT: c_int = 1;

/// Get the version of the library.
///
/// # Safety
///
/// Returns a static string that must not be freed.
#[no_mangle]
pub extern "C" fn undoc_version() -> *const c_char {
    concat!(env!("CARGO_PKG_VERSION"), "\0").as_ptr() as *const c_char
}

/// Get the last error message.
///
/// # Safety
///
/// Returns a pointer to a thread-local error string. The pointer is valid until
/// the next call to any undoc function on the same thread.
#[no_mangle]
pub extern "C" fn undoc_last_error() -> *const c_char {
    LAST_ERROR.with(|e| {
        e.borrow()
            .as_ref()
            .map(|s| s.as_ptr())
            .unwrap_or(ptr::null())
    })
}

/// Parse a document from a file path.
///
/// # Safety
///
/// - `path` must be a valid null-terminated UTF-8 string.
/// - Returns null on error. Use `undoc_last_error` to get the error message.
/// - The returned handle must be freed with `undoc_free_document`.
#[no_mangle]
pub unsafe extern "C" fn undoc_parse_file(path: *const c_char) -> *mut UndocDocument {
    clear_last_error();

    if path.is_null() {
        set_last_error("path is null");
        return ptr::null_mut();
    }

    let result = catch_unwind(|| {
        let path_str = CStr::from_ptr(path).to_str().map_err(|e| e.to_string())?;

        crate::parse_file(path_str)
            .map(|doc| Box::into_raw(Box::new(UndocDocument { inner: doc })))
            .map_err(|e| e.to_string())
    });

    match result {
        Ok(Ok(doc)) => doc,
        Ok(Err(e)) => {
            set_last_error(&e);
            ptr::null_mut()
        }
        Err(_) => {
            set_last_error("panic occurred during parsing");
            ptr::null_mut()
        }
    }
}

/// Parse a document from a byte buffer.
///
/// # Safety
///
/// - `data` must be a valid pointer to a byte buffer of at least `len` bytes.
/// - Returns null on error. Use `undoc_last_error` to get the error message.
/// - The returned handle must be freed with `undoc_free_document`.
#[no_mangle]
pub unsafe extern "C" fn undoc_parse_bytes(data: *const u8, len: usize) -> *mut UndocDocument {
    clear_last_error();

    if data.is_null() {
        set_last_error("data is null");
        return ptr::null_mut();
    }

    let result = catch_unwind(|| {
        let bytes = std::slice::from_raw_parts(data, len);

        crate::parse_bytes(bytes)
            .map(|doc| Box::into_raw(Box::new(UndocDocument { inner: doc })))
            .map_err(|e| e.to_string())
    });

    match result {
        Ok(Ok(doc)) => doc,
        Ok(Err(e)) => {
            set_last_error(&e);
            ptr::null_mut()
        }
        Err(_) => {
            set_last_error("panic occurred during parsing");
            ptr::null_mut()
        }
    }
}

/// Free a document handle.
///
/// # Safety
///
/// - `doc` must be a valid pointer returned by `undoc_parse_file` or `undoc_parse_bytes`.
/// - After calling this function, the handle is invalid and must not be used.
#[no_mangle]
pub unsafe extern "C" fn undoc_free_document(doc: *mut UndocDocument) {
    if !doc.is_null() {
        let _ = Box::from_raw(doc);
    }
}

/// Convert a document to Markdown.
///
/// # Safety
///
/// - `doc` must be a valid document handle.
/// - `flags` is a bitwise OR of `UNDOC_FLAG_*` constants.
/// - Returns null on error. Use `undoc_last_error` to get the error message.
/// - The returned string must be freed with `undoc_free_string`.
#[no_mangle]
pub unsafe extern "C" fn undoc_to_markdown(doc: *const UndocDocument, flags: u32) -> *mut c_char {
    clear_last_error();

    if doc.is_null() {
        set_last_error("document is null");
        return ptr::null_mut();
    }

    let result = catch_unwind(|| {
        let document = &(*doc).inner;

        let mut options = RenderOptions::new();

        if flags & UNDOC_FLAG_FRONTMATTER != 0 {
            options.include_frontmatter = true;
        }
        if flags & UNDOC_FLAG_ESCAPE_SPECIAL != 0 {
            options.escape_special_chars = true;
        }
        if flags & UNDOC_FLAG_PARAGRAPH_SPACING != 0 {
            options.paragraph_spacing = true;
        }

        crate::render::to_markdown(document, &options).map_err(|e| e.to_string())
    });

    match result {
        Ok(Ok(md)) => match CString::new(md) {
            Ok(s) => s.into_raw(),
            Err(_) => {
                set_last_error("output contains null byte");
                ptr::null_mut()
            }
        },
        Ok(Err(e)) => {
            set_last_error(&e);
            ptr::null_mut()
        }
        Err(_) => {
            set_last_error("panic occurred during rendering");
            ptr::null_mut()
        }
    }
}

/// Convert a document to plain text.
///
/// # Safety
///
/// - `doc` must be a valid document handle.
/// - Returns null on error. Use `undoc_last_error` to get the error message.
/// - The returned string must be freed with `undoc_free_string`.
#[no_mangle]
pub unsafe extern "C" fn undoc_to_text(doc: *const UndocDocument) -> *mut c_char {
    clear_last_error();

    if doc.is_null() {
        set_last_error("document is null");
        return ptr::null_mut();
    }

    let result = catch_unwind(|| {
        let document = &(*doc).inner;
        let options = RenderOptions::default();
        crate::render::to_text(document, &options).map_err(|e| e.to_string())
    });

    match result {
        Ok(Ok(text)) => match CString::new(text) {
            Ok(s) => s.into_raw(),
            Err(_) => {
                set_last_error("output contains null byte");
                ptr::null_mut()
            }
        },
        Ok(Err(e)) => {
            set_last_error(&e);
            ptr::null_mut()
        }
        Err(_) => {
            set_last_error("panic occurred during rendering");
            ptr::null_mut()
        }
    }
}

/// Convert a document to JSON.
///
/// # Safety
///
/// - `doc` must be a valid document handle.
/// - `format` is one of `UNDOC_JSON_PRETTY` or `UNDOC_JSON_COMPACT`.
/// - Returns null on error. Use `undoc_last_error` to get the error message.
/// - The returned string must be freed with `undoc_free_string`.
#[no_mangle]
pub unsafe extern "C" fn undoc_to_json(doc: *const UndocDocument, format: c_int) -> *mut c_char {
    clear_last_error();

    if doc.is_null() {
        set_last_error("document is null");
        return ptr::null_mut();
    }

    let result = catch_unwind(|| {
        let document = &(*doc).inner;
        let json_format = if format == UNDOC_JSON_COMPACT {
            JsonFormat::Compact
        } else {
            JsonFormat::Pretty
        };
        crate::render::to_json(document, json_format).map_err(|e| e.to_string())
    });

    match result {
        Ok(Ok(json)) => match CString::new(json) {
            Ok(s) => s.into_raw(),
            Err(_) => {
                set_last_error("output contains null byte");
                ptr::null_mut()
            }
        },
        Ok(Err(e)) => {
            set_last_error(&e);
            ptr::null_mut()
        }
        Err(_) => {
            set_last_error("panic occurred during rendering");
            ptr::null_mut()
        }
    }
}

/// Get the plain text content of a document.
///
/// # Safety
///
/// - `doc` must be a valid document handle.
/// - Returns null on error.
/// - The returned string must be freed with `undoc_free_string`.
#[no_mangle]
pub unsafe extern "C" fn undoc_plain_text(doc: *const UndocDocument) -> *mut c_char {
    clear_last_error();

    if doc.is_null() {
        set_last_error("document is null");
        return ptr::null_mut();
    }

    let result = catch_unwind(|| {
        let document = &(*doc).inner;
        document.plain_text()
    });

    match result {
        Ok(text) => match CString::new(text) {
            Ok(s) => s.into_raw(),
            Err(_) => {
                set_last_error("output contains null byte");
                ptr::null_mut()
            }
        },
        Err(_) => {
            set_last_error("panic occurred");
            ptr::null_mut()
        }
    }
}

/// Get the number of sections in a document.
///
/// # Safety
///
/// - `doc` must be a valid document handle.
/// - Returns -1 on error.
#[no_mangle]
pub unsafe extern "C" fn undoc_section_count(doc: *const UndocDocument) -> c_int {
    if doc.is_null() {
        set_last_error("document is null");
        return -1;
    }

    match catch_unwind(|| (*doc).inner.sections.len() as c_int) {
        Ok(count) => count,
        Err(_) => {
            set_last_error("panic occurred");
            -1
        }
    }
}

/// Get the number of resources in a document.
///
/// # Safety
///
/// - `doc` must be a valid document handle.
/// - Returns -1 on error.
#[no_mangle]
pub unsafe extern "C" fn undoc_resource_count(doc: *const UndocDocument) -> c_int {
    if doc.is_null() {
        set_last_error("document is null");
        return -1;
    }

    match catch_unwind(|| (*doc).inner.resources.len() as c_int) {
        Ok(count) => count,
        Err(_) => {
            set_last_error("panic occurred");
            -1
        }
    }
}

/// Get the document title.
///
/// # Safety
///
/// - `doc` must be a valid document handle.
/// - Returns null if no title is set.
/// - The returned string must be freed with `undoc_free_string`.
#[no_mangle]
pub unsafe extern "C" fn undoc_get_title(doc: *const UndocDocument) -> *mut c_char {
    clear_last_error();

    if doc.is_null() {
        set_last_error("document is null");
        return ptr::null_mut();
    }

    let result = catch_unwind(|| {
        (*doc)
            .inner
            .metadata
            .title
            .as_ref()
            .and_then(|t| CString::new(t.as_str()).ok())
    });

    match result {
        Ok(Some(s)) => s.into_raw(),
        Ok(None) => ptr::null_mut(),
        Err(_) => {
            set_last_error("panic occurred");
            ptr::null_mut()
        }
    }
}

/// Get the document author.
///
/// # Safety
///
/// - `doc` must be a valid document handle.
/// - Returns null if no author is set.
/// - The returned string must be freed with `undoc_free_string`.
#[no_mangle]
pub unsafe extern "C" fn undoc_get_author(doc: *const UndocDocument) -> *mut c_char {
    clear_last_error();

    if doc.is_null() {
        set_last_error("document is null");
        return ptr::null_mut();
    }

    let result = catch_unwind(|| {
        (*doc)
            .inner
            .metadata
            .author
            .as_ref()
            .and_then(|a| CString::new(a.as_str()).ok())
    });

    match result {
        Ok(Some(s)) => s.into_raw(),
        Ok(None) => ptr::null_mut(),
        Err(_) => {
            set_last_error("panic occurred");
            ptr::null_mut()
        }
    }
}

/// Free a string allocated by this library.
///
/// # Safety
///
/// - `s` must be a pointer returned by an undoc function, or null.
/// - After calling this function, the pointer is invalid and must not be used.
#[no_mangle]
pub unsafe extern "C" fn undoc_free_string(s: *mut c_char) {
    if !s.is_null() {
        let _ = CString::from_raw(s);
    }
}

/// Get all resource IDs as a JSON array.
///
/// # Safety
///
/// - `doc` must be a valid document handle.
/// - Returns null on error. Use `undoc_last_error` to get the error message.
/// - The returned string must be freed with `undoc_free_string`.
///
/// # Returns
///
/// A JSON array of resource IDs, e.g., `["rId1", "rId2", "rId3"]`
#[no_mangle]
pub unsafe extern "C" fn undoc_get_resource_ids(doc: *const UndocDocument) -> *mut c_char {
    clear_last_error();

    if doc.is_null() {
        set_last_error("document is null");
        return ptr::null_mut();
    }

    let result = catch_unwind(|| {
        let document = &(*doc).inner;
        let ids: Vec<&String> = document.resources.keys().collect();
        serde_json::to_string(&ids).map_err(|e| e.to_string())
    });

    match result {
        Ok(Ok(json)) => match CString::new(json) {
            Ok(s) => s.into_raw(),
            Err(_) => {
                set_last_error("output contains null byte");
                ptr::null_mut()
            }
        },
        Ok(Err(e)) => {
            set_last_error(&e);
            ptr::null_mut()
        }
        Err(_) => {
            set_last_error("panic occurred");
            ptr::null_mut()
        }
    }
}

/// Get resource metadata as JSON (without binary data).
///
/// # Safety
///
/// - `doc` must be a valid document handle.
/// - `resource_id` must be a valid null-terminated UTF-8 string.
/// - Returns null if resource not found or on error.
/// - The returned string must be freed with `undoc_free_string`.
///
/// # Returns
///
/// JSON object with resource metadata:
/// `{"id":"rId1","type":"image","filename":"image1.png","mime_type":"image/png","size":1024,"width":800,"height":600,"alt_text":"Description"}`
#[no_mangle]
pub unsafe extern "C" fn undoc_get_resource_info(
    doc: *const UndocDocument,
    resource_id: *const c_char,
) -> *mut c_char {
    clear_last_error();

    if doc.is_null() {
        set_last_error("document is null");
        return ptr::null_mut();
    }

    if resource_id.is_null() {
        set_last_error("resource_id is null");
        return ptr::null_mut();
    }

    let result = catch_unwind(|| {
        let id_str = CStr::from_ptr(resource_id)
            .to_str()
            .map_err(|e| e.to_string())?;

        let document = &(*doc).inner;

        match document.resources.get(id_str) {
            Some(resource) => {
                let info = serde_json::json!({
                    "id": id_str,
                    "type": resource.resource_type,
                    "filename": resource.filename,
                    "mime_type": resource.mime_type,
                    "size": resource.size,
                    "width": resource.width,
                    "height": resource.height,
                    "alt_text": resource.alt_text
                });
                serde_json::to_string(&info).map_err(|e| e.to_string())
            }
            None => Err(format!("resource not found: {}", id_str)),
        }
    });

    match result {
        Ok(Ok(json)) => match CString::new(json) {
            Ok(s) => s.into_raw(),
            Err(_) => {
                set_last_error("output contains null byte");
                ptr::null_mut()
            }
        },
        Ok(Err(e)) => {
            set_last_error(&e);
            ptr::null_mut()
        }
        Err(_) => {
            set_last_error("panic occurred");
            ptr::null_mut()
        }
    }
}

/// Get resource binary data.
///
/// # Safety
///
/// - `doc` must be a valid document handle.
/// - `resource_id` must be a valid null-terminated UTF-8 string.
/// - `out_len` must be a valid pointer to receive the data length.
/// - Returns null if resource not found or on error.
/// - The returned pointer must be freed with `undoc_free_bytes`.
#[no_mangle]
pub unsafe extern "C" fn undoc_get_resource_data(
    doc: *const UndocDocument,
    resource_id: *const c_char,
    out_len: *mut usize,
) -> *mut u8 {
    clear_last_error();

    if doc.is_null() {
        set_last_error("document is null");
        return ptr::null_mut();
    }

    if resource_id.is_null() {
        set_last_error("resource_id is null");
        return ptr::null_mut();
    }

    if out_len.is_null() {
        set_last_error("out_len is null");
        return ptr::null_mut();
    }

    let result = catch_unwind(|| {
        let id_str = CStr::from_ptr(resource_id)
            .to_str()
            .map_err(|e| e.to_string())?;

        let document = &(*doc).inner;

        match document.resources.get(id_str) {
            Some(resource) => {
                let data = resource.data.clone();
                let len = data.len();
                let boxed = data.into_boxed_slice();
                let ptr = Box::into_raw(boxed) as *mut u8;
                Ok((ptr, len))
            }
            None => Err(format!("resource not found: {}", id_str)),
        }
    });

    match result {
        Ok(Ok((ptr, len))) => {
            *out_len = len;
            ptr
        }
        Ok(Err(e)) => {
            set_last_error(&e);
            *out_len = 0;
            ptr::null_mut()
        }
        Err(_) => {
            set_last_error("panic occurred");
            *out_len = 0;
            ptr::null_mut()
        }
    }
}

/// Free binary data allocated by `undoc_get_resource_data`.
///
/// # Safety
///
/// - `data` must be a pointer returned by `undoc_get_resource_data`, or null.
/// - `len` must be the length returned by `undoc_get_resource_data`.
/// - After calling this function, the pointer is invalid and must not be used.
#[no_mangle]
pub unsafe extern "C" fn undoc_free_bytes(data: *mut u8, len: usize) {
    if !data.is_null() && len > 0 {
        let _ = Box::from_raw(std::ptr::slice_from_raw_parts_mut(data, len));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ffi::CString;
    use std::path::Path;

    #[test]
    fn test_version() {
        let version = unsafe { undoc_version() };
        assert!(!version.is_null());
        let version_str = unsafe { CStr::from_ptr(version) }.to_str().unwrap();
        assert!(!version_str.is_empty());
    }

    #[test]
    fn test_parse_null_path() {
        let doc = unsafe { undoc_parse_file(ptr::null()) };
        assert!(doc.is_null());

        let error = unsafe { undoc_last_error() };
        assert!(!error.is_null());
    }

    #[test]
    fn test_parse_invalid_path() {
        let path = CString::new("nonexistent.docx").unwrap();
        let doc = unsafe { undoc_parse_file(path.as_ptr()) };
        assert!(doc.is_null());

        let error = unsafe { undoc_last_error() };
        assert!(!error.is_null());
    }

    #[test]
    fn test_parse_and_convert() {
        let path = "test-files/file-sample_1MB.docx";
        if !Path::new(path).exists() {
            return;
        }

        let path_cstr = CString::new(path).unwrap();
        let doc = unsafe { undoc_parse_file(path_cstr.as_ptr()) };
        assert!(!doc.is_null());

        // Test markdown conversion
        let md = unsafe { undoc_to_markdown(doc, 0) };
        assert!(!md.is_null());
        unsafe { undoc_free_string(md) };

        // Test text conversion
        let text = unsafe { undoc_to_text(doc) };
        assert!(!text.is_null());
        unsafe { undoc_free_string(text) };

        // Test JSON conversion
        let json = unsafe { undoc_to_json(doc, UNDOC_JSON_PRETTY) };
        assert!(!json.is_null());
        unsafe { undoc_free_string(json) };

        // Test section count
        let count = unsafe { undoc_section_count(doc) };
        assert!(count >= 0);

        // Free document
        unsafe { undoc_free_document(doc) };
    }

    #[test]
    fn test_null_document_operations() {
        let md = unsafe { undoc_to_markdown(ptr::null(), 0) };
        assert!(md.is_null());

        let text = unsafe { undoc_to_text(ptr::null()) };
        assert!(text.is_null());

        let json = unsafe { undoc_to_json(ptr::null(), 0) };
        assert!(json.is_null());

        let count = unsafe { undoc_section_count(ptr::null()) };
        assert_eq!(count, -1);

        let res_count = unsafe { undoc_resource_count(ptr::null()) };
        assert_eq!(res_count, -1);
    }

    #[test]
    fn test_free_null() {
        // Should not crash
        unsafe {
            undoc_free_document(ptr::null_mut());
            undoc_free_string(ptr::null_mut());
        }
    }
}