flpdf 0.6.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
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
//! Catalog-first object renumbering for plain rewrite, matching qpdf's order.
//!
//! qpdf correspondence: QPDFWriter.cc object renumbering shared by plain and linearized writers.
//!
//! qpdf renumbers every object it writes into a deterministic order rather than
//! preserving the input object numbers. This module reproduces that order so
//! that flpdf's plain rewrite can become byte-identical to
//! `qpdf --static-id --object-streams=disable`.
//!
//! The order is a breadth-first traversal of the object graph:
//!
//! - The BFS queue is seeded from the trimmed trailer: `/Root` first, then the
//!   remaining trailer entries that are indirect references, visited in
//!   lexicographic key order. The keys `/ID`, `/Encrypt`, `/Prev`, `/Root`
//!   (already seeded) and `/Size` (an integer) are skipped. This places the
//!   document `/Info` dictionary at object number 2, since it is not reachable
//!   from the `/Catalog`.
//! - Each dequeued object is resolved and the objects it references are
//!   enqueued, descending into dictionary entries in lexicographic byte order
//!   of their keys and array elements in order. For streams only the stream
//!   dictionary is walked; the data bytes are opaque. A stream's indirect
//!   `/Length` edge is not followed (qpdf removes `/Length` before enqueueing a
//!   stream's children, since it re-emits a direct `/Length`), so a holder
//!   reachable only through it is dropped — except in qdf mode, which keeps the
//!   indirect holder.
//! - The first time an object is enqueued fixes its new number; later
//!   encounters are ignored.
//! - New numbers are the visitation order `1..=N`, all with generation 0.
//! - Objects unreachable from the seed never receive a number (qpdf drops them
//!   by default).

#[cfg(test)]
use std::collections::HashMap;
use std::collections::{BTreeSet, VecDeque};
use std::io::{Read, Seek};

use crate::object_ref::ObjectRef;
use crate::parser::MAX_PARSE_DEPTH;
#[cfg(test)]
use crate::qpdf_obj_gen::QpdfObjGen;
#[cfg(test)]
use crate::writer::object_streams::sort_source_backed_members_qpdf_order;
#[cfg(test)]
use crate::writer::object_streams::ObjectStreamGroup;
use crate::Error;
use crate::Pdf;
#[cfg(test)]
use crate::XrefEntry;

type LinearizedStreamParameterOmission<'a> =
    Option<&'a dyn Fn(&crate::ObjectHandle) -> crate::Result<bool>>;

/// Maps an original object reference to its assigned new reference.
///
/// Implemented by both renumber schemes ([`CanonicalCatalogFirstRenumber`] for plain
/// rewrite, [`ObjectStreamRenumber`] for object-stream output) so that
/// `renumber_qpdf_refs_in_place` can rewrite an object's internal references
/// under either numbering without duplication.
#[cfg(test)]
pub(crate) trait NewNumberLookup {
    /// Return the new reference assigned to `original`, if it was reachable.
    fn new_for_original(&self, original: ObjectRef) -> Option<ObjectRef>;
}

#[cfg(test)]
impl NewNumberLookup for ObjectStreamRenumber {
    fn new_for_original(&self, original: ObjectRef) -> Option<ObjectRef> {
        self.old_to_new.get(&original).copied()
    }
}

#[cfg(test)]
impl NewNumberLookup for HashMap<ObjectRef, ObjectRef> {
    fn new_for_original(&self, original: ObjectRef) -> Option<ObjectRef> {
        self.get(&original).copied()
    }
}

/// Return the source object references that actually own compressed xref
/// entries. qpdf derives this mapping from its xref table
/// (`QPDF.cc:2381-2390`), not from an object's dictionary `/Type`; an ordinary
/// orphan stream merely typed `/ObjStm` remains a preserve-unreferenced object.
#[cfg(test)]
fn qpdf_source_objstm_containers<R: Read + Seek>(pdf: &Pdf<R>) -> BTreeSet<ObjectRef> {
    pdf.source_xref_entries()
        .into_values()
        .filter_map(|entry| match entry {
            XrefEntry::Compressed { stream, .. } => Some(ObjectRef::new(stream, 0)),
            XrefEntry::Free { .. } | XrefEntry::Uncompressed { .. } => None,
        })
        .collect()
}

/// Return a stable writer-local key for a raw qpdf object identity that cannot
/// be represented by `ObjectRef`. It is never registered in the source Pdf.
#[cfg(test)]
fn writer_local_raw_ref(raw: QpdfObjGen) -> Option<ObjectRef> {
    let object = u32::try_from(raw.get_obj()).ok()?;
    if object == 0 {
        return None;
    }
    Some(ObjectRef::new(u32::MAX - object, 0))
}

/// Catalog-first numbering over the live [`crate::ObjectHandle`] graph.
///
/// This is the writer's canonical traversal boundary. It resolves and inspects
/// ObjectHandles directly, so an in-place handle mutation is observed without
/// creating a separate legacy `Object` snapshot. The enqueue order and
/// null-visible edge rules mirror `QPDFWriter::enqueueObject` and
/// `enqueueObjectsStandard` (`QPDFWriter.cc:1072-1141,2916-2924`).
#[cfg(test)]
pub(crate) struct CanonicalCatalogFirstRenumber {
    old_to_new: HashMap<ObjectRef, ObjectRef>,
    order: Vec<ObjectRef>,
    #[cfg(test)]
    raw_sources: HashMap<ObjectRef, QpdfObjGen>,
}

#[cfg(test)]
impl NewNumberLookup for CanonicalCatalogFirstRenumber {
    fn new_for_original(&self, original: ObjectRef) -> Option<ObjectRef> {
        self.old_to_new.get(&original).copied()
    }
}

#[cfg(test)]
impl CanonicalCatalogFirstRenumber {
    /// Return the new number assigned to an original object reference.
    pub(crate) fn new_for_original(&self, original: ObjectRef) -> Option<ObjectRef> {
        self.old_to_new.get(&original).copied()
    }

