micropdf 0.15.15

A pure Rust PDF library - A pure Rust PDF library with fz_/pdf_ API compatibility
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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
//! C FFI for XML parsing - MicroPDF compatible
//! Safe Rust implementation of fz_xml

use super::{Handle, HandleStore};
use std::collections::HashMap;
use std::ffi::{CStr, c_char};
use std::sync::LazyLock;

/// XML node type
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum XmlNodeType {
    /// Document root
    Document = 0,
    /// Element node
    Element = 1,
    /// Text content
    Text = 2,
    /// Comment
    Comment = 3,
    /// CDATA section
    CData = 4,
    /// Processing instruction
    ProcessingInstruction = 5,
}

/// XML node structure
#[derive(Debug, Clone)]
pub struct XmlNode {
    /// Node type
    pub node_type: XmlNodeType,
    /// Tag name (for elements)
    pub name: String,
    /// Namespace URI
    pub namespace_uri: String,
    /// Namespace prefix
    pub namespace_prefix: String,
    /// Text content
    pub content: String,
    /// Attributes
    pub attributes: HashMap<String, String>,
    /// Child nodes
    pub children: Vec<Handle>,
    /// Parent node
    pub parent: Handle,
    /// Next sibling
    pub next: Handle,
    /// Previous sibling
    pub prev: Handle,
}

impl Default for XmlNode {
    fn default() -> Self {
        Self {
            node_type: XmlNodeType::Element,
            name: String::new(),
            namespace_uri: String::new(),
            namespace_prefix: String::new(),
            content: String::new(),
            attributes: HashMap::new(),
            children: Vec::new(),
            parent: 0,
            next: 0,
            prev: 0,
        }
    }
}

/// XML document structure
#[derive(Debug)]
pub struct XmlDocument {
    /// Root element
    pub root: Handle,
    /// All nodes (for handle lookup)
    pub nodes: Vec<Handle>,
    /// Namespace declarations
    pub namespaces: HashMap<String, String>,
    /// XML version
    pub version: String,
    /// Encoding
    pub encoding: String,
    /// Standalone flag
    pub standalone: bool,
}

impl Default for XmlDocument {
    fn default() -> Self {
        Self {
            root: 0,
            nodes: Vec::new(),
            namespaces: HashMap::new(),
            version: "1.0".to_string(),
            encoding: "UTF-8".to_string(),
            standalone: false,
        }
    }
}

/// Global XML node storage
pub static XML_NODES: LazyLock<HandleStore<XmlNode>> = LazyLock::new(HandleStore::new);

/// Global XML document storage
pub static XML_DOCS: LazyLock<HandleStore<XmlDocument>> = LazyLock::new(HandleStore::new);

// ============================================================================
// Document Creation and Parsing
// ============================================================================

/// Create a new empty XML document
#[unsafe(no_mangle)]
pub extern "C" fn fz_new_xml_document(_ctx: Handle) -> Handle {
    XML_DOCS.insert(XmlDocument::default())
}

/// Parse XML from string
///
/// # Safety
/// `xml_string` must be a valid null-terminated UTF-8 string.
#[unsafe(no_mangle)]
pub extern "C" fn fz_parse_xml(
    _ctx: Handle,
    xml_string: *const c_char,
    _preserve_whitespace: i32,
) -> Handle {
    if xml_string.is_null() {
        return 0;
    }

    let xml_str = unsafe { CStr::from_ptr(xml_string) };
    let xml = match xml_str.to_str() {
        Ok(s) => s,
        Err(_) => return 0,
    };

    // Simple XML parser
    match parse_xml_string(xml) {
        Some(doc_handle) => doc_handle,
        None => 0,
    }
}

/// Parse XML from buffer
#[unsafe(no_mangle)]
pub extern "C" fn fz_parse_xml_from_buffer(
    _ctx: Handle,
    buffer: Handle,
    _preserve_whitespace: i32,
) -> Handle {
    if let Some(buf) = super::BUFFERS.get(buffer) {
        if let Ok(guard) = buf.lock() {
            if let Ok(xml_str) = std::str::from_utf8(guard.data()) {
                return parse_xml_string(xml_str).unwrap_or(0);
            }
        }
    }
    0
}

