flpdf 0.3.0

A pure-Rust PDF toolkit modeled on qpdf — read, rewrite, linearize, and inspect PDFs.
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
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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
//! Generic name-tree / number-tree iteration (ISO 32000-2 §7.9.6 / §7.9.7).
//!
//! Name trees (`/Names` leaf, string keys) and number trees (`/Nums` leaf,
//! integer keys) share the same shape: `/Kids` intermediate nodes, an optional
//! `/Limits [least greatest]` array, depth-first key-ascending order, and the
//! need for depth + cycle guards against hostile or cyclic `/Kids` chains.
//!
//! [`read_name_tree`] / [`read_number_tree`] enumerate a tree, decoding each
//! value via a caller-supplied hook (generic over the value type, so the same
//! walker serves verbatim-`Object`, reference-only, and resolved-`Dictionary`
//! views). [`build_name_tree`] rebuilds a name tree from sorted entries.
//!
//! This module owns only structural concerns (parse + build). Catalog wiring,
//! `/AF` upkeep, GC, and prune-during-walk stay in the consumer.

use crate::ref_chain::resolve_ref_chain;
use crate::{Dictionary, Object, ObjectRef, Pdf, Result};
use std::collections::BTreeSet;
use std::io::{Read, Seek};

/// Default `/Kids` descent depth limit (cyclic / maliciously deep guard).
pub const DEFAULT_MAX_TREE_DEPTH: usize = 100;

/// Max entries in a single leaf before [`build_name_tree`] splits into a
/// `/Kids` root (mirrors qpdf's aggressive rebuild threshold).
pub const LEAF_MAX: usize = 32;

/// Enumerate a **name** tree rooted at `root` (a `/Kids` root node reference,
/// or an inline node dictionary), decoding each value via `decode`.
///
/// Entries are returned in depth-first order (the spec mandates keys be sorted).
/// `decode` returning `Ok(None)` skips that entry; non-string keys and the
/// trailing orphan of an odd-length leaf array are dropped silently.
///
/// # Errors
/// Propagates [`Pdf::resolve_borrowed`] (indirect-object resolution) errors and
/// returns [`crate::Error::Unsupported`] if a `/Kids` chain reaches `max_depth`.
pub fn read_name_tree<R, V, F>(
    pdf: &mut Pdf<R>,
    root: Object,
    mut decode: F,
    max_depth: usize,
) -> Result<Vec<(Vec<u8>, V)>>
where
    R: Read + Seek,
    F: FnMut(&mut Pdf<R>, Object) -> Result<Option<V>>,
{
    let mut out = Vec::new();
    let mut visited = BTreeSet::new();
    walk_tree(
        pdf,
        root,
        "Names",
        &|o| match o {
            Object::String(b) => Some(b),
            _ => None,
        },
        &mut decode,
        &mut out,
        &mut visited,
        0,
        max_depth,
    )?;
    Ok(out)
}

/// Enumerate a **number** tree rooted at `root` (a `/Kids` root node reference,
/// or an inline node dictionary), decoding each value via `decode`.
///
/// Same semantics as [`read_name_tree`] but with `/Nums` leaves and integer
/// keys; non-integer keys are skipped.
///
/// # Errors
/// Propagates [`Pdf::resolve_borrowed`] (indirect-object resolution) errors and
/// returns [`crate::Error::Unsupported`] if a `/Kids` chain reaches `max_depth`.
pub fn read_number_tree<R, V, F>(
    pdf: &mut Pdf<R>,
    root: Object,
    mut decode: F,
    max_depth: usize,
) -> Result<Vec<(i64, V)>>
where
    R: Read + Seek,
    F: FnMut(&mut Pdf<R>, Object) -> Result<Option<V>>,
{
    let mut out = Vec::new();
    let mut visited = BTreeSet::new();
    walk_tree(
        pdf,
        root,
        "Nums",
        &|o| match o {
            Object::Integer(n) => Some(n),
            _ => None,
        },
        &mut decode,
        &mut out,
        &mut visited,
        0,
        max_depth,
    )?;
    Ok(out)
}