    pub(crate) fn pairs(&self) -> impl Iterator<Item = (ObjectRef, ObjectRef)> + '_ {
        self.order
            .iter()
            .enumerate()
            .map(|(index, &source)| (ObjectRef::new(index as u32 + 1, 0), source))
    }

    #[cfg(test)]
    pub(crate) fn raw_source_for(&self, source: ObjectRef) -> Option<QpdfObjGen> {
        self.raw_sources.get(&source).copied()
    }

    pub(crate) fn build_qpdf<R: Read + Seek>(
        pdf: &mut Pdf<R>,
        skip_length: bool,
        preserve_unreferenced_objects: bool,
        removed_refs: &BTreeSet<ObjectRef>,
    ) -> crate::Result<Self> {
        let root_ref = pdf.root_ref();
        let direct_root = if root_ref.is_none() {
            let candidate = pdf.trailer_key_handle(b"Root");
            if candidate.try_is_null()? {
                return Err(Error::Unsupported(
                    "plain rewrite: trailer has no /Root".to_string(),
                ));
            }
            Some(pdf.root_handle()?)
        } else {
            None
        };
        let mut raw_sources = HashMap::new();
        let mut seeds = if preserve_unreferenced_objects {
            let mut seeds = Vec::new();
            let source_objstm_containers = qpdf_source_objstm_containers(pdf);
            for handle in pdf.get_all_objects()? {
                let object_ref = if let Some(object_ref) = handle.object_ref() {
                    object_ref
                } else if let Some(raw) = handle.qpdf_obj_gen().filter(|raw| raw.is_indirect()) {
                    // cov:ignore-start: an indirect raw qpdf identity with
                    // object number zero is excluded by `is_indirect`.
                    let Some(local_ref) = writer_local_raw_ref(raw) else {
                        continue;
                    };
                    // cov:ignore-end
                    raw_sources.insert(local_ref, raw);
                    local_ref
                } else {
                    // cov:ignore-start: qpdf's complete object cache yields
                    // indirect handles only.
                    continue;
                    // cov:ignore-end
                };
                if object_ref.number == 0
                    || removed_refs.contains(&object_ref)
                    || source_objstm_containers.contains(&object_ref)
                {
                    continue;
                }
                seeds.push(object_ref);
            }
            seeds
        } else {
            Vec::new()
        };
        if let Some(root) = root_ref {
            seeds.push(root);
        } else if let Some(root) = &direct_root {
            // qpdf's enqueueObject recurses through a direct Catalog instead
            // of assigning it an object number. Its indirect descendants are
            // nevertheless numbered in the Catalog's dictionary order.
            collect_canonical_enqueue_refs(pdf, root, 0, skip_length, &mut seeds)?;
            // cov:ignore: direct-root traversal is exercised by the writer tests; LLVM maps this successful-call terminator to a zero-count continuation region.
        } // cov:ignore: direct-root traversal executes above; LLVM places this branch-exit counter on an uninstrumented continuation line.

        let trailer = pdf.trailer();
        let trailer_entries = trailer.try_as_dictionary()?.unwrap_or_default();
        for (key, value) in trailer_entries {
            if matches!(
                key.as_slice(),
                b"/ID" | b"/Encrypt" | b"/Prev" | b"/Root" | b"/Size"
            ) {
                continue;
            }
            // QPDFWriter::getTrimmedTrailer obtains the trailer's visible keys
            // before enqueueing their values. A top-level trailer reference
            // that resolves to null is therefore omitted entirely, while an
            // array-valued trailer entry still reaches the recursive collector
            // so its null elements retain their positions/identities.
            if !value.try_is_null()? {
                collect_canonical_enqueue_refs(pdf, &value, 0, skip_length, &mut seeds)?;
                // cov:ignore: successful trailer traversal is covered; llvm-cov attributes this continuation to the defensive error path
            }
        }

        let mut old_to_new = HashMap::new();
        let mut order = Vec::new();
        let mut queue = VecDeque::new();
        for seed in seeds {
            if !removed_refs.contains(&seed) {
                enqueue(seed, &mut old_to_new, &mut order, &mut queue);
            }
        }

        while let Some(source) = queue.pop_front() {
            let handle = raw_sources
                .get(&source)
                .map(|raw| pdf.get_object_handle_by_raw_identity(raw.get_obj(), raw.get_gen()))
                .unwrap_or_else(|| pdf.get_object_handle(source));
            let mut found = Vec::new();
            collect_canonical_children(pdf, &handle, 0, skip_length, &mut found)?;
            for reference in found {
                if !removed_refs.contains(&reference) {
                    enqueue(reference, &mut old_to_new, &mut order, &mut queue);
                }
            }
        }

        Ok(Self {
            old_to_new,
            order,
            #[cfg(test)]
            raw_sources,
        })
    }
}

pub(crate) fn collect_canonical_enqueue_refs<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    handle: &crate::ObjectHandle,
    depth: usize,
    skip_length: bool,
    found: &mut Vec<ObjectRef>,
) -> crate::Result<()> {
    collect_canonical_enqueue_refs_with_linearized_omission(
        pdf,
        handle,
        depth,
        skip_length,
        found,
        None,
    )
}

fn collect_canonical_enqueue_refs_with_linearized_omission<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    handle: &crate::ObjectHandle,
    depth: usize,
    skip_length: bool,
    found: &mut Vec<ObjectRef>,
    stream_parameter_omission: LinearizedStreamParameterOmission<'_>,
) -> crate::Result<()> {
    if let Some(object_ref) = handle.object_ref() {
        ensure_canonical_owner(pdf, handle)?;
        // qpdf treats `0 0 R` as a direct null at every child position
        // (QPDFObjectHandle.cc:344-350); it is not an object to enqueue.
        if object_ref.number != 0 {
            found.push(object_ref);
        }
        return Ok(());
    }
    collect_canonical_children_with_linearized_omission(
        pdf,
        handle,
        depth,
        skip_length,
        found,
        stream_parameter_omission,
    )
}