/// Simple XML parser
fn parse_xml_string(xml: &str) -> Option<Handle> {
    let mut doc = XmlDocument::default();

    // Create root document node
    let root_node = XmlNode {
        node_type: XmlNodeType::Document,
        ..Default::default()
    };
    let root_handle = XML_NODES.insert(root_node);
    doc.root = root_handle;
    doc.nodes.push(root_handle);

    // Simple recursive descent parser
    let mut chars = xml.chars().peekable();
    let mut current_parent = root_handle;

    while chars.peek().is_some() {
        skip_whitespace(&mut chars);

        if chars.peek() == Some(&'<') {
            chars.next(); // consume '<'

            if chars.peek() == Some(&'/') {
                // Closing tag
                chars.next();
                let _tag_name = read_until(&mut chars, '>');

                // Move up to parent
                if let Some(node) = XML_NODES.get(current_parent) {
                    if let Ok(guard) = node.lock() {
                        if guard.parent != 0 {
                            current_parent = guard.parent;
                        }
                    }
                }
            } else if chars.peek() == Some(&'?') {
                // Processing instruction
                chars.next();
                let _pi = read_until(&mut chars, '>');
            } else if chars.peek() == Some(&'!') {
                // Comment or CDATA
                chars.next();
                if chars.peek() == Some(&'-') {
                    // Comment
                    read_until(&mut chars, '>');
                } else {
                    // CDATA or DOCTYPE
                    read_until(&mut chars, '>');
                }
            } else {
                // Opening tag
                let (tag_name, attributes, self_closing) = parse_start_tag(&mut chars);

                let mut new_node = XmlNode {
                    node_type: XmlNodeType::Element,
                    name: tag_name,
                    parent: current_parent,
                    ..Default::default()
                };

                // Parse attributes
                for (key, mut value) in attributes {
                    // Append null terminator for C string compatibility
                    value.push('\0');

                    if key.starts_with("xmlns") {
                        // Namespace declaration
                        if key == "xmlns" {
                            new_node.namespace_uri = value;
                        } else if let Some(prefix) = key.strip_prefix("xmlns:") {
                            doc.namespaces.insert(prefix.to_string(), value);
                        }
                    } else {
                        new_node.attributes.insert(key, value);
                    }
                }

                let new_handle = XML_NODES.insert(new_node);
                doc.nodes.push(new_handle);

                // Link to parent
                if let Some(parent_node) = XML_NODES.get(current_parent) {
                    if let Ok(mut guard) = parent_node.lock() {
                        // Update sibling links
                        if let Some(&prev_sibling) = guard.children.last() {
                            if let Some(prev) = XML_NODES.get(prev_sibling) {
                                if let Ok(mut prev_guard) = prev.lock() {
                                    prev_guard.next = new_handle;
                                }
                            }
                            if let Some(new) = XML_NODES.get(new_handle) {
                                if let Ok(mut new_guard) = new.lock() {
                                    new_guard.prev = prev_sibling;
                                }
                            }
                        }
                        guard.children.push(new_handle);
                    }
                }

                if !self_closing {
                    current_parent = new_handle;
                }
            }
        } else {
            // Text content
            let text = read_until_char(&mut chars, '<');
            let trimmed = text.trim();

            if !trimmed.is_empty() {
                let text_node = XmlNode {
                    node_type: XmlNodeType::Text,
                    content: trimmed.to_string(),
                    parent: current_parent,
                    ..Default::default()
                };
                let text_handle = XML_NODES.insert(text_node);
                doc.nodes.push(text_handle);

                if let Some(parent_node) = XML_NODES.get(current_parent) {
                    if let Ok(mut guard) = parent_node.lock() {
                        guard.children.push(text_handle);
                    }
                }
            }
        }
    }

    Some(XML_DOCS.insert(doc))
}

fn skip_whitespace(chars: &mut std::iter::Peekable<std::str::Chars>) {
    while chars.peek().map(|c| c.is_whitespace()).unwrap_or(false) {
        chars.next();
    }
}