/// Build a name-tree from a **non-empty, pre-sorted** `(key, value)` slice.
///
/// Returns `(root_ref, nodes)` where `nodes` is every `(ObjectRef, Object)` the
/// caller must store via [`Pdf::set_object`]. The caller owns object numbering
/// (via `alloc`), the empty-entries case, and all catalog wiring.
///
/// Layout (qpdf-aligned). Per ISO 32000-2 §7.9.6, `/Limits` is carried by
/// intermediate and leaf nodes only; the root node omits it:
/// - `<= LEAF_MAX` entries → a single root node holding `/Names` only (no
///   `/Limits`), returned as the root.
/// - `> LEAF_MAX` entries → leaves chunked by `div_ceil`, each `/Limits` +
///   `/Names`, under a root carrying `/Kids` only (no `/Limits`). Leaves are
///   allocated in order, the root last.
///
/// The number-tree analogue is [`build_number_tree`]; the two share this exact
/// chunking/allocation layout and must be kept in sync (only the key encoding
/// and the `/Names` vs `/Nums` leaf key differ).
///
/// # Panics (debug)
/// Debug-asserts `entries` is non-empty.
pub fn build_name_tree<A>(
    entries: &[(Vec<u8>, Object)],
    mut alloc: A,
) -> (ObjectRef, Vec<(ObjectRef, Object)>)
where
    A: FnMut() -> ObjectRef,
{
    debug_assert!(
        !entries.is_empty(),
        "build_name_tree requires non-empty entries"
    );
    let mut nodes: Vec<(ObjectRef, Object)> = Vec::new();

    if entries.len() <= LEAF_MAX {
        let root_ref = alloc();
        // Root node omits /Limits: ISO 32000-2 7.9.6 restricts /Limits to
        // intermediate and leaf nodes. qpdf emits a single-node name-tree root as
        // /Names only.
        let mut root = Dictionary::new();
        root.insert("Names", Object::Array(name_pairs(entries)));
        nodes.push((root_ref, Object::Dictionary(root)));
        return (root_ref, nodes);
    }

    let n_leaves = entries.len().div_ceil(LEAF_MAX);
    let chunk_size = entries.len().div_ceil(n_leaves);
    let mut kids: Vec<Object> = Vec::with_capacity(n_leaves);
    for chunk in entries.chunks(chunk_size) {
        let leaf_ref = alloc();
        nodes.push((leaf_ref, Object::Dictionary(build_leaf_dict(chunk))));
        kids.push(Object::Reference(leaf_ref));
    }
    // Root node omits /Limits (ISO 32000-2 7.9.6: /Limits is for intermediate
    // and leaf nodes only; qpdf emits a multi-node root as /Kids only).
    let mut root = Dictionary::new();
    root.insert("Kids", Object::Array(kids));
    let root_ref = alloc();
    nodes.push((root_ref, Object::Dictionary(root)));
    (root_ref, nodes)
}

/// The `/Names` value: a flat `[key1 val1 key2 val2 ...]` array.
fn name_pairs(entries: &[(Vec<u8>, Object)]) -> Vec<Object> {
    let mut pairs = Vec::with_capacity(entries.len() * 2);
    for (key, val) in entries {
        pairs.push(Object::String(key.clone()));
        pairs.push(val.clone());
    }
    pairs
}

/// Leaf node dict: `/Limits [first last]` + `/Names [k1 v1 ...]`.
fn build_leaf_dict(entries: &[(Vec<u8>, Object)]) -> Dictionary {
    let first = entries.first().map(|(k, _)| k.clone()).unwrap_or_default();
    let last = entries.last().map(|(k, _)| k.clone()).unwrap_or_default();
    let mut dict = Dictionary::new();
    dict.insert(
        "Limits",
        Object::Array(vec![Object::String(first), Object::String(last)]),
    );
    dict.insert("Names", Object::Array(name_pairs(entries)));
    dict
}

/// Build a **number** tree from a **non-empty, pre-sorted** `(key, value)` slice.
///
/// Number-tree analogue of [`build_name_tree`]: identical layout per ISO
/// 32000-2 §7.9.7. For `<= LEAF_MAX` entries the root holds `/Nums` only (no
/// `/Limits`); otherwise `div_ceil`-chunked leaves (each `/Limits` + `/Nums`,
/// **integer** `/Limits`) sit under a root carrying `/Kids` only (no
/// `/Limits`), leaves allocated first then the root. Returns `(root_ref,
/// nodes)` for the caller to [`Pdf::set_object`]; the caller owns numbering,
/// the empty case, and catalog wiring.
///
/// # Panics (debug)
/// Debug-asserts `entries` is non-empty.
pub fn build_number_tree<A>(
    entries: &[(i64, Object)],
    mut alloc: A,
) -> (ObjectRef, Vec<(ObjectRef, Object)>)
where
    A: FnMut() -> ObjectRef,
{
    debug_assert!(
        !entries.is_empty(),
        "build_number_tree requires non-empty entries"
    );
    let mut nodes: Vec<(ObjectRef, Object)> = Vec::new();

    if entries.len() <= LEAF_MAX {
        let root_ref = alloc();
        // Root node omits /Limits: ISO 32000-2 7.9.7 restricts /Limits to
        // intermediate and leaf nodes. qpdf emits a single-node number-tree root
        // as /Nums only.
        let mut root = Dictionary::new();
        root.insert("Nums", Object::Array(num_pairs(entries)));
        nodes.push((root_ref, Object::Dictionary(root)));
        return (root_ref, nodes);
    }

    let n_leaves = entries.len().div_ceil(LEAF_MAX);
    let chunk_size = entries.len().div_ceil(n_leaves);
    let mut kids: Vec<Object> = Vec::with_capacity(n_leaves);
    for chunk in entries.chunks(chunk_size) {
        let leaf_ref = alloc();
        nodes.push((leaf_ref, Object::Dictionary(build_num_leaf_dict(chunk))));
        kids.push(Object::Reference(leaf_ref));
    }
    // Root node omits /Limits (ISO 32000-2 7.9.7: /Limits is for intermediate
    // and leaf nodes only; qpdf emits a multi-node root as /Kids only).
    let mut root = Dictionary::new();
    root.insert("Kids", Object::Array(kids));
    let root_ref = alloc();
    nodes.push((root_ref, Object::Dictionary(root)));
    (root_ref, nodes)
}