#[cfg(test)]
pub(crate) fn collect_canonical_children<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    handle: &crate::ObjectHandle,
    depth: usize,
    skip_length: bool,
    found: &mut Vec<ObjectRef>,
) -> crate::Result<()> {
    collect_canonical_children_with_linearized_omission(
        pdf,
        handle,
        depth,
        skip_length,
        found,
        None,
    )
}

fn collect_canonical_children_with_linearized_omission<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    handle: &crate::ObjectHandle,
    depth: usize,
    skip_length: bool,
    found: &mut Vec<ObjectRef>,
    stream_parameter_omission: LinearizedStreamParameterOmission<'_>,
) -> crate::Result<()> {
    if depth > MAX_PARSE_DEPTH {
        return Err(Error::Unsupported(
            "plain rewrite: inline object nesting exceeds MAX_PARSE_DEPTH during canonical enqueue collection"
                .to_string(),
        ));
    }
    if let Some(items) = handle.try_as_array()? {
        for item in items {
            collect_canonical_enqueue_refs_with_linearized_omission(
                pdf,
                &item,
                depth + 1,
                skip_length,
                found,
                stream_parameter_omission,
            )?; // cov:ignore: successful array traversal is covered; llvm-cov attributes this continuation to the defensive error path
        }
        return Ok(());
    }
    if let Some(entries) = handle.try_as_dictionary()? {
        for (_, value) in entries {
            if !value.try_is_null()? {
                collect_canonical_enqueue_refs_with_linearized_omission(
                    pdf,
                    &value,
                    depth + 1,
                    skip_length,
                    found,
                    stream_parameter_omission,
                )?; // cov:ignore: successful dictionary traversal is covered; llvm-cov attributes this continuation to the defensive error path
            }
        }
        return Ok(());
    }
    if let Some(stream_dict) = handle.as_stream_dict() {
        let skip_stream_parameters = stream_parameter_omission
            .map(|predicate| predicate(handle))
            .transpose()?
            .unwrap_or(false);
        if let Some(entries) = stream_dict.try_as_dictionary()? {
            for (key, value) in entries {
                if skip_length && key.as_slice() == b"/Length" {
                    continue;
                }
                if skip_stream_parameters && matches!(key.as_slice(), b"/Filter" | b"/DecodeParms")
                {
                    continue;
                }
                if !value.try_is_null()? {
                    collect_canonical_enqueue_refs_with_linearized_omission(
                        pdf,
                        &value,
                        depth + 1,
                        skip_length,
                        found,
                        stream_parameter_omission,
                    )?; // cov:ignore: successful stream traversal is covered; llvm-cov attributes this continuation to the defensive error path
                }
            }
        } // cov:ignore: llvm-cov maps this if-let exit to an unhit synthetic branch; its body is covered
    }
    Ok(())
}

pub(crate) fn ensure_canonical_owner<R: Read + Seek>(
    pdf: &Pdf<R>,
    handle: &crate::ObjectHandle,
) -> crate::Result<()> {
    if !pdf.is_canonical_object_handle(handle) {
        return Err(Error::Internal(
            "QPDFObjectHandle from different QPDF found while writing.  Use QPDF::copyForeignObject to add objects from another file."
                .to_string(),
        ));
    }
    Ok(())
}

/// Compute the set of object references reachable from the trailer roots,
/// matching qpdf's reachability garbage collection of the linearized object
/// universe.
///
/// Seeds from `/Root` plus every qpdf-visible trailer entry — **including
/// `/Encrypt`**, excluding `/Prev`, `/Size`, `/ID` (and `/Root`, already
/// seeded) — then breadth-first walks with qpdf's position-dependent null
/// visibility. Arrays retain indirect null identities; dictionary and stream
/// values that resolve to null contribute no edge. When `skip_length` is set
/// (always, for linearize: the linearized writer directizes every `/Length`), a
/// stream's indirect `/Length` edge is not followed, so an object reachable
/// ONLY through that dead edge is correctly absent — matching qpdf's
/// reachability GC.
///
/// Unlike the plain rewrite's Catalog-first numbering, `/Encrypt` IS part of
/// the seed set: the linearized object universe must retain the encryption
/// dictionary and its closure (the plain rewrite numbers `/Encrypt` in a
/// separate slot, hence its omission there).
///
/// # Errors
///
/// Returns [`Error::Unsupported`] when the trailer has no `/Root` or inline
/// nesting exceeds [`MAX_PARSE_DEPTH`] (via the canonical enqueue collector), and propagates
/// [`Error::Io`] / [`Error::Parse`] / [`Error::Encrypted`] from resolving
/// objects during the walk.
pub(crate) fn reachable_object_set_with_stream_parameters<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    skip_length: bool,
    skipped_stream_parameter_streams: &BTreeSet<crate::qpdf_obj_gen::QpdfObjGen>,
) -> crate::Result<BTreeSet<ObjectRef>> {
    let root = pdf
        .root_ref()
        .ok_or_else(|| Error::Unsupported("reachability: trailer has no /Root".to_string()))?;
    let mut seeds: Vec<ObjectRef> = vec![root];
    let trailer_entries = pdf.trailer().try_as_dictionary()?.unwrap_or_default();
    let skip_stream_parameters = |handle: &crate::ObjectHandle| -> crate::Result<bool> {
        Ok(handle
            .qpdf_obj_gen()
            .is_some_and(|object_gen| skipped_stream_parameter_streams.contains(&object_gen)))
    };
    for (key, value) in trailer_entries {
        // /Encrypt is intentionally NOT skipped: it is part of the live universe.
        // /Prev, /Size, /ID, /Root are not object roots of the document graph.
        if matches!(key.as_slice(), b"/ID" | b"/Prev" | b"/Root" | b"/Size") {
            continue;
        }
        // Recurse into direct dict/array trailer values so a nested indirect ref
        // (e.g. inside a direct `/Info` dict) is seeded, matching qpdf's recursive
        // trailer enqueue. A bare reference yields exactly one seed as before.
        if !value.try_is_null()? {
            collect_canonical_enqueue_refs_with_linearized_omission(
                pdf,
                &value,
                0,
                skip_length,
                &mut seeds,
                Some(&skip_stream_parameters),
            )?; // cov:ignore: LLVM maps this covered canonical trailer traversal terminator to a zero-count continuation region
        }
    }

    let mut reachable: BTreeSet<ObjectRef> = BTreeSet::new();
    let mut queue: VecDeque<ObjectRef> = VecDeque::new();
    for seed in seeds {
        if reachable.insert(seed) {
            queue.push_back(seed);
        }
    }
    while let Some(cur) = queue.pop_front() {
        let handle = pdf.get_object_handle(cur);
        let mut found = Vec::new();
        collect_canonical_children_with_linearized_omission(
            pdf,
            &handle,
            0,
            skip_length,
            &mut found,
            Some(&skip_stream_parameters),
        )?; // cov:ignore: LLVM maps this covered canonical reachability traversal terminator to a zero-count continuation region
        for r in found {
            if reachable.insert(r) {
                queue.push_back(r);
            }
        }
    }
    Ok(reachable)
}