fn read_until(chars: &mut std::iter::Peekable<std::str::Chars>, end: char) -> String {
    let mut result = String::new();
    while let Some(&c) = chars.peek() {
        chars.next();
        if c == end {
            break;
        }
        result.push(c);
    }
    result
}

fn read_until_char(chars: &mut std::iter::Peekable<std::str::Chars>, end: char) -> String {
    let mut result = String::new();
    while let Some(&c) = chars.peek() {
        if c == end {
            break;
        }
        chars.next();
        result.push(c);
    }
    result
}

fn parse_start_tag(
    chars: &mut std::iter::Peekable<std::str::Chars>,
) -> (String, Vec<(String, String)>, bool) {
    let mut tag_name = String::new();
    let mut attributes = Vec::new();
    let mut self_closing = false;

    // Read tag name
    while let Some(&c) = chars.peek() {
        if c.is_whitespace() || c == '>' || c == '/' {
            break;
        }
        chars.next();
        tag_name.push(c);
    }

    // Read attributes
    loop {
        skip_whitespace(chars);

        match chars.peek() {
            Some(&'>') => {
                chars.next();
                break;
            }
            Some(&'/') => {
                chars.next();
                if chars.peek() == Some(&'>') {
                    chars.next();
                    self_closing = true;
                }
                break;
            }
            Some(_) => {
                // Read attribute name
                let attr_name = read_until_chars(chars, &['=', '>', '/', ' ']);
                skip_whitespace(chars);

                if chars.peek() == Some(&'=') {
                    chars.next();
                    skip_whitespace(chars);

                    // Read attribute value
                    let quote = chars.next().unwrap_or('"');
                    let attr_value = read_until(chars, quote);
                    attributes.push((attr_name, attr_value));
                }
            }
            None => break,
        }
    }

    (tag_name, attributes, self_closing)
}

fn read_until_chars(chars: &mut std::iter::Peekable<std::str::Chars>, ends: &[char]) -> String {
    let mut result = String::new();
    while let Some(&c) = chars.peek() {
        if ends.contains(&c) {
            break;
        }
        chars.next();
        result.push(c);
    }
    result
}

// ============================================================================
// Document Navigation
// ============================================================================

/// Get root element of document
#[unsafe(no_mangle)]
pub extern "C" fn fz_xml_root(_ctx: Handle, doc: Handle) -> Handle {
    if let Some(d) = XML_DOCS.get(doc) {
        if let Ok(guard) = d.lock() {
            // Return first child of document node
            if let Some(root) = XML_NODES.get(guard.root) {
                if let Ok(root_guard) = root.lock() {
                    return root_guard.children.first().copied().unwrap_or(0);
                }
            }
        }
    }
    0
}

/// Get first child element
#[unsafe(no_mangle)]
pub extern "C" fn fz_xml_down(_ctx: Handle, node: Handle) -> Handle {
    if let Some(n) = XML_NODES.get(node) {
        if let Ok(guard) = n.lock() {
            return guard.children.first().copied().unwrap_or(0);
        }
    }
    0
}

/// Get next sibling element
#[unsafe(no_mangle)]
pub extern "C" fn fz_xml_next(_ctx: Handle, node: Handle) -> Handle {
    if let Some(n) = XML_NODES.get(node) {
        if let Ok(guard) = n.lock() {
            return guard.next;
        }
    }
    0
}

/// Get previous sibling element
#[unsafe(no_mangle)]
pub extern "C" fn fz_xml_prev(_ctx: Handle, node: Handle) -> Handle {
    if let Some(n) = XML_NODES.get(node) {
        if let Ok(guard) = n.lock() {
            return guard.prev;
        }
    }
    0
}

/// Get parent element
#[unsafe(no_mangle)]
pub extern "C" fn fz_xml_up(_ctx: Handle, node: Handle) -> Handle {
    if let Some(n) = XML_NODES.get(node) {
        if let Ok(guard) = n.lock() {
            return guard.parent;
        }
    }
    0
}

// ============================================================================
// Node Properties
// ============================================================================