/// The `/Nums` value: a flat `[key1 val1 key2 val2 ...]` array (integer keys).
fn num_pairs(entries: &[(i64, Object)]) -> Vec<Object> {
    let mut pairs = Vec::with_capacity(entries.len() * 2);
    for (key, val) in entries {
        pairs.push(Object::Integer(*key));
        pairs.push(val.clone());
    }
    pairs
}

/// Leaf node dict: `/Limits [first last]` (integers) + `/Nums [k1 v1 ...]`.
fn build_num_leaf_dict(entries: &[(i64, Object)]) -> Dictionary {
    let first = entries.first().map(|(k, _)| *k).unwrap_or_default();
    let last = entries.last().map(|(k, _)| *k).unwrap_or_default();
    let mut dict = Dictionary::new();
    dict.insert(
        "Limits",
        Object::Array(vec![Object::Integer(first), Object::Integer(last)]),
    );
    dict.insert("Nums", Object::Array(num_pairs(entries)));
    dict
}

/// Internal generic walker shared by name + number readers.
///
/// `node` is a `Reference` (resolved + cycle-tracked here) or a `Dictionary`.
/// `leaf_key` is `"Names"` or `"Nums"`; `parse_key` converts a leaf key object
/// to `K` (or `None` to skip the pair).
#[allow(clippy::too_many_arguments)]
fn walk_tree<R, K, V, FK, FV>(
    pdf: &mut Pdf<R>,
    node: Object,
    leaf_key: &str,
    parse_key: &FK,
    decode: &mut FV,
    out: &mut Vec<(K, V)>,
    visited: &mut BTreeSet<ObjectRef>,
    depth: usize,
    max_depth: usize,
) -> Result<()>
where
    R: Read + Seek,
    FK: Fn(Object) -> Option<K>,
    FV: FnMut(&mut Pdf<R>, Object) -> Result<Option<V>>,
{
    if depth >= max_depth {
        return Err(crate::Error::Unsupported(format!(
            "name_number_tree: /Kids depth limit {max_depth} exceeded"
        )));
    }

    // Resolve a reference node (cycle-tracked); inline dicts pass through.
    let mut dict: Dictionary = match node {
        Object::Dictionary(d) => d,
        Object::Reference(r) => {
            // A /Kids node ref may be a holder chain (`r → r2 → node dict`);
            // follow it to the terminal so a doubled-indirect kid is descended,
            // not dropped. Holder hops are bounded by resolve_ref_chain's own
            // MAX_REF_CHAIN_DEPTH — a separate axis from the /Kids `visited` /
            // `depth` guards (kept as-is). `into_dict` takes the terminal by
            // value, so no extra clone over the prior `as_dict().clone()`.
            let (terminal, terminal_ref) = resolve_ref_chain(pdf, &Object::Reference(r))?;
            // Dedup on the *terminal* ref, not the holder `r`: two distinct
            // holders (`21 0 R`, `22 0 R`) resolving to one terminal node are
            // the holder-form of a direct `[20 0 R 20 0 R]` dup, which the
            // visited set already collapses. Keying on `r` would walk that
            // shared child twice and emit duplicate name/number-tree entries.
            // (terminal_ref is always Some for a Reference start; fall back to
            // `r` defensively.)
            if !visited.insert(terminal_ref.unwrap_or(r)) {
                return Ok(()); // already walked this terminal node / cycle — skip
            }
            match terminal.into_dict() {
                Some(d) => d,
                None => return Ok(()), // malformed / non-dict node — skip
            }
        }
        _ => return Ok(()), // unexpected node type — skip
    };

    // Leaf takes priority over /Kids (spec leaf vs. intermediate). `dict` is
    // owned here, so move the leaf array out instead of copying it. A non-array
    // (or absent) leaf value falls through to /Kids, matching the old
    // `.and_then(Object::as_array)` semantics.
    if let Some(Object::Array(pairs)) = dict.remove(leaf_key) {
        let mut it = pairs.into_iter();
        while let Some(key_obj) = it.next() {
            let Some(val_obj) = it.next() else {
                break; // odd-length array — drop orphan key
            };
            let Some(key) = parse_key(key_obj) else {
                continue; // non-matching key type — skip pair
            };
            if let Some(v) = decode(pdf, val_obj)? {
                out.push((key, v));
            }
        }
        return Ok(());
    }

    // Intermediate node. Only indirect-reference kids are descended (inline-dict
    // kids are dropped, preserving the two legacy walkers this module replaces).
    if let Some(kids) = dict.get("Kids").and_then(Object::as_array) {
        // `kids` borrows the owned local `dict`; the recursive call only borrows
        // `pdf`/`decode`/… (never `dict`), so iterate the filter_map directly and
        // avoid a per-node `Vec<ObjectRef>` heap allocation.
        for r in kids.iter().filter_map(Object::as_ref_id) {
            walk_tree(
                pdf,
                Object::Reference(r),
                leaf_key,
                parse_key,
                decode,
                out,
                visited,
                depth + 1,
                max_depth,
            )?;
        }
    }
    Ok(())
}

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

    // Shared decode hooks, reused across tests so each body is defined (and
    // covered) once instead of as a fresh inline closure per call site.
    fn ref_only<R: Read + Seek>(_: &mut Pdf<R>, v: Object) -> Result<Option<ObjectRef>> {
        Ok(v.as_ref_id())
    }
    fn verbatim<R: Read + Seek>(_: &mut Pdf<R>, v: Object) -> Result<Option<Object>> {
        Ok(Some(v))
    }

    #[test]
    fn read_name_tree_verbatim_passes_value_through() {
        // The verbatim decode keeps each leaf value as-is (used by the raw
        // collector view).
        let mut pdf = empty_pdf();
        let mut leaf = Dictionary::new();
        leaf.insert(
            "Names",
            Object::Array(vec![Object::String(b"k".to_vec()), Object::Integer(7)]),
        );
        let out = read_name_tree(
            &mut pdf,
            Object::Dictionary(leaf),
            verbatim,
            DEFAULT_MAX_TREE_DEPTH,
        )
        .unwrap();
        assert_eq!(out, vec![(b"k".to_vec(), Object::Integer(7))]);
    }

    fn empty_pdf() -> Pdf<std::io::Cursor<Vec<u8>>> {
        // Minimal valid PDF; the readers don't need a real catalog because we
        // pass nodes directly via set_object refs.
        let mut bytes = Vec::new();
        bytes.extend_from_slice(b"%PDF-1.4\n");
        let off1 = bytes.len() as u64;
        bytes.extend_from_slice(b"1 0 obj\n<< /Type /Catalog >>\nendobj\n");
        let xref = bytes.len() as u64;
        bytes.extend_from_slice(
            format!(
                "xref\n0 2\n0000000000 65535 f \n{off1:010} 00000 n \ntrailer\n<< /Size 2 /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n"
            )
            .as_bytes(),
        );
        Pdf::open(std::io::Cursor::new(bytes)).expect("open")
    }

    #[test]
    fn read_name_tree_inline_leaf_ref_only() {
        let mut pdf = empty_pdf();
        let mut leaf = Dictionary::new();
        leaf.insert(
            "Names",
            Object::Array(vec![
                Object::String(b"a".to_vec()),
                Object::Reference(ObjectRef::new(10, 0)),
                Object::String(b"b".to_vec()),
                Object::Reference(ObjectRef::new(11, 0)),
            ]),
        );
        let out = read_name_tree(
            &mut pdf,
            Object::Dictionary(leaf),
            ref_only,
            DEFAULT_MAX_TREE_DEPTH,
        )
        .unwrap();
        assert_eq!(
            out,
            vec![
                (b"a".to_vec(), ObjectRef::new(10, 0)),
                (b"b".to_vec(), ObjectRef::new(11, 0)),
            ]
        );
    }

    #[test]
    fn read_name_tree_skips_when_decode_none() {
        let mut pdf = empty_pdf();
        let mut leaf = Dictionary::new();
        leaf.insert(
            "Names",
            Object::Array(vec![
                Object::String(b"a".to_vec()),
                Object::Integer(5), // not a ref -> decode returns None -> skipped
                Object::String(b"b".to_vec()),
                Object::Reference(ObjectRef::new(11, 0)),
            ]),
        );
        let out = read_name_tree(
            &mut pdf,
            Object::Dictionary(leaf),
            ref_only,
            DEFAULT_MAX_TREE_DEPTH,
        )
        .unwrap();
        assert_eq!(out, vec![(b"b".to_vec(), ObjectRef::new(11, 0))]);
    }

    #[test]
    fn read_name_tree_descends_kids_via_reference() {
        let mut pdf = empty_pdf();
        // Leaf object at ref 20.
        let mut leaf = Dictionary::new();
        leaf.insert(
            "Names",
            Object::Array(vec![
                Object::String(b"k".to_vec()),
                Object::Reference(ObjectRef::new(99, 0)),
            ]),
        );
        let leaf_ref = ObjectRef::new(20, 0);
        pdf.set_object(leaf_ref, Object::Dictionary(leaf));
        // Root with /Kids -> [20 0 R].
        let mut root = Dictionary::new();
        root.insert("Kids", Object::Array(vec![Object::Reference(leaf_ref)]));
        let out = read_name_tree(
            &mut pdf,
            Object::Dictionary(root),
            ref_only,
            DEFAULT_MAX_TREE_DEPTH,
        )
        .unwrap();
        assert_eq!(out, vec![(b"k".to_vec(), ObjectRef::new(99, 0))]);
    }

    #[test]
    fn read_name_tree_descends_kids_via_holder_chain() {
        let mut pdf = empty_pdf();
        // Leaf node at obj 20.
        let mut leaf = Dictionary::new();
        leaf.insert(
            "Names",
            Object::Array(vec![
                Object::String(b"k".to_vec()),
                Object::Reference(ObjectRef::new(99, 0)),
            ]),
        );
        pdf.set_object(ObjectRef::new(20, 0), Object::Dictionary(leaf));
        // Holder: obj 21 is a bare reference to obj 20 (ref → ref → node).
        pdf.set_object(
            ObjectRef::new(21, 0),
            Object::Reference(ObjectRef::new(20, 0)),
        );
        // Root /Kids -> [21 0 R]; 21 is a holder chain, not a direct node.
        let mut root = Dictionary::new();
        root.insert(
            "Kids",
            Object::Array(vec![Object::Reference(ObjectRef::new(21, 0))]),
        );
        let out = read_name_tree(
            &mut pdf,
            Object::Dictionary(root),
            ref_only,
            DEFAULT_MAX_TREE_DEPTH,
        )
        .unwrap();
        assert_eq!(out, vec![(b"k".to_vec(), ObjectRef::new(99, 0))]);
    }

    #[test]
    fn read_name_tree_dedups_distinct_holders_to_same_terminal() {
        // Two distinct holder refs (21, 22) both resolve to the same terminal
        // leaf node (20). This is the holder-form of a direct `[20 0 R 20 0 R]`
        // duplicate: the shared child must be walked once, not once per holder.
        // Keying `visited` on the holder ref would emit the leaf entry twice.
        let mut pdf = empty_pdf();
        let mut leaf = Dictionary::new();
        leaf.insert(
            "Names",
            Object::Array(vec![
                Object::String(b"k".to_vec()),
                Object::Reference(ObjectRef::new(99, 0)),
            ]),
        );
        pdf.set_object(ObjectRef::new(20, 0), Object::Dictionary(leaf));
        // Holders 21 and 22 are bare references to the same terminal node 20.
        pdf.set_object(
            ObjectRef::new(21, 0),
            Object::Reference(ObjectRef::new(20, 0)),
        );
        pdf.set_object(
            ObjectRef::new(22, 0),
            Object::Reference(ObjectRef::new(20, 0)),
        );
        let mut root = Dictionary::new();
        root.insert(
            "Kids",
            Object::Array(vec![
                Object::Reference(ObjectRef::new(21, 0)),
                Object::Reference(ObjectRef::new(22, 0)),
            ]),
        );
        let out = read_name_tree(
            &mut pdf,
            Object::Dictionary(root),
            ref_only,
            DEFAULT_MAX_TREE_DEPTH,
        )
        .unwrap();
        // Exactly one entry: the second holder collapses onto the terminal ref.
        assert_eq!(out, vec![(b"k".to_vec(), ObjectRef::new(99, 0))]);
    }

    #[test]
    fn read_name_tree_skips_inline_dict_kid() {
        // A /Kids array element that is an inline Dictionary leaf (not an
        // indirect reference) must NOT be descended — preserving the legacy
        // reference-only descent. Only Reference kids are followed.
        let mut pdf = empty_pdf();
        let mut inline_leaf = Dictionary::new();
        inline_leaf.insert(
            "Names",
            Object::Array(vec![
                Object::String(b"k".to_vec()),
                Object::Reference(ObjectRef::new(99, 0)),
            ]),
        );
        let mut root = Dictionary::new();
        root.insert("Kids", Object::Array(vec![Object::Dictionary(inline_leaf)]));
        let out = read_name_tree(
            &mut pdf,
            Object::Dictionary(root),
            ref_only,
            DEFAULT_MAX_TREE_DEPTH,
        )
        .unwrap();
        assert!(out.is_empty(), "inline-dict kid must not be descended");
    }

    #[test]
    fn read_name_tree_cycle_terminates() {
        let mut pdf = empty_pdf();
        // Node 30 has /Kids -> [30 0 R] (self-cycle).
        let mut node = Dictionary::new();
        let node_ref = ObjectRef::new(30, 0);
        node.insert("Kids", Object::Array(vec![Object::Reference(node_ref)]));
        pdf.set_object(node_ref, Object::Dictionary(node));
        let out = read_name_tree(
            &mut pdf,
            Object::Reference(node_ref),
            ref_only,
            DEFAULT_MAX_TREE_DEPTH,
        )
        .unwrap();
        assert!(out.is_empty());
    }

    #[test]
    fn read_name_tree_depth_limit_errors() {
        let mut pdf = empty_pdf();
        // Chain of /Kids deeper than the limit.
        // 40 -> 41 -> 42 ...; with max_depth=2 the third level errors.
        let r40 = ObjectRef::new(40, 0);
        let r41 = ObjectRef::new(41, 0);
        let r42 = ObjectRef::new(42, 0);
        for (this, next) in [(r40, r41), (r41, r42)] {
            let mut d = Dictionary::new();
            d.insert("Kids", Object::Array(vec![Object::Reference(next)]));
            pdf.set_object(this, Object::Dictionary(d));
        }
        let mut leaf = Dictionary::new();
        leaf.insert("Names", Object::Array(vec![]));
        pdf.set_object(r42, Object::Dictionary(leaf));
        let err = read_name_tree(&mut pdf, Object::Reference(r40), verbatim, 2);
        assert!(matches!(err, Err(crate::Error::Unsupported(_))));
    }

    #[test]
    fn read_number_tree_resolves_indirect_dict_value() {
        let mut pdf = empty_pdf();
        // Value at ref 50 is a label dict.
        let mut label = Dictionary::new();
        label.insert("S", Object::Name("D".into()));
        let label_ref = ObjectRef::new(50, 0);
        pdf.set_object(label_ref, Object::Dictionary(label));
        let mut leaf = Dictionary::new();
        leaf.insert(
            "Nums",
            Object::Array(vec![
                Object::Integer(0),
                Object::Reference(label_ref), // indirect value -> resolve
                Object::Integer(5),
                Object::Dictionary({
                    let mut d = Dictionary::new();
                    d.insert("S", Object::Name("R".into()));
                    d
                }),
                Object::Integer(9),
                Object::Name("notadict".into()), // value not dict/ref -> decode _ => None -> skipped
            ]),
        );
        let out: Vec<(i64, Dictionary)> = read_number_tree(
            &mut pdf,
            Object::Dictionary(leaf),
            |pdf, v| match v {
                Object::Dictionary(d) => Ok(Some(d)),
                Object::Reference(r) => Ok(pdf.resolve_borrowed(r)?.as_dict().cloned()),
                _ => Ok(None),
            },
            DEFAULT_MAX_TREE_DEPTH,
        )
        .unwrap();
        assert_eq!(out.len(), 2);
        assert_eq!(out[0].0, 0);
        assert_eq!(out[0].1.get("S"), Some(&Object::Name("D".into())));
        assert_eq!(out[1].0, 5);
        assert_eq!(out[1].1.get("S"), Some(&Object::Name("R".into())));
    }

    #[test]
    fn read_number_tree_skips_noninteger_key() {
        let mut pdf = empty_pdf();
        let mut leaf = Dictionary::new();
        leaf.insert(
            "Nums",
            Object::Array(vec![
                Object::Name("oops".into()), // non-integer key -> skip pair
                Object::Integer(1),
                Object::Integer(7),
                Object::Integer(2),
            ]),
        );
        let out: Vec<(i64, i64)> = read_number_tree(
            &mut pdf,
            Object::Dictionary(leaf),
            |_, v| Ok(v.as_integer()),
            DEFAULT_MAX_TREE_DEPTH,
        )
        .unwrap();
        assert_eq!(out, vec![(7, 2)]);
    }

    fn mk_entries(n: usize) -> Vec<(Vec<u8>, Object)> {
        (0..n)
            .map(|i| {
                (
                    format!("{i:03}").into_bytes(),
                    Object::Reference(ObjectRef::new(1000 + i as u32, 0)),
                )
            })
            .collect()
    }

    #[test]
    fn build_name_tree_single_leaf_no_kids() {
        let entries = mk_entries(3);
        let mut next = 0u32;
        let (root, nodes) = build_name_tree(&entries, || {
            next += 1;
            ObjectRef::new(next, 0)
        });
        assert_eq!(nodes.len(), 1);
        assert_eq!(root, nodes[0].0);
        let d = nodes[0].1.as_dict().expect("leaf dict");
        assert!(d.get("Kids").is_none(), "single leaf must not have /Kids");
        assert!(d.get("Names").is_some());
        assert!(
            d.get("Limits").is_none(),
            "single-node root omits /Limits (ISO 32000-2 7.9.6; qpdf)"
        );
    }

    #[test]
    fn build_name_tree_multi_leaf_root_kids_alloc_order() {
        let entries = mk_entries(LEAF_MAX + 1); // 33 -> 2 leaves + root
        let mut next = 0u32;
        let (root, nodes) = build_name_tree(&entries, || {
            next += 1;
            ObjectRef::new(next, 0)
        });
        // Leaves allocated first (1,2), root last (3).
        assert_eq!(nodes.len(), 3);
        assert_eq!(root, ObjectRef::new(3, 0), "root allocated last");
        let root_dict = nodes[2].1.as_dict().expect("root dict");
        let kids = root_dict
            .get("Kids")
            .and_then(Object::as_array)
            .expect("root needs /Kids");
        assert_eq!(kids.len(), 2);
        assert_eq!(kids[0], Object::Reference(ObjectRef::new(1, 0)));
        assert_eq!(kids[1], Object::Reference(ObjectRef::new(2, 0)));
        // Root omits /Limits (ISO 32000-2 7.9.6); both leaves keep it.
        assert!(
            root_dict.get("Limits").is_none(),
            "multi-node root omits /Limits"
        );
        for (_, leaf) in &nodes[..2] {
            let lim = leaf
                .as_dict()
                .unwrap()
                .get("Limits")
                .and_then(Object::as_array)
                .expect("leaf keeps string /Limits");
            assert!(matches!(lim[0], Object::String(_)));
            assert!(matches!(lim[1], Object::String(_)));
        }
    }

    #[test]
    fn read_name_tree_skips_non_string_key() {
        // A /Names leaf whose key is not a PDF string drops that pair; its value
        // is still consumed so the following pair stays aligned.
        let mut pdf = empty_pdf();
        let mut leaf = Dictionary::new();
        leaf.insert(
            "Names",
            Object::Array(vec![
                Object::Integer(7), // non-string key -> skip pair
                Object::Reference(ObjectRef::new(10, 0)),
                Object::String(b"ok".to_vec()),
                Object::Reference(ObjectRef::new(11, 0)),
            ]),
        );
        let out = read_name_tree(
            &mut pdf,
            Object::Dictionary(leaf),
            ref_only,
            DEFAULT_MAX_TREE_DEPTH,
        )
        .unwrap();
        assert_eq!(out, vec![(b"ok".to_vec(), ObjectRef::new(11, 0))]);
    }

    #[test]
    fn read_name_tree_unexpected_root_type_is_empty() {
        // A root that is neither a Dictionary nor a Reference yields no entries.
        let mut pdf = empty_pdf();
        let out = read_name_tree(
            &mut pdf,
            Object::Integer(42),
            verbatim,
            DEFAULT_MAX_TREE_DEPTH,
        )
        .unwrap();
        assert!(out.is_empty());
    }

    #[test]
    fn read_name_tree_kid_resolving_to_non_dict_is_skipped() {
        // A /Kids reference resolving to a non-dictionary object is skipped
        // (malformed node), not an error.
        let mut pdf = empty_pdf();
        let bad_ref = ObjectRef::new(60, 0);
        pdf.set_object(bad_ref, Object::Integer(0));
        let mut root = Dictionary::new();
        root.insert("Kids", Object::Array(vec![Object::Reference(bad_ref)]));
        let out = read_name_tree(
            &mut pdf,
            Object::Dictionary(root),
            verbatim,
            DEFAULT_MAX_TREE_DEPTH,
        )
        .unwrap();
        assert!(out.is_empty());
    }

    #[test]
    fn read_name_tree_odd_length_leaf_drops_orphan() {
        // An odd-length /Names array drops the trailing key with no value.
        let mut pdf = empty_pdf();
        let mut leaf = Dictionary::new();
        leaf.insert(
            "Names",
            Object::Array(vec![
                Object::String(b"a".to_vec()),
                Object::Reference(ObjectRef::new(10, 0)),
                Object::String(b"orphan".to_vec()), // no value -> dropped
            ]),
        );
        let out = read_name_tree(
            &mut pdf,
            Object::Dictionary(leaf),
            ref_only,
            DEFAULT_MAX_TREE_DEPTH,
        )
        .unwrap();
        assert_eq!(out, vec![(b"a".to_vec(), ObjectRef::new(10, 0))]);
    }

    #[test]
    fn read_name_tree_node_without_names_or_kids_is_empty() {
        // A node carrying neither /Names nor /Kids contributes nothing; the walk
        // falls through to the end of walk_tree.
        let mut pdf = empty_pdf();
        let out = read_name_tree(
            &mut pdf,
            Object::Dictionary(Dictionary::new()),
            verbatim,
            DEFAULT_MAX_TREE_DEPTH,
        )
        .unwrap();
        assert!(out.is_empty());
    }

    #[test]
    fn read_number_tree_depth_limit_errors() {
        // The depth guard fires for number trees too; the error propagates out
        // of read_number_tree via `?`.
        let mut pdf = empty_pdf();
        let r70 = ObjectRef::new(70, 0);
        let r71 = ObjectRef::new(71, 0);
        let mut node = Dictionary::new();
        node.insert("Kids", Object::Array(vec![Object::Reference(r71)]));
        pdf.set_object(r70, Object::Dictionary(node));
        // r71 need not exist: with max_depth=1 the guard fires before resolving it.
        let err: Result<Vec<(i64, Object)>> =
            read_number_tree(&mut pdf, Object::Reference(r70), verbatim, 1);
        assert!(matches!(err, Err(crate::Error::Unsupported(_))));
    }

    #[test]
    fn read_number_tree_decode_none_skips_value() {
        // A number-tree value the decode hook rejects (returns None) is skipped.
        let mut pdf = empty_pdf();
        let mut leaf = Dictionary::new();
        leaf.insert(
            "Nums",
            Object::Array(vec![
                Object::Integer(0),
                Object::Name("notanint".into()), // decode -> None -> skip
                Object::Integer(5),
                Object::Integer(99),
            ]),
        );
        let out: Vec<(i64, i64)> = read_number_tree(
            &mut pdf,
            Object::Dictionary(leaf),
            |_, v| Ok(v.as_integer()),
            DEFAULT_MAX_TREE_DEPTH,
        )
        .unwrap();
        assert_eq!(out, vec![(5, 99)]);
    }

    fn mk_num_entries(n: usize) -> Vec<(i64, Object)> {
        (0..n)
            .map(|i| {
                (
                    i as i64 * 10,
                    Object::Reference(ObjectRef::new(1000 + i as u32, 0)),
                )
            })
            .collect()
    }

    #[test]
    fn build_number_tree_single_leaf_no_kids() {
        let entries = mk_num_entries(3);
        let mut next = 0u32;
        let (root, nodes) = build_number_tree(&entries, || {
            next += 1;
            ObjectRef::new(next, 0)
        });
        assert_eq!(nodes.len(), 1);
        assert_eq!(root, nodes[0].0);
        let d = nodes[0].1.as_dict().expect("leaf dict");
        assert!(d.get("Kids").is_none(), "single leaf must not have /Kids");
        assert!(d.get("Nums").is_some());
        assert!(
            d.get("Limits").is_none(),
            "single-node number root omits /Limits"
        );
    }

    #[test]
    fn build_number_tree_multi_leaf_root_kids_alloc_order() {
        let entries = mk_num_entries(LEAF_MAX + 1); // 33 -> 2 leaves + root
        let mut next = 0u32;
        let (root, nodes) = build_number_tree(&entries, || {
            next += 1;
            ObjectRef::new(next, 0)
        });
        assert_eq!(nodes.len(), 3);
        assert_eq!(root, ObjectRef::new(3, 0), "root allocated last");
        let root_dict = nodes[2].1.as_dict().expect("root dict");
        let kids = root_dict
            .get("Kids")
            .and_then(Object::as_array)
            .expect("root needs /Kids");
        assert_eq!(kids.len(), 2);
        assert_eq!(kids[0], Object::Reference(ObjectRef::new(1, 0)));
        // Root omits /Limits (ISO 32000-2 7.9.7); both leaves keep integer /Limits.
        assert!(
            root_dict.get("Limits").is_none(),
            "multi-node root omits /Limits"
        );
        for (_, leaf) in &nodes[..2] {
            let lim = leaf
                .as_dict()
                .unwrap()
                .get("Limits")
                .and_then(Object::as_array)
                .expect("leaf keeps integer /Limits");
            assert!(matches!(lim[0], Object::Integer(_)));
            assert!(matches!(lim[1], Object::Integer(_)));
        }
    }

    #[test]
    fn build_number_tree_round_trips_via_read_number_tree() {
        let mut pdf = empty_pdf();
        let entries: Vec<(i64, Object)> =
            vec![(0, Object::Integer(100)), (5, Object::Integer(200))];
        let mut next = 500u32;
        let (root, nodes) = build_number_tree(&entries, || {
            next += 1;
            ObjectRef::new(next, 0)
        });
        for (r, n) in nodes {
            pdf.set_object(r, n);
        }
        let out: Vec<(i64, i64)> = read_number_tree(
            &mut pdf,
            Object::Reference(root),
            |_, v| Ok(v.as_integer()),
            DEFAULT_MAX_TREE_DEPTH,
        )
        .unwrap();
        assert_eq!(out, vec![(0, 100), (5, 200)]);
    }

    #[test]
    fn build_number_tree_multi_node_round_trips_via_read_number_tree() {
        // LEAF_MAX + 1 entries force a multi-node tree (2 leaves under a
        // /Kids-only root with no /Limits). Reading back from that root proves
        // the reader traverses a Limits-less root and enumerates every entry in
        // order via /Kids -> /Nums.
        let mut pdf = empty_pdf();
        let entries = mk_num_entries(LEAF_MAX + 1);
        let expected: Vec<(i64, ObjectRef)> = entries
            .iter()
            .map(|(k, v)| (*k, v.as_ref_id().unwrap()))
            .collect();
        let mut next = 0u32;
        let (root, nodes) = build_number_tree(&entries, || {
            next += 1;
            ObjectRef::new(next, 0)
        });
        assert!(nodes.len() > 1, "expected a multi-node tree");
        assert!(
            nodes[nodes.len() - 1]
                .1
                .as_dict()
                .unwrap()
                .get("Limits")
                .is_none(),
            "multi-node root must omit /Limits"
        );
        for (r, n) in nodes {
            pdf.set_object(r, n);
        }
        let out: Vec<(i64, ObjectRef)> = read_number_tree(
            &mut pdf,
            Object::Reference(root),
            ref_only,
            DEFAULT_MAX_TREE_DEPTH,
        )
        .unwrap();
        assert_eq!(out, expected);
    }

    #[test]
    fn build_name_tree_multi_node_round_trips_via_read_name_tree() {
        // Name-tree analogue: LEAF_MAX + 1 entries force a /Kids-only root
        // without /Limits. Reading back from the root recovers all entries in
        // order, proving the Limits-less root is traversed via /Kids -> /Names.
        let mut pdf = empty_pdf();
        let entries = mk_entries(LEAF_MAX + 1);
        let expected: Vec<(Vec<u8>, ObjectRef)> = entries
            .iter()
            .map(|(k, v)| (k.clone(), v.as_ref_id().unwrap()))
            .collect();
        let mut next = 0u32;
        let (root, nodes) = build_name_tree(&entries, || {
            next += 1;
            ObjectRef::new(next, 0)
        });
        assert!(nodes.len() > 1, "expected a multi-node tree");
        assert!(
            nodes[nodes.len() - 1]
                .1
                .as_dict()
                .unwrap()
                .get("Limits")
                .is_none(),
            "multi-node root must omit /Limits"
        );
        for (r, n) in nodes {
            pdf.set_object(r, n);
        }
        let out: Vec<(Vec<u8>, ObjectRef)> = read_name_tree(
            &mut pdf,
            Object::Reference(root),
            ref_only,
            DEFAULT_MAX_TREE_DEPTH,
        )
        .unwrap();
        assert_eq!(out, expected);
    }
}