/// Indirect references that qpdf "resurrects" as `null` body objects rather than
/// dropping: a reference that resolves to null (missing, free, real-null, or a
/// holder chain ending in null, with `number > 0`) **reached through a surviving
/// edge** — i.e. as an ARRAY element, or nested inside a non-null dict/array
/// value.
///
/// This is the array half of qpdf's null-resolving normalization (the dict-value
/// half drops the key). The walk is **drop-aware**: a null-resolving reference
/// reached ONLY as a dictionary value is omitted (qpdf drops that key, so the
/// object becomes unreachable and is garbage-collected, not resurrected). Object
/// 0 (`0 0 R`) is excluded — qpdf inlines it as a direct `null`, not an indirect
/// null object.
///
/// # Errors
///
/// This set is used by linearization's all-ref and object-user planning. ObjStm
/// Generate membership has its own qpdf DFS
/// ([`crate::writer::object_streams::get_compressible_objgens`]) and must not append
/// this set a second time.
///
/// Propagates resolve errors and the [`MAX_PARSE_DEPTH`] guard from the walk.
/// Null-resolving references to retain, minus any identities removed by the
/// current qpdf operation's compressible-object walk.
///
/// `removed_refs` is the exact stale-generation set returned by
/// `getCompressibleObjGens` parity logic. Checking this once-built set during
/// the null-edge walk avoids the former O(null edges × live refs) rescan while
/// preserving standard enqueue semantics when the set is empty.
pub(crate) fn resurrectable_null_refs_excluding<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    removed_refs: &BTreeSet<ObjectRef>,
) -> crate::Result<BTreeSet<ObjectRef>> {
    let root = pdf
        .root_ref()
        .ok_or_else(|| Error::Unsupported("resurrectable: trailer has no /Root".to_string()))?;

    let mut result: BTreeSet<ObjectRef> = BTreeSet::new();
    let mut visited: BTreeSet<ObjectRef> = BTreeSet::new();
    let mut queue: VecDeque<ObjectRef> = VecDeque::from([root]);

    // Seed from the trailer (dict context): visible roots are followed; a
    // null-resolving trailer ref is a dropped key, not resurrected.
    let trailer_entries = pdf.trailer().try_as_dictionary()?.unwrap_or_default();
    for (key, value) in trailer_entries {
        if matches!(key.as_slice(), b"/ID" | b"/Prev" | b"/Root" | b"/Size") {
            continue;
        }
        let mut follow: Vec<ObjectRef> = Vec::new();
        let mut state = ResurrectableWalkState {
            follow: &mut follow,
            result: &mut result,
            removed_refs,
        };
        walk_resurrectable_handle(&value, 0, false, true, &mut state)?;
        queue.extend(follow);
    }

    while let Some(cur) = queue.pop_front() {
        if !visited.insert(cur) {
            continue;
        }
        let handle = pdf.get_object_handle(cur);
        let mut follow: Vec<ObjectRef> = Vec::new();
        let mut state = ResurrectableWalkState {
            follow: &mut follow,
            result: &mut result,
            removed_refs,
        };
        walk_resurrectable_handle(&handle, 0, false, false, &mut state)?;
        for r in follow {
            if !visited.contains(&r) {
                queue.push_back(r);
            }
        }
    }
    Ok(result)
}

/// Drop-aware handle walk for [`resurrectable_null_refs_excluding`].
/// Distinguishes array position (`in_array`) from dict-value position: a
/// null-resolving reference (`number > 0`) is collected into `result` only
/// when it sits in an array (a surviving edge); a dict/stream value that is
/// null-resolving is skipped entirely (qpdf drops that key). Object 0 is
/// ignored.
struct ResurrectableWalkState<'a> {
    follow: &'a mut Vec<ObjectRef>,
    result: &'a mut BTreeSet<ObjectRef>,
    removed_refs: &'a BTreeSet<ObjectRef>,
}

fn walk_resurrectable_handle(
    handle: &crate::ObjectHandle,
    depth: usize,
    in_array: bool,
    edge_context: bool,
    state: &mut ResurrectableWalkState<'_>,
) -> crate::Result<()> {
    if depth > MAX_PARSE_DEPTH {
        return Err(Error::Unsupported(
            "linearization: inline nesting exceeds MAX_PARSE_DEPTH during resurrectable walk"
                .to_string(),
        ));
    }

    let is_null = handle.try_is_null()?;
    // `object_ref()` is the identity of a canonical handle, not a stored
    // reference value. A handle fetched from the document cache therefore
    // keeps its identity after resolving to a dictionary or array and must
    // still be traversed. Only a child reached through an edge contributes
    // that identity as the edge reference.
    let edge_ref = edge_context.then_some(handle.object_ref()).flatten();

    if is_null {
        if in_array {
            if let Some(reference) = edge_ref {
                // Generate and source-ObjStm Preserve directize only refs the
                // operation's compressible walk removed. Standard enqueue
                // passes an empty set and retains the stale identity until the
                // linearization duplicate-generation guard rejects it.
                if reference.number > 0 && !state.removed_refs.contains(&reference) {
                    state.result.insert(reference);
                }
            }
        }
        return Ok(());
    }

    if let Some(reference) = edge_ref {
        if reference.number > 0 {
            state.follow.push(reference);
        }
        return Ok(());
    }

    if let Some(elements) = handle.try_as_array()? {
        for element in elements {
            walk_resurrectable_handle(&element, depth + 1, true, true, state)?;
        }
        return Ok(());
    }

    if let Some(entries) = handle.try_as_dictionary()? {
        for (_key, value) in entries {
            walk_resurrectable_handle(&value, depth + 1, false, true, state)?;
        }
        return Ok(());
    }

    if let Some(stream_dict) = handle.as_stream_dict() {
        if let Some(entries) = stream_dict.try_as_dictionary()? {
            for (_key, value) in entries {
                walk_resurrectable_handle(&value, depth + 1, false, true, state)?;
            }
        }
    }
    Ok(())
}