/// Get node tag name
#[unsafe(no_mangle)]
pub extern "C" fn fz_xml_tag(_ctx: Handle, node: Handle) -> *const c_char {
    static EMPTY: &[u8] = b"\0";

    if let Some(n) = XML_NODES.get(node) {
        if let Ok(guard) = n.lock() {
            if !guard.name.is_empty() {
                return guard.name.as_ptr().cast();
            }
        }
    }
    EMPTY.as_ptr().cast()
}

/// Check if node has specific tag
#[unsafe(no_mangle)]
pub extern "C" fn fz_xml_is_tag(_ctx: Handle, node: Handle, tag: *const c_char) -> i32 {
    if tag.is_null() {
        return 0;
    }

    let tag_str = unsafe { CStr::from_ptr(tag) };
    let tag_name = tag_str.to_str().unwrap_or("");

    if let Some(n) = XML_NODES.get(node) {
        if let Ok(guard) = n.lock() {
            return i32::from(guard.name == tag_name);
        }
    }
    0
}

/// Get node text content
#[unsafe(no_mangle)]
pub extern "C" fn fz_xml_text(_ctx: Handle, node: Handle) -> *const c_char {
    static EMPTY: &[u8] = b"\0";

    if let Some(n) = XML_NODES.get(node) {
        if let Ok(guard) = n.lock() {
            if guard.node_type == XmlNodeType::Text && !guard.content.is_empty() {
                return guard.content.as_ptr().cast();
            }
        }
    }
    EMPTY.as_ptr().cast()
}

/// Get attribute value
#[unsafe(no_mangle)]
pub extern "C" fn fz_xml_att(_ctx: Handle, node: Handle, name: *const c_char) -> *const c_char {
    if name.is_null() {
        return std::ptr::null();
    }

    let name_str = unsafe { CStr::from_ptr(name) };
    let attr_name = name_str.to_str().unwrap_or("");

    if let Some(n) = XML_NODES.get(node) {
        if let Ok(guard) = n.lock() {
            if let Some(value) = guard.attributes.get(attr_name) {
                return value.as_ptr().cast();
            }
        }
    }
    std::ptr::null()
}

/// Get attribute count
#[unsafe(no_mangle)]
pub extern "C" fn fz_xml_att_count(_ctx: Handle, node: Handle) -> i32 {
    if let Some(n) = XML_NODES.get(node) {
        if let Ok(guard) = n.lock() {
            return guard.attributes.len() as i32;
        }
    }
    0
}

/// Get child count
#[unsafe(no_mangle)]
pub extern "C" fn fz_xml_child_count(_ctx: Handle, node: Handle) -> i32 {
    if let Some(n) = XML_NODES.get(node) {
        if let Ok(guard) = n.lock() {
            return guard.children.len() as i32;
        }
    }
    0
}

/// Get node type
#[unsafe(no_mangle)]
pub extern "C" fn fz_xml_node_type(_ctx: Handle, node: Handle) -> i32 {
    if let Some(n) = XML_NODES.get(node) {
        if let Ok(guard) = n.lock() {
            return guard.node_type as i32;
        }
    }
    -1
}

// ============================================================================
// XPath Queries (Simple Implementation)
// ============================================================================

/// Find element by simple path (e.g., "root/child/grandchild")
#[unsafe(no_mangle)]
pub extern "C" fn fz_xml_find(_ctx: Handle, node: Handle, path: *const c_char) -> Handle {
    if path.is_null() {
        return 0;
    }

    let path_str = unsafe { CStr::from_ptr(path) };
    let xpath = path_str.to_str().unwrap_or("");

    let mut current = node;
    for segment in xpath.split('/') {
        if segment.is_empty() {
            continue;
        }

        current = find_child_by_tag(current, segment);
        if current == 0 {
            return 0;
        }
    }

    current
}

fn find_child_by_tag(parent: Handle, tag: &str) -> Handle {
    if let Some(n) = XML_NODES.get(parent) {
        if let Ok(guard) = n.lock() {
            for &child in &guard.children {
                if let Some(child_node) = XML_NODES.get(child) {
                    if let Ok(child_guard) = child_node.lock() {
                        if child_guard.name == tag {
                            return child;
                        }
                    }
                }
            }
        }
    }
    0
}