/// Object-stream renumbering: the Catalog-first BFS extended with qpdf's
/// object-stream branch (`QPDFWriter::enqueueObject` QPDFWriter.cc:1097-1118 +
/// `assignCompressedObjectNumbers` 1057). When the walk first reaches a member
/// of an object stream, the stream's container is numbered immediately, then
/// every member of that container is numbered consecutively in ascending source
/// object order (qpdf stores members in a `std::set<QPDFObjGen>`). Containers
/// are therefore numbered in the order their first member is encountered.
///
/// The container membership comes from the caller (the `get_compressible_objgens`
/// traversal split into even groups); this type only assigns the numbers in
/// qpdf's order.
//
// Shared by Preserve and Generate plain-writer planning.
#[cfg(test)]
pub(crate) struct ObjectStreamRenumber {
    old_to_new: HashMap<ObjectRef, ObjectRef>,
    #[cfg(test)]
    raw_sources: HashMap<ObjectRef, QpdfObjGen>,
    /// New object number assigned to each input group's container, in group
    /// order. `container_new[i]` is `None` only if group `i` was never reached.
    container_new: Vec<Option<u32>>,
}

#[cfg(test)]
impl ObjectStreamRenumber {
    /// The container object number assigned to input group `group_index`, or
    /// `None` if the index is out of range or that group was never reached.
    /// This preserves the group-to-number correspondence even when some group
    /// went unreached.
    pub(crate) fn container_number(&self, group_index: usize) -> Option<u32> {
        self.container_new.get(group_index).copied().flatten()
    }

    #[cfg(test)]
    pub(crate) fn raw_source_for(&self, source: ObjectRef) -> Option<QpdfObjGen> {
        self.raw_sources.get(&source).copied()
    }

    /// Iterate `(new_ref, old_ref)` pairs for every reachable input object.
    /// Source-backed containers, object-stream members, raw preserve seeds, and
    /// plain objects are included. Synthetic containers have no original ref;
    /// obtain their numbers via [`Self::container_number`]. Yield order is
    /// unspecified (backed by a hash map); callers that need ordering sort by
    /// the new number.
    pub(crate) fn pairs(&self) -> impl Iterator<Item = (ObjectRef, ObjectRef)> + '_ {
        self.old_to_new.iter().map(|(&old, &new)| (new, old))
    }

    pub(crate) fn build<R: Read + Seek>(
        pdf: &mut Pdf<R>,
        groups: &[ObjectStreamGroup],
        skip_length: bool,
        removed_refs: &BTreeSet<ObjectRef>,
        preserve_unreferenced_objects: bool,
    ) -> crate::Result<Self> {
        Self::build_with_seed_policy(
            pdf,
            groups,
            skip_length,
            removed_refs,
            preserve_unreferenced_objects,
        )
    }

    fn build_with_seed_policy<R: Read + Seek>(
        pdf: &mut Pdf<R>,
        groups: &[ObjectStreamGroup],
        skip_length: bool,
        removed_refs: &BTreeSet<ObjectRef>,
        preserve_unreferenced_objects: bool,
    ) -> crate::Result<Self> {
        let mut member_to_group: HashMap<ObjectRef, usize> = HashMap::new();
        let mut source_to_group: HashMap<ObjectRef, usize> = HashMap::new();
        let mut groups_sorted: Vec<Vec<ObjectRef>> = Vec::with_capacity(groups.len());
        for (gi, group) in groups.iter().enumerate() {
            let mut sorted = group.members().to_vec();
            if sorted.is_empty() {
                return Err(Error::Unsupported(format!(
                    "object-stream renumber: group {gi} has no members"
                )));
            }
            // qpdf's source-backed Preserve map stores each container's
            // members in `std::set<QPDFObjGen>` and `writeObjectStream` walks
            // that set directly (`QPDFWriter.cc:1621-1758`). A multi-source
            // target therefore uses the recorded original-object provenance,
            // while an ordinary source uses its local ObjGen directly.
            if matches!(group, ObjectStreamGroup::SourceBacked { .. }) {
                sort_source_backed_members_qpdf_order(pdf, &mut sorted);
            } else if pdf.writer_object_order.is_some() {
                sorted.sort_unstable_by_key(|object_ref| pdf.writer_object_order_key(*object_ref));
            } else {
                sorted.sort_unstable_by_key(|r| (r.number, r.generation));
            }
            for &m in &sorted {
                if let Some(previous) = member_to_group.insert(m, gi) {
                    return Err(Error::Unsupported(format!(
                        "object-stream renumber: member {m} occurs in groups {previous} and {gi}"
                    )));
                }
            }
            let source = match group {
                ObjectStreamGroup::SourceBacked { source, .. }
                | ObjectStreamGroup::Generated { source, .. } => *source,
            };
            if let Some(previous) = source_to_group.insert(source, gi) {
                return Err(Error::Unsupported(format!(
                    "object-stream renumber: source container {source} occurs in groups {previous} and {gi}"
                )));
            }
            groups_sorted.push(sorted);
        }
        if let Some(source) = source_to_group
            .keys()
            .find(|source| member_to_group.contains_key(source))
        {
            return Err(Error::Unsupported(format!(
                "object-stream renumber: source container {source} is also a member"
            )));
        }
        let generated_container_sources: BTreeSet<ObjectRef> = groups
            .iter()
            .filter_map(|group| match group {
                ObjectStreamGroup::Generated { source, .. } => Some(*source),
                ObjectStreamGroup::SourceBacked { .. } => None,
            })
            .collect();
        let mut old_to_new: HashMap<ObjectRef, ObjectRef> = HashMap::new();
        let mut container_new: Vec<Option<u32>> = vec![None; groups.len()];
        let mut next: u32 = 1;
        let mut queue: VecDeque<RenumberWork> = VecDeque::new();

        // Seeds match the plain Catalog-first walk: `/Root` first, then the
        // remaining indirect trailer entries in lexicographic key order. The
        // skipped keys mirror qpdf's `getTrimmedTrailer` (QPDFWriter.cc), which
        // removes `/ID`, `/Encrypt`, `/Prev`, etc. before the enqueue walk. In
        // particular `/Encrypt` is intentionally NOT seeded here: like qpdf,
        // flpdf numbers and emits the encryption dictionary through a separate
        // path (the encryption writer emits it as a plaintext indirect object),
        // not through the renumber walk. Seeding it here would assign it a
        // walk-order number and diverge from qpdf.
        let root_ref = pdf.root_ref();
        let direct_root = if root_ref.is_none() {
            let candidate = pdf.trailer_key_handle(b"Root");
            if candidate.try_is_null()? {
                return Err(Error::Unsupported(
                    "object-stream renumber: trailer has no /Root".to_string(),
                ));
            }
            Some(pdf.root_handle()?)
        } else {
            None
        };
        let mut raw_sources = HashMap::new();
        let mut seeds: Vec<ObjectRef> = if preserve_unreferenced_objects {
            let mut seeds = Vec::new();
            for handle in pdf.get_all_objects()? {
                let source = if let Some(object_ref) = handle.object_ref() {
                    object_ref
                } else if let Some(raw) = handle.qpdf_obj_gen().filter(|raw| raw.is_indirect()) {
                    // cov:ignore-start: an indirect raw qpdf identity with
                    // object number zero is excluded by `is_indirect`.
                    let Some(local_ref) = writer_local_raw_ref(raw) else {
                        continue;
                    };
                    // cov:ignore-end
                    raw_sources.insert(local_ref, raw);
                    local_ref
                } else {
                    // cov:ignore-start: every parsed indirect raw identity has
                    // an object number accepted by writer_local_raw_ref.
                    continue;
                    // cov:ignore-end
                };
                if !removed_refs.contains(&source) && !generated_container_sources.contains(&source)
                {
                    seeds.push(source);
                }
            }
            seeds
        } else {
            Vec::new()
        };
        if let Some(root) = root_ref {
            seeds.push(root);
        } else if let Some(root) = &direct_root {
            // cov:ignore-start: LLVM maps this covered direct-root call to a zero-count continuation region.
            collect_canonical_enqueue_refs(pdf, root, 0, skip_length, &mut seeds)?;
            // cov:ignore-end
        } // cov:ignore: direct-root traversal executes above; LLVM places this branch-exit counter on an uninstrumented continuation line.
        let trailer = pdf.trailer();
        let trailer_entries = trailer.try_as_dictionary()?.unwrap_or_default();
        for (key, value) in trailer_entries {
            if matches!(
                key.as_slice(),
                b"/ID" | b"/Encrypt" | b"/Prev" | b"/Root" | b"/Size"
            ) {
                continue;
            }
            if value.try_is_null()? {
                continue;
            }
            // Recurse into direct dict/array trailer values so a nested indirect
            // ref is seeded, matching qpdf's recursive trailer enqueue. A bare
            // reference yields exactly one seed as before. The live handle
            // graph applies qpdf's null-visible dictionary rule while walking.
            collect_canonical_enqueue_refs(pdf, &value, 0, skip_length, &mut seeds)?;
            // cov:ignore: successful trailer traversal is covered; llvm-cov attributes this continuation to the defensive error path
        }
        seeds.retain(|reference| !removed_refs.contains(reference));

        for seed in seeds {
            enqueue_object_stream(
                seed,
                groups,
                &member_to_group,
                &source_to_group,
                &groups_sorted,
                &mut old_to_new,
                &mut container_new,
                &mut next,
                &mut queue,
            );
        }

        while let Some(work) = queue.pop_front() {
            match work {
                RenumberWork::Ordinary(cur) => {
                    let handle = raw_sources
                        .get(&cur)
                        .map(|raw| {
                            pdf.get_object_handle_by_raw_identity(raw.get_obj(), raw.get_gen())
                        })
                        .unwrap_or_else(|| pdf.get_object_handle(cur));
                    let mut found = Vec::new();
                    collect_canonical_children(pdf, &handle, 0, skip_length, &mut found)?; // cov:ignore: successful object-stream traversal is covered; llvm-cov attributes this continuation to the defensive error path
                    found.retain(|reference| !removed_refs.contains(reference));
                    for reference in found {
                        enqueue_object_stream(
                            reference,
                            groups,
                            &member_to_group,
                            &source_to_group,
                            &groups_sorted,
                            &mut old_to_new,
                            &mut container_new,
                            &mut next,
                            &mut queue,
                        );
                    }
                }
                RenumberWork::SourceContainer(source) => {
                    // qpdf's object-stream membership comes from the source
                    // xref table and survives replaceObject(source, null).
                    // writeObjectStream then treats that indirect null as a
                    // generated placeholder: it rebuilds the same container
                    // but has no original dictionary from which to copy
                    // /Extends (QPDF.cc:2381-2390;
                    // QPDFWriter.cc:1621-1625,1731-1739,1939-1965).
                    if removed_refs.contains(&source) {
                        continue;
                    }
                    let handle = pdf.get_object_handle(source);
                    if handle.try_is_null()? {
                        continue;
                    }
                    let stream_dict = handle.as_stream_dict().ok_or_else(|| {
                        Error::Unsupported(format!(
                            "object-stream renumber: source container {source} is not a stream"
                        ))
                    })?;
                    let extends = stream_dict.try_get_key(b"/Extends")?.object_ref();
                    if let Some(extends) = extends.filter(|extends| !removed_refs.contains(extends))
                    {
                        enqueue_object_stream(
                            extends,
                            groups,
                            &member_to_group,
                            &source_to_group,
                            &groups_sorted,
                            &mut old_to_new,
                            &mut container_new,
                            &mut next,
                            &mut queue,
                        );
                    }
                }
            }
        }

        Ok(Self {
            old_to_new,
            container_new,
            #[cfg(test)]
            raw_sources,
        })
    }
}