/// Find all elements matching tag
#[unsafe(no_mangle)]
pub extern "C" fn fz_xml_find_all(
    _ctx: Handle,
    node: Handle,
    tag: *const c_char,
    results: *mut Handle,
    max_results: i32,
) -> i32 {
    if tag.is_null() || results.is_null() || max_results <= 0 {
        return 0;
    }

    let tag_str = unsafe { CStr::from_ptr(tag) };
    let tag_name = tag_str.to_str().unwrap_or("");

    let mut found = Vec::new();
    find_all_recursive(node, tag_name, &mut found, max_results as usize);

    let count = found.len().min(max_results as usize);
    let result_slice = unsafe { std::slice::from_raw_parts_mut(results, count) };
    result_slice.copy_from_slice(&found[..count]);

    count as i32
}

fn find_all_recursive(node: Handle, tag: &str, results: &mut Vec<Handle>, max: usize) {
    if results.len() >= max {
        return;
    }

    if let Some(n) = XML_NODES.get(node) {
        if let Ok(guard) = n.lock() {
            if guard.name == tag {
                results.push(node);
            }

            for &child in &guard.children {
                find_all_recursive(child, tag, results, max);
            }
        }
    }
}

// ============================================================================
// Reference Counting
// ============================================================================

/// Drop XML document
#[unsafe(no_mangle)]
pub extern "C" fn fz_drop_xml(_ctx: Handle, doc: Handle) {
    if let Some(d) = XML_DOCS.get(doc) {
        if let Ok(guard) = d.lock() {
            // Drop all nodes
            for &node in &guard.nodes {
                XML_NODES.remove(node);
            }
        }
    }
    XML_DOCS.remove(doc);
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_simple_xml() {
        let xml = c"<root><child>text</child></root>";
        let doc = fz_parse_xml(0, xml.as_ptr(), 0);
        assert!(doc > 0);

        let root = fz_xml_root(0, doc);
        assert!(root > 0);
        assert_eq!(fz_xml_is_tag(0, root, c"root".as_ptr()), 1);

        let child = fz_xml_down(0, root);
        assert!(child > 0);
        assert_eq!(fz_xml_is_tag(0, child, c"child".as_ptr()), 1);

        fz_drop_xml(0, doc);
    }

    #[test]
    fn test_xml_attributes() {
        let xml = c"<elem attr=\"value\" num=\"42\"/>";
        let doc = fz_parse_xml(0, xml.as_ptr(), 0);
        let root = fz_xml_root(0, doc);

        assert_eq!(fz_xml_att_count(0, root), 2);

        let attr = fz_xml_att(0, root, c"attr".as_ptr());
        assert!(!attr.is_null());
        let attr_str = unsafe { CStr::from_ptr(attr) };
        assert_eq!(attr_str.to_str().unwrap(), "value");

        fz_drop_xml(0, doc);
    }

    #[test]
    fn test_xml_navigation() {
        let xml = c"<root><a/><b/><c/></root>";
        let doc = fz_parse_xml(0, xml.as_ptr(), 0);
        let root = fz_xml_root(0, doc);

        let a = fz_xml_down(0, root);
        assert_eq!(fz_xml_is_tag(0, a, c"a".as_ptr()), 1);

        let b = fz_xml_next(0, a);
        assert_eq!(fz_xml_is_tag(0, b, c"b".as_ptr()), 1);

        let c = fz_xml_next(0, b);
        assert_eq!(fz_xml_is_tag(0, c, c"c".as_ptr()), 1);

        // Navigate back
        let b_again = fz_xml_prev(0, c);
        assert_eq!(fz_xml_is_tag(0, b_again, c"b".as_ptr()), 1);

        fz_drop_xml(0, doc);
    }

    #[test]
    fn test_xml_find() {
        let xml = c"<root><level1><level2>deep</level2></level1></root>";
        let doc = fz_parse_xml(0, xml.as_ptr(), 0);
        let root = fz_xml_root(0, doc);

        let level2 = fz_xml_find(0, root, c"level1/level2".as_ptr());
        assert!(level2 > 0);
        assert_eq!(fz_xml_is_tag(0, level2, c"level2".as_ptr()), 1);

        fz_drop_xml(0, doc);
    }

    #[test]
    fn test_parse_xml_null() {
        assert_eq!(fz_parse_xml(0, std::ptr::null(), 0), 0);
    }

    #[test]
    fn test_parse_xml_from_buffer_invalid() {
        assert_eq!(fz_parse_xml_from_buffer(0, 99999, 0), 0);
    }

    #[test]
    fn test_xml_root_invalid() {
        assert_eq!(fz_xml_root(0, 0), 0);
        assert_eq!(fz_xml_root(0, 99999), 0);
    }

    #[test]
    fn test_xml_down_next_prev_up_invalid() {
        assert_eq!(fz_xml_down(0, 0), 0);
        assert_eq!(fz_xml_next(0, 0), 0);
        assert_eq!(fz_xml_prev(0, 0), 0);
        assert_eq!(fz_xml_up(0, 0), 0);
    }

    #[test]
    fn test_xml_tag_text_invalid() {
        assert!(!fz_xml_tag(0, 0).is_null());
        assert!(!fz_xml_text(0, 0).is_null());
    }

    #[test]
    fn test_xml_is_tag_null() {
        let xml = c"<root/>";
        let doc = fz_parse_xml(0, xml.as_ptr(), 0);
        let root = fz_xml_root(0, doc);
        assert_eq!(fz_xml_is_tag(0, root, std::ptr::null()), 0);
        fz_drop_xml(0, doc);
    }

    #[test]
    fn test_xml_att_null() {
        let xml = c"<root a=\"v\"/>";
        let doc = fz_parse_xml(0, xml.as_ptr(), 0);
        let root = fz_xml_root(0, doc);
        assert!(fz_xml_att(0, root, std::ptr::null()).is_null());
        fz_drop_xml(0, doc);
    }

    #[test]
    fn test_xml_att_count_child_count_node_type_invalid() {
        assert_eq!(fz_xml_att_count(0, 0), 0);
        assert_eq!(fz_xml_child_count(0, 0), 0);
        assert_eq!(fz_xml_node_type(0, 0), -1);
    }

    #[test]
    fn test_xml_find_null_path() {
        let xml = c"<root/>";
        let doc = fz_parse_xml(0, xml.as_ptr(), 0);
        let root = fz_xml_root(0, doc);
        assert_eq!(fz_xml_find(0, root, std::ptr::null()), 0);
        fz_drop_xml(0, doc);
    }

    #[test]
    fn test_xml_find_all() {
        let xml = c"<root><a/><a/><a/></root>";
        let doc = fz_parse_xml(0, xml.as_ptr(), 0);
        let root = fz_xml_root(0, doc);
        let mut results = [0u64; 10];
        let n = fz_xml_find_all(0, root, c"a".as_ptr(), results.as_mut_ptr(), 10);
        assert_eq!(n, 3);
        fz_drop_xml(0, doc);
    }

    #[test]
    fn test_xml_find_all_null() {
        let xml = c"<root><a/></root>";
        let doc = fz_parse_xml(0, xml.as_ptr(), 0);
        let root = fz_xml_root(0, doc);
        assert_eq!(
            fz_xml_find_all(0, root, std::ptr::null(), [0u64].as_mut_ptr(), 10),
            0
        );
        assert_eq!(
            fz_xml_find_all(0, root, c"a".as_ptr(), std::ptr::null_mut(), 10),
            0
        );
        assert_eq!(
            fz_xml_find_all(0, root, c"a".as_ptr(), [0u64].as_mut_ptr(), 0),
            0
        );
        fz_drop_xml(0, doc);
    }

    #[test]
    fn test_new_xml_document() {
        let doc = fz_new_xml_document(0);
        assert_ne!(doc, 0);
        fz_drop_xml(0, doc);
    }

    #[test]
    fn test_xml_text_content() {
        let xml = c"<root><child>hello world</child></root>";
        let doc = fz_parse_xml(0, xml.as_ptr(), 0);
        let root = fz_xml_root(0, doc);
        let child = fz_xml_down(0, root);
        let text_ptr = fz_xml_text(0, child);
        assert!(!text_ptr.is_null());
        fz_drop_xml(0, doc);
    }
}