#[derive(Clone, Copy, Debug)]
#[cfg(test)]
enum RenumberWork {
    Ordinary(ObjectRef),
    SourceContainer(ObjectRef),
}

/// Number a plain object directly, or activate its source-backed/synthetic
/// object-stream group from either the source container or any member.
#[allow(clippy::too_many_arguments)]
#[cfg(test)]
fn enqueue_object_stream(
    r: ObjectRef,
    groups: &[ObjectStreamGroup],
    member_to_group: &HashMap<ObjectRef, usize>,
    source_to_group: &HashMap<ObjectRef, usize>,
    groups_sorted: &[Vec<ObjectRef>],
    old_to_new: &mut HashMap<ObjectRef, ObjectRef>,
    container_new: &mut [Option<u32>],
    next: &mut u32,
    queue: &mut VecDeque<RenumberWork>,
) {
    if old_to_new.contains_key(&r) {
        return;
    }
    let group_index = member_to_group
        .get(&r)
        .or_else(|| source_to_group.get(&r))
        .copied();
    match group_index {
        Some(gi) => {
            // Activation inserts the source and every member into old_to_new,
            // so the leading map guard makes a second activation impossible.
            let container = *next;
            container_new[gi] = Some(container);
            *next += 1;

            let source = match &groups[gi] {
                ObjectStreamGroup::SourceBacked { source, .. }
                | ObjectStreamGroup::Generated { source, .. } => {
                    old_to_new.insert(*source, ObjectRef::new(container, 0));
                    Some(*source)
                }
            };
            for &m in &groups_sorted[gi] {
                old_to_new.insert(m, ObjectRef::new(*next, 0));
                *next += 1;
                queue.push_back(RenumberWork::Ordinary(m));
            }
            if let Some(source) = source {
                queue.push_back(RenumberWork::SourceContainer(source));
            }
        }
        None => {
            old_to_new.insert(r, ObjectRef::new(*next, 0));
            *next += 1;
            queue.push_back(RenumberWork::Ordinary(r));
        }
    }
}

/// Assign `original` a new number on first encounter and enqueue it for the BFS
/// walk. Repeated calls for the same reference are no-ops.
#[cfg(test)]
fn enqueue(
    original: ObjectRef,
    old_to_new: &mut HashMap<ObjectRef, ObjectRef>,
    order: &mut Vec<ObjectRef>,
    queue: &mut VecDeque<ObjectRef>,
) {
    if old_to_new.contains_key(&original) {
        return;
    }
    // Keyed on the full ObjectRef (number + generation); flpdf inputs are
    // generation 0 throughout, whereas qpdf keys on object number alone. Revisit
    // this key if mixed-generation inputs ever reach the renumber walk.
    let new_ref = ObjectRef::new(order.len() as u32 + 1, 0);
    old_to_new.insert(original, new_ref);
    order.push(original);
    queue.push_back(original);
}

#[cfg(test)]
mod tests {
    use super::{
        collect_canonical_children, ensure_canonical_owner, walk_resurrectable_handle,
        writer_local_raw_ref, NewNumberLookup, ObjectStreamRenumber, ResurrectableWalkState,
    };
    use crate::parser::MAX_PARSE_DEPTH;
    use crate::qpdf_obj_gen::QpdfObjGen;
    use crate::writer::object_streams::ObjectStreamGroup;
    use crate::{Error, ObjectHandle, ObjectRef, Pdf};
    use std::collections::{BTreeMap, BTreeSet};
    use std::io::Cursor;

    fn raw_stream_pdf() -> Vec<u8> {
        let mut bytes = b"%PDF-1.4\n".to_vec();
        let catalog_offset = bytes.len();
        bytes.extend_from_slice(b"1 0 obj\n<< /Type /Catalog >>\nendobj\n");
        let stream_offset = bytes.len();
        bytes.extend_from_slice(
            b"5 65536 obj\n<< /Length 3 >>\nstream\nabc\nendstream\nendobj\n%tail\n",
        );
        let xref_offset = bytes.len();
        bytes.extend_from_slice(b"xref\n0 6\n0000000000 65535 f \n");
        bytes.extend_from_slice(format!("{catalog_offset:010} 00000 n \n").as_bytes());
        bytes.extend_from_slice(b"0000000000 00000 f \n0000000000 00000 f \n0000000000 00000 f \n");
        bytes.extend_from_slice(format!("{stream_offset:010} 65536 n \n").as_bytes());
        bytes.extend_from_slice(
            format!("trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n{xref_offset}\n%%EOF\n")
                .as_bytes(),
        );
        bytes
    }

    #[test]
    fn writer_local_raw_ref_rejects_qpdf_object_zero() {
        assert_eq!(writer_local_raw_ref(QpdfObjGen::new(0, 65_536)), None);
    }

    #[test]
    fn writer_local_raw_ref_keeps_a_raw_generation_stream_unregistered() {
        let mut pdf = Pdf::open(Cursor::new(raw_stream_pdf())).expect("open raw stream PDF");
        let handle = pdf
            .get_all_objects()
            .unwrap()
            .into_iter()
            .find(|handle| handle.qpdf_obj_gen() == Some(QpdfObjGen::new(5, 65_536)))
            .expect("raw stream cache entry");
        let raw = handle.qpdf_obj_gen().expect("raw identity");
        assert_eq!(
            writer_local_raw_ref(raw),
            Some(ObjectRef::new(u32::MAX - 5, 0))
        );
        assert_eq!(pdf.get_all_objects().unwrap().len(), 2);
    }

    #[test]
    fn preserve_walk_reuses_raw_qpdf_identity_for_an_ordinary_seed() {
        let mut pdf = Pdf::open(Cursor::new(raw_stream_pdf())).expect("open raw stream PDF");
        let local_ref = writer_local_raw_ref(QpdfObjGen::new(5, 65_536)).unwrap();

        let renumber = ObjectStreamRenumber::build(&mut pdf, &[], false, &BTreeSet::new(), true)
            .expect("preserve walk should resolve raw source seeds");

        assert_eq!(
            renumber.raw_source_for(local_ref),
            Some(QpdfObjGen::new(5, 65_536))
        );
    }

    #[test]
    fn writer_foreign_owner_is_a_qpdf_logic_error() {
        let mut first = Pdf::empty().expect("create first empty PDF");
        let second = Pdf::empty().expect("create second empty PDF");
        let root_ref = first.root_ref().expect("first PDF has a root");
        let foreign_root = first.get_object_handle(root_ref);

        let error = ensure_canonical_owner(&second, &foreign_root)
            .expect_err("a foreign object must be rejected by the writer");
        assert!(matches!(
            error,
            Error::Internal(message)
                if message == "QPDFObjectHandle from different QPDF found while writing.  Use QPDF::copyForeignObject to add objects from another file."
        ));
    }

    #[test]
    fn object_stream_renumber_rejects_a_duplicate_source_container() {
        let mut pdf = Pdf::empty().expect("create object-stream owner");
        let source = pdf
            .make_indirect_object_handle(ObjectHandle::null())
            .expect("create source container")
            .object_ref()
            .unwrap();
        let first = pdf
            .make_indirect_object_handle(ObjectHandle::integer(1))
            .expect("create first member")
            .object_ref()
            .unwrap();
        let second = pdf
            .make_indirect_object_handle(ObjectHandle::integer(2))
            .expect("create second member")
            .object_ref()
            .unwrap();
        let groups = [
            ObjectStreamGroup::Generated {
                source,
                members: vec![first],
            },
            ObjectStreamGroup::Generated {
                source,
                members: vec![second],
            },
        ];

        let error = ObjectStreamRenumber::build(&mut pdf, &groups, false, &BTreeSet::new(), false)
            .err()
            .expect("duplicate source containers must fail before traversal");

        assert!(
            matches!(error, Error::Unsupported(message) if message.contains("source container") && message.contains("groups 0 and 1"))
        );
    }

    #[test]
    fn generated_object_stream_renumber_uses_recorded_writer_order() {
        let mut pdf = Pdf::empty().expect("create generated object-stream owner");
        let source = pdf
            .make_indirect_object_handle(ObjectHandle::null())
            .expect("create generated source container")
            .object_ref()
            .unwrap();
        let first = pdf
            .make_indirect_object_handle(ObjectHandle::integer(1))
            .expect("create first generated member")
            .object_ref()
            .unwrap();
        let second = pdf
            .make_indirect_object_handle(ObjectHandle::integer(2))
            .expect("create second generated member")
            .object_ref()
            .unwrap();
        let mut order = BTreeMap::new();
        order.insert(
            first,
            crate::pdf::WriterObjectOrderKey::foreign(ObjectRef::new(2, 0)),
        );
        order.insert(
            second,
            crate::pdf::WriterObjectOrderKey::foreign(ObjectRef::new(1, 0)),
        );
        pdf.set_writer_object_order(order);
        let groups = [ObjectStreamGroup::Generated {
            source,
            members: vec![first, second],
        }];

        let renumber =
            ObjectStreamRenumber::build(&mut pdf, &groups, false, &BTreeSet::new(), true)
                .expect("generated object-stream order must be accepted");
        assert!(renumber.new_for_original(first).is_some());
        assert!(renumber.new_for_original(second).is_some());
    }

    #[test]
    fn resurrectable_walk_rejects_programmatic_depth_beyond_parser_limit() {
        let mut follow = Vec::new();
        let mut result = BTreeSet::new();
        let removed_refs = BTreeSet::new();
        let mut state = ResurrectableWalkState {
            follow: &mut follow,
            result: &mut result,
            removed_refs: &removed_refs,
        };
        let error = walk_resurrectable_handle(
            &ObjectHandle::null(),
            MAX_PARSE_DEPTH + 1,
            false,
            false,
            &mut state,
        )
        .expect_err("the resurrectable walk has a parser-depth guard");
        assert!(error.to_string().contains("MAX_PARSE_DEPTH"));
    }

    #[test]
    fn canonical_children_propagate_resolution_errors() {
        let mut pdf = Pdf::empty().expect("create a document for the walk");
        let unresolved = ObjectHandle::new_indirect_unresolved(ObjectRef::new(91, 0), -1);
        let mut found = Vec::new();

        let error = collect_canonical_children(&mut pdf, &unresolved, 0, false, &mut found)
            .expect_err("an unresolved child must remain a fallible traversal");
        assert!(matches!(
            error,
            Error::Internal(message) if message == "object 91 0 belongs to a dropped PDF"
        ));
    }

    #[test]
    fn resurrectable_walk_propagates_resolution_errors() {
        let unresolved = ObjectHandle::new_indirect_unresolved(ObjectRef::new(92, 0), -1);
        let mut follow = Vec::new();
        let mut result = BTreeSet::new();
        let removed_refs = BTreeSet::new();
        let mut state = ResurrectableWalkState {
            follow: &mut follow,
            result: &mut result,
            removed_refs: &removed_refs,
        };

        let error = walk_resurrectable_handle(&unresolved, 0, false, false, &mut state)
            .expect_err("the resurrectable walk must propagate resolution errors");
        assert!(matches!(
            error,
            Error::Internal(message) if message == "object 92 0 belongs to a dropped PDF"
        ));
    }
}