flpdf 0.1.5

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
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
//! Page-tree traversal helpers.
//!
//! Iterates the document's `/Pages` tree in the order described by ISO 32000-1 §7.7.3.2
//! and yields the `ObjectRef` of every leaf `Page` node. The walker tolerates broken
//! cycles (each node is visited at most once) and bounds its recursion via a configurable
//! depth limit, since malformed PDFs occasionally embed self-referential page trees.

use crate::filters::decode_stream_data;
use crate::{Dictionary, Error, Object, ObjectRef, Pdf, Result, Stream};
use std::collections::BTreeSet;
use std::io::{Read, Seek};

/// Default recursion limit for [`page_refs`].
///
/// Real-world PDFs almost always fit within a couple of dozen levels; the limit is
/// generous enough for legitimate documents while still preventing pathological inputs
/// from causing unbounded recursion.
pub const DEFAULT_MAX_PAGE_TREE_DEPTH: usize = 100;

/// Return every `Page` object in document order using [`DEFAULT_MAX_PAGE_TREE_DEPTH`].
///
/// Returns [`Error::Missing`] if the catalog or `/Pages` entry is absent. Returns
/// [`Error::Unsupported`] if the page tree exceeds the depth limit or the catalog is
/// not a dictionary.
///
/// # Examples
///
/// ```no_run
/// use std::fs::File;
/// use std::io::BufReader;
/// use flpdf::{pages, Pdf};
///
/// let mut pdf = Pdf::open(BufReader::new(File::open("input.pdf")?))?;
/// let pages = pages::page_refs(&mut pdf)?;
/// println!("{} pages", pages.len());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn page_refs<R: Read + Seek>(pdf: &mut Pdf<R>) -> Result<Vec<ObjectRef>> {
    page_refs_with_max_depth(pdf, DEFAULT_MAX_PAGE_TREE_DEPTH)
}

/// Like [`page_refs`] but with a caller-supplied recursion limit.
pub fn page_refs_with_max_depth<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    max_depth: usize,
) -> Result<Vec<ObjectRef>> {
    PageWalk::with_max_depth(pdf, max_depth)?.collect()
}

/// Return the decoded content-stream bytes for a single `Page` object.
///
/// The page's `/Contents` entry may be absent (returns `Ok(Vec::new())`), a single
/// `Stream` or `Reference → Stream`, or an `Array` of such references.  Every stream
/// is decoded through its filter pipeline via [`crate::filters::decode_stream_data`]
/// and the resulting byte slices are concatenated with a single ASCII space (`b' '`)
/// between each part, which is safe as a token boundary for PDF content-stream
/// tokenisers (matching the convention used by lopdf and qpdf).
///
/// # Errors
///
/// - [`Error::Unsupported`] when `page_ref` does not resolve to a dictionary with
///   `/Type /Page`, or when a `/Contents` element is not a stream.
/// - Any [`Error`] that [`Pdf::resolve`] or [`crate::filters::decode_stream_data`]
///   may return.
///
/// # Examples
///
/// ```no_run
/// use std::fs::File;
/// use std::io::BufReader;
/// use flpdf::{pages, Pdf};
///
/// let mut pdf = Pdf::open(BufReader::new(File::open("input.pdf")?))?;
/// let page_refs = pages::page_refs(&mut pdf)?;
/// if let Some(&page_ref) = page_refs.first() {
///     let content = pages::page_content_bytes(&mut pdf, page_ref)?;
///     println!("{} content bytes", content.len());
/// }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn page_content_bytes<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    page_ref: ObjectRef,
) -> Result<Vec<u8>> {
    // Resolve the page object itself.
    let page_obj = pdf.resolve_borrowed(page_ref)?;
    let Some(page_dict) = page_obj.as_dict() else {
        return Err(Error::Unsupported(format!(
            "object {page_ref} is not a dictionary, cannot extract /Contents"
        )));
    };
    // Verify the /Type is /Page.
    match page_dict.get("Type") {
        Some(Object::Name(name)) if name.as_slice() == b"Page" => {}
        Some(Object::Name(name)) => {
            return Err(Error::Unsupported(format!(
                "object {page_ref} has /Type /{}, expected /Page",
                String::from_utf8_lossy(name)
            )));
        }
        Some(_) => {
            return Err(Error::Unsupported(format!(
                "object {page_ref} has a non-name /Type entry"
            )));
        }
        None => {
            return Err(Error::Unsupported(format!(
                "object {page_ref} has no /Type entry"
            )));
        }
    }

    // Extract the /Contents entry.  Absence is not an error (empty page).
    let contents = match page_dict.get("Contents").cloned() {
        None => return Ok(Vec::new()),
        Some(c) => c,
    };

    // Collect every stream that /Contents references.
    let streams: Vec<Stream> = collect_content_streams(pdf, &contents, page_ref)?;

    if streams.is_empty() {
        return Ok(Vec::new());
    }

    // Decode each stream and join with a single space separator.
    let mut result: Vec<u8> = Vec::new();
    for (i, stream) in streams.into_iter().enumerate() {
        let decoded = decode_stream_data(&stream.dict, &stream.data)?;
        if i > 0 {
            result.push(b' ');
        }
        result.extend_from_slice(&decoded);
    }
    Ok(result)
}

/// Resolve a `/Contents` value into a flat list of `Stream`s, handling all three
/// legal forms: a direct `Stream`, a `Reference` to a stream, or an `Array` of
/// `Reference`s (or direct streams).
fn collect_content_streams<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    contents: &Object,
    page_ref: ObjectRef,
) -> Result<Vec<Stream>> {
    match contents {
        // Direct inline stream — valid per spec (§7.8.2 note) and used in test PDFs.
        Object::Stream(s) => Ok(vec![s.clone()]),

        // Indirect reference — must resolve to a stream.
        Object::Reference(r) => {
            let resolved = pdf.resolve_borrowed(*r)?;
            match resolved {
                Object::Stream(s) => Ok(vec![s.clone()]),
                _ => Err(Error::Unsupported(format!(
                    "/Contents reference {r} on page {page_ref} does not resolve to a stream"
                ))),
            }
        }

        // Array — each element must be a Reference to a stream (or a direct stream).
        Object::Array(elems) => {
            let mut streams = Vec::with_capacity(elems.len());
            for elem in elems {
                match elem {
                    Object::Reference(r) => {
                        let resolved = pdf.resolve_borrowed(*r)?;
                        match resolved {
                            Object::Stream(s) => streams.push(s.clone()),
                            _ => {
                                return Err(Error::Unsupported(format!(
                                    "/Contents array element {r} on page {page_ref} does not resolve to a stream"
                                )));
                            }
                        }
                    }
                    Object::Stream(s) => streams.push(s.clone()),
                    other => {
                        let type_name = object_type_name(other);
                        return Err(Error::Unsupported(format!(
                            "/Contents array element of type {type_name} on page {page_ref} is not a stream or reference"
                        )));
                    }
                }
            }
            Ok(streams)
        }

        other => Err(Error::Unsupported(format!(
            "/Contents entry on page {page_ref} has unexpected type {}",
            object_type_name(other)
        ))),
    }
}

/// Coalesce a page's `/Contents` array into a single stream.
///
/// When a PDF page's `/Contents` entry is an array of two or more stream
/// references, this function:
///
/// 1. Decodes each stream through its filter pipeline.
/// 2. Joins the decoded bytes with a single `b'\n'` separator between segments
///    (matching qpdf's `--coalesce-contents` semantics — ISO 32000-1 §7.8.2
///    allows any whitespace between concatenated content streams, and newline
///    is qpdf's choice).
/// 3. Stores the result as a new indirect `Stream` object (no filter applied —
///    re-encoding is the responsibility of the write path / flpdf-9hc.12.5).
/// 4. Updates the page dictionary's `/Contents` entry to reference the new
///    single stream object.
///
/// **No `q`/`Q` framing is inserted.** ISO 32000-1 §7.8.2 specifies that
/// adjacent content streams are concatenated as if they formed a single stream;
/// the standard does not require wrapping. The acceptance criterion
/// "nested q/Q balance preserved" means that the `\n` separator guarantees
/// tokens from adjacent segments are never lexically merged (e.g. a trailing
/// number `12` and a leading digit `0` would form `120` without the newline).
///
/// # No-op cases
///
/// - `/Contents` absent → returns `Ok(())` (empty page, unchanged).
/// - `/Contents` is a single reference or a direct `Stream` → returns `Ok(())`
///   (already a single stream, no mutation needed).
/// - `/Contents` is an array with exactly **one** element → treated as a
///   single stream (no mutation needed).
///
/// Only when `/Contents` is an array with **two or more** elements does the
/// function perform a write.
///
/// # Errors
///
/// Propagates any error from [`Pdf::resolve`] or
/// [`crate::filters::decode_stream_data`], or returns [`Error::Unsupported`]
/// when the page object or its `/Contents` elements have unexpected types.
///
/// # Examples
///
/// ```no_run
/// use std::fs::File;
/// use std::io::BufReader;
/// use flpdf::{pages, Pdf};
///
/// let mut pdf = Pdf::open(BufReader::new(File::open("input.pdf")?))?;
/// let page_refs = pages::page_refs(&mut pdf)?;
/// for page_ref in page_refs {
///     pages::coalesce_page_contents(&mut pdf, page_ref)?;
/// }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn coalesce_page_contents<R: Read + Seek>(pdf: &mut Pdf<R>, page_ref: ObjectRef) -> Result<()> {
    // ── 1. Resolve the page dictionary ────────────────────────────────────────
    let page_obj = pdf.resolve_borrowed(page_ref)?;
    let Some(page_dict) = page_obj.as_dict() else {
        return Err(Error::Unsupported(format!(
            "object {page_ref} is not a dictionary, cannot coalesce /Contents"
        )));
    };

    // Verify /Type is /Page (same check as page_content_bytes).
    match page_dict.get("Type") {
        Some(Object::Name(name)) if name.as_slice() == b"Page" => {}
        Some(Object::Name(name)) => {
            return Err(Error::Unsupported(format!(
                "object {page_ref} has /Type /{}, expected /Page",
                String::from_utf8_lossy(name)
            )));
        }
        Some(_) => {
            return Err(Error::Unsupported(format!(
                "object {page_ref} has a non-name /Type entry"
            )));
        }
        None => {
            return Err(Error::Unsupported(format!(
                "object {page_ref} has no /Type entry"
            )));
        }
    }

    // ── 2. Extract /Contents; skip if absent or already a single stream ───────
    let contents = match page_dict.get("Contents").cloned() {
        None => return Ok(()), // empty page
        Some(c) => c,
    };

    // Collect references: only an Array with ≥2 elements triggers coalesce.
    let refs: Vec<Object> = match &contents {
        Object::Array(elems) if elems.len() >= 2 => elems.clone(),
        // Single-element array, direct Stream, or Reference: no-op.
        _ => return Ok(()),
    };

    // ── 3. Decode each stream and concatenate with '\n' separators ─────────────
    let mut coalesced: Vec<u8> = Vec::new();
    // Preserve the first content stream's non-filter dictionary entries so
    // stream-level metadata in the input is not silently dropped. Keys that
    // describe the encoded form are stripped because the coalesced data is
    // raw decoded bytes (the writer re-derives Length / re-applies a filter).
    let mut new_dict: Option<Dictionary> = None;
    for (i, elem) in refs.iter().enumerate() {
        let stream: Stream = match elem {
            Object::Reference(r) => {
                let resolved = pdf.resolve_borrowed(*r)?;
                match resolved {
                    Object::Stream(s) => s.clone(),
                    _ => {
                        return Err(Error::Unsupported(format!(
                            "/Contents array element {r} on page {page_ref} does not resolve to a stream"
                        )));
                    }
                }
            }
            Object::Stream(s) => s.clone(),
            other => {
                let type_name = object_type_name(other);
                return Err(Error::Unsupported(format!(
                    "/Contents array element of type {type_name} on page {page_ref} is not a stream or reference"
                )));
            }
        };

        if i == 0 {
            let mut d = stream.dict.clone();
            // Stripped: encode-form keys (Filter/DecodeParms/DP/Length/DL)
            // and external-data keys (F/FFilter/FDecodeParms) — see the
            // stream-dictionary entries in ISO 32000-1 Table 5. The
            // coalesced payload is embedded raw decoded bytes, so an
            // external file specification or external-filter chain would
            // be inconsistent with it.
            for key in [
                "Filter",
                "DecodeParms",
                "DP",
                "Length",
                "DL",
                "F",
                "FFilter",
                "FDecodeParms",
            ] {
                d.remove(key);
            }
            new_dict = Some(d);
        }

        let decoded = decode_stream_data(&stream.dict, &stream.data)?;
        if i > 0 {
            coalesced.push(b'\n');
        }
        coalesced.extend_from_slice(&decoded);
    }

    // ── 4. Allocate a fresh object number for the coalesced stream ─────────────
    let new_num: u32 = pdf
        .object_refs()
        .iter()
        .map(|r| r.number)
        .max()
        .unwrap_or(0)
        .checked_add(1)
        .ok_or_else(|| {
            Error::Unsupported(
                "coalesce_page_contents: object number overflow allocating new stream".to_string(),
            )
        })?;
    let new_stream_ref = ObjectRef::new(new_num, 0);

    // ── 5. Build the new Stream (no filter: raw decoded bytes; writer handles re-encode) ─
    let new_stream = Stream::new(new_dict.unwrap_or_default(), coalesced);
    pdf.set_object(new_stream_ref, Object::Stream(new_stream));

    // ── 6. Re-resolve the page dictionary (it may have been evicted) and patch /Contents ─
    let page_obj2 = pdf.resolve_borrowed(page_ref)?;
    let Some(mut new_page_dict) = page_obj2.as_dict().cloned() else {
        return Err(Error::Unsupported(format!(
            "object {page_ref} unexpectedly not a dictionary after coalesce"
        )));
    };
    new_page_dict.insert("Contents", Object::Reference(new_stream_ref));
    pdf.set_object(page_ref, Object::Dictionary(new_page_dict));

    Ok(())
}

fn object_type_name(obj: &Object) -> &'static str {
    match obj {
        Object::Null => "null",
        Object::Boolean(_) => "boolean",
        Object::Integer(_) => "integer",
        Object::Real(_) => "real",
        Object::Name(_) => "name",
        Object::String(_) => "string",
        Object::Array(_) => "array",
        Object::Dictionary(_) => "dictionary",
        Object::Stream(_) => "stream",
        Object::Reference(_) => "reference",
    }
}

/// Return the `/Resources` dictionary for a page, walking up the `/Parent` chain
/// until one is found. Uses [`DEFAULT_MAX_PAGE_TREE_DEPTH`] as the depth limit.
///
/// Inheritable attributes in PDF are defined in ISO 32000-1 §7.7.3.4. `/Resources`
/// is one of them: if a `Page` node does not carry its own `/Resources`, the nearest
/// ancestor `Pages` node that has one should be used.
///
/// Returns `Ok(None)` when no node in the chain carries a `/Resources` entry.
///
/// # Errors
///
/// - [`Error::Unsupported`] if the depth limit is exceeded (indicates a malformed or
///   extremely deeply nested document).
/// - Any [`Error`] propagated from [`Pdf::resolve`].
pub fn resolve_inherited_resources<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    page_ref: ObjectRef,
) -> Result<Option<Dictionary>> {
    resolve_inherited_resources_with_max_depth(pdf, page_ref, DEFAULT_MAX_PAGE_TREE_DEPTH)
}

/// Like [`resolve_inherited_resources`] but with a caller-supplied recursion limit.
pub fn resolve_inherited_resources_with_max_depth<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    page_ref: ObjectRef,
    max_depth: usize,
) -> Result<Option<Dictionary>> {
    let mut seen: BTreeSet<ObjectRef> = BTreeSet::new();
    let mut current = page_ref;
    let mut depth: usize = 0;

    loop {
        if depth >= max_depth {
            return Err(Error::Unsupported(format!(
                "page tree depth exceeds maximum of {max_depth} at {current}"
            )));
        }

        // Cycle guard: if we have already visited this node, stop.
        if !seen.insert(current) {
            return Ok(None);
        }

        let node_obj = pdf.resolve_borrowed(current)?;
        let Some(dict) = node_obj.as_dict() else {
            // Not a dictionary — cannot walk further.
            return Ok(None);
        };

        let resources_val = dict.get("Resources").cloned();
        let parent_val = dict.get("Parent").cloned();

        // Check for /Resources on this node. Per PDF §7.3.9, a null value is
        // equivalent to the key being absent — so Object::Null (and references
        // that resolve to null) fall through to the /Parent chain.
        if let Some(resources_val) = resources_val {
            match resources_val {
                Object::Null => {}
                Object::Dictionary(d) => return Ok(Some(d)),
                Object::Reference(r) => {
                    let resolved = pdf.resolve_borrowed(r)?;
                    match resolved {
                        Object::Null => {}
                        Object::Dictionary(d) => return Ok(Some(d.clone())),
                        _ => {
                            return Err(Error::Unsupported(format!(
                                "/Resources reference {r} on node {current} does not resolve to a dictionary"
                            )));
                        }
                    }
                }
                _ => {
                    return Err(Error::Unsupported(format!(
                        "/Resources entry on node {current} has unexpected type"
                    )));
                }
            }
        }

        // No /Resources here — try the /Parent. A null /Parent is equivalent
        // to no /Parent at all (PDF §7.3.9), so stop walking in either case.
        let parent_val = match parent_val {
            Some(Object::Null) | None => return Ok(None),
            Some(v) => v,
        };

        match parent_val {
            Object::Reference(r) => {
                current = r;
                depth += 1;
            }
            // Direct dictionary as /Parent is non-standard; treat as absent.
            _ => return Ok(None),
        }
    }
}

/// An iterator over every leaf `Page` object-reference in the document's `/Pages`
/// tree, yielding refs in document order (ISO 32000-1 §7.7.3.2).
///
/// Each node is visited at most once (tracked via a `BTreeSet`) so cycles in
/// malformed documents are silently skipped. On the first resolve failure or
/// depth-limit breach the iterator emits `Some(Err(...))` and is then fused
/// — all subsequent calls return `None`.
///
/// # Construction
///
/// Use [`PageWalk::new`] or [`PageWalk::with_max_depth`].
///
/// # Example
///
/// ```no_run
/// use std::fs::File;
/// use std::io::BufReader;
/// use flpdf::{pages::PageWalk, Pdf};
///
/// let mut pdf = Pdf::open(BufReader::new(File::open("input.pdf")?))?;
/// for page_ref in PageWalk::new(&mut pdf)? {
///     let page_ref = page_ref?;
///     println!("page: {page_ref}");
/// }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub struct PageWalk<'a, R: Read + Seek> {
    pdf: &'a mut Pdf<R>,
    /// Stack of `(node_ref, depth)` yet to be visited.
    stack: Vec<(ObjectRef, usize)>,
    seen: BTreeSet<ObjectRef>,
    max_depth: usize,
    /// Set to `true` after yielding `Err`; causes all subsequent calls to return `None`.
    done: bool,
}

impl<'a, R: Read + Seek> PageWalk<'a, R> {
    /// Create a `PageWalk` using [`DEFAULT_MAX_PAGE_TREE_DEPTH`].
    ///
    /// Returns [`Error::Missing`] if the catalog or `/Pages` entry is absent.
    /// Returns [`Error::Unsupported`] if the catalog is not a dictionary.
    pub fn new(pdf: &'a mut Pdf<R>) -> Result<Self> {
        Self::with_max_depth(pdf, DEFAULT_MAX_PAGE_TREE_DEPTH)
    }

    /// Create a `PageWalk` with a caller-supplied recursion limit.
    pub fn with_max_depth(pdf: &'a mut Pdf<R>, max_depth: usize) -> Result<Self> {
        let catalog_ref = pdf.root_ref().ok_or(Error::Missing("/Root"))?;
        let catalog = pdf.resolve_borrowed(catalog_ref)?;
        let Some(catalog) = catalog.as_dict() else {
            return Err(Error::Unsupported(format!(
                "document catalog {catalog_ref} is not a dictionary"
            )));
        };
        let pages_ref = catalog.get_ref("Pages").ok_or(Error::Missing("/Pages"))?;
        Ok(PageWalk {
            pdf,
            stack: vec![(pages_ref, 0)],
            seen: BTreeSet::new(),
            max_depth,
            done: false,
        })
    }
}

impl<'a, R: Read + Seek> Iterator for PageWalk<'a, R> {
    type Item = Result<ObjectRef>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }

        loop {
            let (node, depth) = self.stack.pop()?;

            if depth >= self.max_depth {
                self.done = true;
                return Some(Err(Error::Unsupported(format!(
                    "page tree depth exceeds maximum of {} at {}",
                    self.max_depth, node
                ))));
            }

            if !self.seen.insert(node) {
                continue; // cycle guard: already visited
            }

            let node_obj = match self.pdf.resolve_borrowed(node) {
                Ok(o) => o,
                Err(e) => {
                    self.done = true;
                    return Some(Err(e));
                }
            };

            let Some(dict) = node_obj.as_dict() else {
                continue; // non-dictionary: skip silently
            };

            let node_type = dict
                .get("Type")
                .and_then(|value| match value {
                    Object::Name(value) => Some(value.as_slice()),
                    _ => None,
                })
                .unwrap_or(&[]);

            if node_type == b"Pages" {
                if let Some(kids) = dict.get("Kids").and_then(Object::as_array) {
                    // Push in reverse order so that the first kid is popped first.
                    for kid in kids.iter().rev() {
                        if let Object::Reference(r) = kid {
                            self.stack.push((*r, depth + 1));
                        }
                    }
                }
                continue;
            }

            if node_type == b"Page" {
                return Some(Ok(node));
            }

            // Unknown or absent /Type: skip silently.
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::filters::encode_stream_data;
    use crate::Dictionary;
    use std::io::Cursor;

    // -----------------------------------------------------------------------
    // Minimal PDF builder helpers
    // -----------------------------------------------------------------------

    /// Build a minimal PDF with one page whose /Contents is supplied by the
    /// caller. `extra_objects` is appended verbatim (for additional stream
    /// objects); `contents_entry` is placed in the Page dictionary.
    ///
    /// Object layout:
    ///   1 0 R  Catalog
    ///   2 0 R  Pages
    ///   3 0 R  Page (with /Contents = contents_entry)
    ///   4+ 0 R extra objects
    fn build_pdf_with_contents(contents_entry: &str, extra_objects: &[(u32, &str)]) -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");

        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

        let off2 = pdf.len() as u64;
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");

        let off3 = pdf.len() as u64;
        let page_obj = if contents_entry.is_empty() {
            "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n".to_string()
        } else {
            format!(
                "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents {contents_entry} >>\nendobj\n"
            )
        };
        pdf.extend_from_slice(page_obj.as_bytes());

        // Extra stream objects
        let mut extra_offsets: Vec<(u32, u64)> = Vec::new();
        for (num, body) in extra_objects.iter() {
            let off = pdf.len() as u64;
            extra_offsets.push((*num, off));
            pdf.extend_from_slice(body.as_bytes());
        }

        let xref_start = pdf.len() as u64;
        let max_num = extra_offsets.iter().map(|(n, _)| *n).max().unwrap_or(3);
        let total = max_num as usize + 1; // 0..=max_num
        let mut xref = format!("xref\n0 {total}\n0000000000 65535 f \n");
        xref.push_str(&format!("{:010} 00000 n \n", off1));
        xref.push_str(&format!("{:010} 00000 n \n", off2));
        xref.push_str(&format!("{:010} 00000 n \n", off3));
        for i in 4..=max_num {
            if let Some((_, off)) = extra_offsets.iter().find(|(n, _)| *n == i) {
                xref.push_str(&format!("{:010} 00000 n \n", off));
            } else {
                xref.push_str("0000000000 65535 f \n");
            }
        }
        pdf.extend_from_slice(xref.as_bytes());
        let trailer =
            format!("trailer\n<< /Size {total} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
        pdf.extend_from_slice(trailer.as_bytes());
        pdf
    }

    /// Build a minimal PDF with a non-Page object (a Pages node) at object 3.
    fn build_pdf_with_pages_node_as_obj3() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");

        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

        let off2 = pdf.len() as u64;
        // object 2 is actually the Pages intermediary (no /Kids for simplicity)
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n");

        let off3 = pdf.len() as u64;
        // object 3 is deliberately another Pages node, not a Page
        pdf.extend_from_slice(b"3 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n");

        let xref_start = pdf.len() as u64;
        let xref = format!(
            "xref\n0 4\n0000000000 65535 f \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n",
            off1, off2, off3,
        );
        pdf.extend_from_slice(xref.as_bytes());
        let trailer =
            format!("trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
        pdf.extend_from_slice(trailer.as_bytes());
        pdf
    }

    /// Build raw stream object bytes (binary-safe).
    fn stream_object_bytes(num: u32, body: &[u8]) -> Vec<u8> {
        let mut out = Vec::new();
        out.extend_from_slice(
            format!("{num} 0 obj\n<< /Length {} >>\nstream\n", body.len()).as_bytes(),
        );
        out.extend_from_slice(body);
        out.extend_from_slice(b"\nendstream\nendobj\n");
        out
    }

    /// Build raw stream object bytes with a chained [/FlateDecode /ASCII85Decode] filter array.
    ///
    /// PDF semantics: Filter = [/FlateDecode /ASCII85Decode] means the *decode* pipeline
    /// applies filters left-to-right, so during decode the reader first FlateDecode-decompresses,
    /// then ASCII85Decode-decodes.  To produce bytes that round-trip correctly we therefore
    /// *encode* in the reverse order: first ASCII85Decode-encode, then FlateDecode-compress.
    /// We encode each step manually (single-name dicts) rather than using encode_stream_data
    /// with an Array dict, because encode_stream_data applies Array filters in the same
    /// left-to-right order as decode (which is the inverse of what we need here).
    ///
    /// This exercises the Array branch in decode_stream_data_with_filters_and_crypt
    /// (filters.rs L78-96).
    fn chained_filter_stream_object_bytes(num: u32, body: &[u8]) -> Vec<u8> {
        // Step 1: ASCII85Decode-encode (encode is the inverse of ASCII85Decode decode)
        let mut a85_dict = Dictionary::new();
        a85_dict.insert("Filter", Object::Name(b"ASCII85Decode".to_vec()));
        let after_a85 = encode_stream_data(&a85_dict, body).unwrap();

        // Step 2: FlateDecode-compress
        let mut flate_dict = Dictionary::new();
        flate_dict.insert("Filter", Object::Name(b"FlateDecode".to_vec()));
        let encoded = encode_stream_data(&flate_dict, &after_a85).unwrap();

        let mut out = Vec::new();
        out.extend_from_slice(
            format!(
                "{num} 0 obj\n<< /Filter [ /FlateDecode /ASCII85Decode ] /Length {} >>\nstream\n",
                encoded.len()
            )
            .as_bytes(),
        );
        out.extend_from_slice(&encoded);
        out.extend_from_slice(b"\nendstream\nendobj\n");
        out
    }

    // -----------------------------------------------------------------------
    // A flexible builder that takes pre-built extra object bytes.
    // -----------------------------------------------------------------------

    fn build_pdf_with_binary_extras(
        contents_entry: &str,
        extra_objects: &[(u32, Vec<u8>)],
    ) -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");

        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

        let off2 = pdf.len() as u64;
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");

        let off3 = pdf.len() as u64;
        let page_obj = if contents_entry.is_empty() {
            "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n".to_string()
        } else {
            format!(
                "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents {contents_entry} >>\nendobj\n"
            )
        };
        pdf.extend_from_slice(page_obj.as_bytes());

        let mut extra_offsets: Vec<(u32, u64)> = Vec::new();
        for (num, body) in extra_objects.iter() {
            let off = pdf.len() as u64;
            extra_offsets.push((*num, off));
            pdf.extend_from_slice(body);
        }

        let xref_start = pdf.len() as u64;
        let max_num = extra_offsets.iter().map(|(n, _)| *n).max().unwrap_or(3);
        let total = max_num as usize + 1;
        let mut xref = format!("xref\n0 {total}\n0000000000 65535 f \n");
        xref.push_str(&format!("{:010} 00000 n \n", off1));
        xref.push_str(&format!("{:010} 00000 n \n", off2));
        xref.push_str(&format!("{:010} 00000 n \n", off3));
        for i in 4..=max_num {
            if let Some((_, off)) = extra_offsets.iter().find(|(n, _)| *n == i) {
                xref.push_str(&format!("{:010} 00000 n \n", off));
            } else {
                xref.push_str("0000000000 65535 f \n");
            }
        }
        pdf.extend_from_slice(xref.as_bytes());
        let trailer =
            format!("trailer\n<< /Size {total} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
        pdf.extend_from_slice(trailer.as_bytes());
        pdf
    }

    // -----------------------------------------------------------------------
    // Test: /Contents absent → empty Vec
    // -----------------------------------------------------------------------

    #[test]
    fn page_content_bytes_returns_empty_for_page_without_contents() {
        let bytes = build_pdf_with_contents("", &[]);
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
        let page_ref = ObjectRef::new(3, 0);
        let content = page_content_bytes(&mut pdf, page_ref).unwrap();
        assert!(
            content.is_empty(),
            "expected empty Vec for page without /Contents"
        );
    }

    // -----------------------------------------------------------------------
    // Test: /Contents = single Reference → decoded bytes
    // -----------------------------------------------------------------------

    #[test]
    fn page_content_bytes_resolves_single_stream_reference() {
        let body = b"BT /F1 12 Tf (Hello) Tj ET";
        let stream_bytes = stream_object_bytes(4, body);
        let bytes = build_pdf_with_binary_extras("4 0 R", &[(4, stream_bytes)]);
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
        let page_ref = ObjectRef::new(3, 0);
        let content = page_content_bytes(&mut pdf, page_ref).unwrap();
        assert_eq!(content, body);
    }

    // -----------------------------------------------------------------------
    // Test: /Contents = Array of References → decoded and joined with space
    // -----------------------------------------------------------------------

    #[test]
    fn page_content_bytes_concatenates_array_of_refs_with_space_separator() {
        let body1 = b"q 1 0 0 1 0 0 cm";
        let body2 = b"BT /F1 12 Tf (World) Tj ET";
        let stream_bytes1 = stream_object_bytes(4, body1);
        let stream_bytes2 = stream_object_bytes(5, body2);
        let bytes = build_pdf_with_binary_extras(
            "[4 0 R 5 0 R]",
            &[(4, stream_bytes1), (5, stream_bytes2)],
        );
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
        let page_ref = ObjectRef::new(3, 0);
        let content = page_content_bytes(&mut pdf, page_ref).unwrap();
        let mut expected = body1.to_vec();
        expected.push(b' ');
        expected.extend_from_slice(body2);
        assert_eq!(content, expected);
    }

    // -----------------------------------------------------------------------
    // Test: /Contents stream with chained [/FlateDecode /ASCII85Decode] filter array
    // -----------------------------------------------------------------------

    #[test]
    fn page_content_bytes_applies_chained_filters() {
        // This stream uses Filter = [/FlateDecode /ASCII85Decode], exercising the Array branch
        // in decode_stream_data (not the single-Name branch).
        let body = b"q 0.5 g 100 100 300 300 re f Q";
        let stream_bytes = chained_filter_stream_object_bytes(4, body);
        let bytes = build_pdf_with_binary_extras("4 0 R", &[(4, stream_bytes)]);
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
        let page_ref = ObjectRef::new(3, 0);
        let content = page_content_bytes(&mut pdf, page_ref).unwrap();
        assert_eq!(content, body);
    }

    // -----------------------------------------------------------------------
    // Test: non-Page object → Error::Unsupported
    // -----------------------------------------------------------------------

    #[test]
    fn page_content_bytes_rejects_non_page_ref() {
        let bytes = build_pdf_with_pages_node_as_obj3();
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
        // Object 3 is a Pages node, not a Page.
        let result = page_content_bytes(&mut pdf, ObjectRef::new(3, 0));
        assert!(result.is_err(), "expected error for non-Page ref, got Ok");
        match result.unwrap_err() {
            Error::Unsupported(_) => {}
            err => panic!("expected Error::Unsupported, got {err:?}"),
        }
    }

    // -----------------------------------------------------------------------
    // Test: /Contents = direct inline Stream (edge case, not typical in PDFs)
    // -----------------------------------------------------------------------

    #[test]
    fn page_content_bytes_handles_direct_stream_in_contents() {
        // We build a PDF where /Contents holds an inline Stream via set_object.
        let base_bytes = build_pdf_with_contents("", &[]);
        let mut pdf = Pdf::open(Cursor::new(base_bytes)).expect("PDF should parse");

        // Build a Page dict that has a direct Stream in /Contents.
        let content_body = b"BT /F1 12 Tf (Direct) Tj ET";
        let stream = Stream::new(Dictionary::new(), content_body.to_vec());
        let mut page_dict = Dictionary::new();
        page_dict.insert("Type", Object::Name(b"Page".to_vec()));
        page_dict.insert("Contents", Object::Stream(stream));
        pdf.set_object(ObjectRef::new(3, 0), Object::Dictionary(page_dict));

        let content = page_content_bytes(&mut pdf, ObjectRef::new(3, 0)).unwrap();
        assert_eq!(content, content_body);
    }

    // -----------------------------------------------------------------------
    // Helpers for resolve_inherited_resources tests
    // -----------------------------------------------------------------------

    /// Build a PDF where the Page (3 0 R) has /Resources directly as a Dictionary.
    ///
    /// Object layout:
    ///   1 0 R  Catalog
    ///   2 0 R  Pages  (no /Resources)
    ///   3 0 R  Page   (/Resources << /Font << >> >>)
    fn build_pdf_page_has_direct_resources() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");

        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

        let off2 = pdf.len() as u64;
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");

        let off3 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << >> >> >>\nendobj\n",
        );

        let xref_start = pdf.len() as u64;
        let xref = format!(
            "xref\n0 4\n0000000000 65535 f \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n",
            off1, off2, off3,
        );
        pdf.extend_from_slice(xref.as_bytes());
        let trailer =
            format!("trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
        pdf.extend_from_slice(trailer.as_bytes());
        pdf
    }

    /// Build a PDF where:
    ///   1 0 R  Catalog
    ///   2 0 R  Pages  (/Resources 4 0 R — indirect reference)
    ///   3 0 R  Page   (no /Resources, /Parent 2 0 R)
    ///   4 0 R  Resources dictionary (indirect object)
    fn build_pdf_resources_inherited_via_indirect_ref() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");

        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

        let off2 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 /Resources 4 0 R >>\nendobj\n",
        );

        let off3 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
        );

        let off4 = pdf.len() as u64;
        // The actual Resources dictionary as an indirect object
        pdf.extend_from_slice(b"4 0 obj\n<< /Font << /F1 << /Type /Font >> >> >>\nendobj\n");

        let xref_start = pdf.len() as u64;
        let xref = format!(
            "xref\n0 5\n0000000000 65535 f \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n",
            off1, off2, off3, off4,
        );
        pdf.extend_from_slice(xref.as_bytes());
        let trailer =
            format!("trailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
        pdf.extend_from_slice(trailer.as_bytes());
        pdf
    }

    /// Build a PDF where no node has /Resources at all.
    ///
    /// Object layout:
    ///   1 0 R  Catalog
    ///   2 0 R  Pages  (no /Resources)
    ///   3 0 R  Page   (no /Resources, /Parent 2 0 R)
    fn build_pdf_no_resources() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");

        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

        let off2 = pdf.len() as u64;
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");

        let off3 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
        );

        let xref_start = pdf.len() as u64;
        let xref = format!(
            "xref\n0 4\n0000000000 65535 f \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n",
            off1, off2, off3,
        );
        pdf.extend_from_slice(xref.as_bytes());
        let trailer =
            format!("trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
        pdf.extend_from_slice(trailer.as_bytes());
        pdf
    }

    // -----------------------------------------------------------------------
    // Test (a): Page itself has /Resources as a direct Dictionary
    // -----------------------------------------------------------------------

    #[test]
    fn resolve_inherited_resources_page_has_direct_dict() {
        let bytes = build_pdf_page_has_direct_resources();
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
        let page_ref = ObjectRef::new(3, 0);
        let result = resolve_inherited_resources(&mut pdf, page_ref).expect("should succeed");
        let dict = result.expect("should find /Resources");
        // The page's /Resources has a /Font key
        assert!(
            dict.get("Font").is_some(),
            "expected /Font key in resolved Resources dict"
        );
    }

    // -----------------------------------------------------------------------
    // Test (b): Page inherits /Resources from parent via an indirect Reference
    // -----------------------------------------------------------------------

    #[test]
    fn resolve_inherited_resources_from_parent_via_indirect_ref() {
        let bytes = build_pdf_resources_inherited_via_indirect_ref();
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
        // Page (3 0 R) has no /Resources — it must be inherited from Pages (2 0 R)
        // which references Resources dict (4 0 R) via an indirect reference.
        let page_ref = ObjectRef::new(3, 0);
        let result = resolve_inherited_resources(&mut pdf, page_ref).expect("should succeed");
        let dict = result.expect("should find inherited /Resources via indirect ref");
        // The inherited Resources (4 0 R) has a /Font key
        assert!(
            dict.get("Font").is_some(),
            "expected /Font key in inherited Resources dict"
        );
    }

    // -----------------------------------------------------------------------
    // Test (c): No /Resources anywhere → Ok(None)
    // -----------------------------------------------------------------------

    #[test]
    fn resolve_inherited_resources_none_when_absent() {
        let bytes = build_pdf_no_resources();
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
        let page_ref = ObjectRef::new(3, 0);
        let result =
            resolve_inherited_resources(&mut pdf, page_ref).expect("should succeed with Ok(None)");
        assert!(
            result.is_none(),
            "expected Ok(None) when no /Resources anywhere in the parent chain"
        );
    }

    // -----------------------------------------------------------------------
    // Test (d): Circular /Parent reference → does not crash; returns Err or Ok(None)
    // -----------------------------------------------------------------------

    #[test]
    fn resolve_inherited_resources_cycle_does_not_crash() {
        // We build a PDF via set_object to introduce a cycle: Page 3 → Pages 2 → Page 3.
        // Use the no-resources PDF as a base, then patch /Parent of Pages (2 0 R) to point
        // back to Page (3 0 R), creating a cycle.
        let bytes = build_pdf_no_resources();
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");

        // Patch Pages node (2 0 R) to have /Parent pointing back to Page (3 0 R)
        let mut pages_dict = Dictionary::new();
        pages_dict.insert("Type", Object::Name(b"Pages".to_vec()));
        pages_dict.insert(
            "Kids",
            Object::Array(vec![Object::Reference(ObjectRef::new(3, 0))]),
        );
        pages_dict.insert("Count", Object::Integer(1));
        pages_dict.insert("Parent", Object::Reference(ObjectRef::new(3, 0))); // cycle!
        pdf.set_object(ObjectRef::new(2, 0), Object::Dictionary(pages_dict));

        let page_ref = ObjectRef::new(3, 0);
        // Must not panic or loop forever; either Ok(None) or Err(Unsupported) is acceptable.
        let result = resolve_inherited_resources(&mut pdf, page_ref);
        match result {
            Ok(None) => {} // cycle detected via BTreeSet — acceptable
            Ok(Some(_)) => panic!("should not find resources in a cycle-only graph"),
            Err(Error::Unsupported(_)) => {} // depth exceeded or explicit cycle error — acceptable
            Err(e) => panic!("unexpected error variant: {e:?}"),
        }
    }

    // -----------------------------------------------------------------------
    // Test: /Resources null and /Parent null are treated as absent (PDF §7.3.9)
    // -----------------------------------------------------------------------

    #[test]
    fn resolve_inherited_resources_null_falls_through_to_parent() {
        // Page has /Resources null → must continue inheritance to the Pages
        // node, which has a real /Resources dict.
        let bytes = build_pdf_resources_inherited_via_indirect_ref();
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");

        let mut page_dict = Dictionary::new();
        page_dict.insert("Type", Object::Name(b"Page".to_vec()));
        page_dict.insert("Parent", Object::Reference(ObjectRef::new(2, 0)));
        page_dict.insert(
            "MediaBox",
            Object::Array(vec![
                Object::Integer(0),
                Object::Integer(0),
                Object::Integer(612),
                Object::Integer(792),
            ]),
        );
        page_dict.insert("Resources", Object::Null);
        pdf.set_object(ObjectRef::new(3, 0), Object::Dictionary(page_dict));

        let page_ref = ObjectRef::new(3, 0);
        let result =
            resolve_inherited_resources(&mut pdf, page_ref).expect("null should be like absent");
        let dict = result.expect("should inherit /Resources from parent despite null on page");
        assert!(
            dict.get("Font").is_some(),
            "expected inherited /Font key when page's /Resources is null"
        );
    }

    #[test]
    fn resolve_inherited_resources_null_parent_terminates_chain() {
        // Page has no /Resources and /Parent null → must terminate at this
        // node and return Ok(None), rather than dereferencing null as a ref.
        let bytes = build_pdf_no_resources();
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");

        let mut page_dict = Dictionary::new();
        page_dict.insert("Type", Object::Name(b"Page".to_vec()));
        page_dict.insert("Parent", Object::Null);
        page_dict.insert(
            "MediaBox",
            Object::Array(vec![
                Object::Integer(0),
                Object::Integer(0),
                Object::Integer(612),
                Object::Integer(792),
            ]),
        );
        pdf.set_object(ObjectRef::new(3, 0), Object::Dictionary(page_dict));

        let page_ref = ObjectRef::new(3, 0);
        let result = resolve_inherited_resources(&mut pdf, page_ref)
            .expect("null /Parent should be like absent");
        assert!(
            result.is_none(),
            "expected Ok(None) when /Parent is null and no /Resources"
        );
    }

    // -----------------------------------------------------------------------
    // PageWalk tests
    // -----------------------------------------------------------------------

    /// Build a minimal valid PDF from a list of (object_number, body_literal) pairs.
    /// `catalog_ref` is the object number of the /Catalog object.
    fn pdf_from_objects(catalog_ref: u32, objects: &[(u32, &str)]) -> Vec<u8> {
        let mut data: Vec<u8> = b"%PDF-1.4\n".to_vec();
        let mut offsets: Vec<(u32, u64)> = Vec::new();
        for (num, body) in objects {
            let off = data.len() as u64;
            offsets.push((*num, off));
            data.extend_from_slice(format!("{num} 0 obj\n{body}\nendobj\n").as_bytes());
        }
        let xref_start = data.len() as u64;
        let max_num = offsets.iter().map(|(n, _)| *n).max().unwrap_or(0);
        let total = max_num as usize + 1;
        let mut xref = format!("xref\n0 {total}\n0000000000 65535 f \n");
        for i in 1..=max_num {
            if let Some((_, off)) = offsets.iter().find(|(n, _)| *n == i) {
                xref.push_str(&format!("{off:010} 00000 n \n"));
            } else {
                xref.push_str("0000000000 65535 f \n");
            }
        }
        data.extend_from_slice(xref.as_bytes());
        let trailer = format!(
            "trailer\n<< /Size {total} /Root {catalog_ref} 0 R >>\nstartxref\n{xref_start}\n%%EOF\n"
        );
        data.extend_from_slice(trailer.as_bytes());
        data
    }

    #[test]
    fn page_walk_single_page_yields_one_ref() {
        let bytes = pdf_from_objects(
            1,
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R >>"),
                (2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
                (3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
            ],
        );
        let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
        let refs: Vec<ObjectRef> = PageWalk::new(&mut pdf)
            .unwrap()
            .collect::<Result<_>>()
            .unwrap();
        assert_eq!(refs, vec![ObjectRef::new(3, 0)]);
    }

    #[test]
    fn page_walk_sibling_order_is_document_order() {
        let bytes = pdf_from_objects(
            1,
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R >>"),
                (2, "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>"),
                (3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
                (4, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
            ],
        );
        let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
        let refs: Vec<ObjectRef> = PageWalk::new(&mut pdf)
            .unwrap()
            .collect::<Result<_>>()
            .unwrap();
        assert_eq!(
            refs,
            vec![ObjectRef::new(3, 0), ObjectRef::new(4, 0)],
            "pages must be yielded in document order (3 before 4)"
        );
    }

    #[test]
    fn page_walk_nested_tree_document_order() {
        // Tree: Pages(2) -> [Pages(3), Page(6)]
        //       Pages(3) -> [Page(4), Page(5)]
        // Expected yield order: 4, 5, 6
        let bytes = pdf_from_objects(
            1,
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R >>"),
                (2, "<< /Type /Pages /Kids [3 0 R 6 0 R] /Count 3 >>"),
                (
                    3,
                    "<< /Type /Pages /Parent 2 0 R /Kids [4 0 R 5 0 R] /Count 2 >>",
                ),
                (4, "<< /Type /Page /Parent 3 0 R /MediaBox [0 0 612 792] >>"),
                (5, "<< /Type /Page /Parent 3 0 R /MediaBox [0 0 612 792] >>"),
                (6, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
            ],
        );
        let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
        let refs: Vec<ObjectRef> = PageWalk::new(&mut pdf)
            .unwrap()
            .collect::<Result<_>>()
            .unwrap();
        assert_eq!(
            refs,
            vec![
                ObjectRef::new(4, 0),
                ObjectRef::new(5, 0),
                ObjectRef::new(6, 0),
            ],
            "pages must be yielded in document order across nested Pages nodes"
        );
    }

    #[test]
    fn page_walk_cycle_does_not_crash() {
        // Cycle: Pages(2) -> [Pages(3)], Pages(3) -> [Pages(2)].
        // seen-set breaks the cycle; no pages exist so result is Ok([]).
        let bytes = pdf_from_objects(
            1,
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R >>"),
                (2, "<< /Type /Pages /Kids [3 0 R] /Count 0 >>"),
                (3, "<< /Type /Pages /Kids [2 0 R] /Count 0 >>"),
            ],
        );
        let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
        let result: Result<Vec<ObjectRef>> = PageWalk::new(&mut pdf).unwrap().collect();
        assert_eq!(result.unwrap(), vec![]);
    }

    #[test]
    fn page_walk_depth_limit_returns_err() {
        // max_depth=1: the Pages root is at depth 0; its kid is pushed at depth 1
        // which equals max_depth, so popping it triggers a depth-limit error.
        let bytes = pdf_from_objects(
            1,
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R >>"),
                (2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
                (3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
            ],
        );
        let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
        let result: Result<Vec<ObjectRef>> =
            PageWalk::with_max_depth(&mut pdf, 1).unwrap().collect();
        match result {
            Err(Error::Unsupported(_)) => {}
            other => panic!("expected Err(Unsupported) for depth limit, got {other:?}"),
        }
    }

    #[test]
    fn page_walk_fused_after_depth_err() {
        // After yielding Err the iterator must return None (fused).
        let bytes = pdf_from_objects(
            1,
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R >>"),
                (2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
                (3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
            ],
        );
        let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
        let mut walk = PageWalk::with_max_depth(&mut pdf, 1).unwrap();
        let first = walk.next();
        assert!(
            matches!(first, Some(Err(Error::Unsupported(_)))),
            "first item should be Err(Unsupported)"
        );
        assert!(walk.next().is_none(), "iterator must be fused after Err");
    }

    #[test]
    fn page_walk_pages_node_without_kids_is_skipped() {
        // A Pages node with no /Kids entry: silently produces no pages.
        let bytes = pdf_from_objects(
            1,
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R >>"),
                (2, "<< /Type /Pages /Count 0 >>"),
            ],
        );
        let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
        let refs: Vec<ObjectRef> = PageWalk::new(&mut pdf)
            .unwrap()
            .collect::<Result<_>>()
            .unwrap();
        assert!(refs.is_empty());
    }

    #[test]
    fn page_walk_non_ref_kid_is_ignored() {
        // Non-Reference element in /Kids must be silently ignored.
        let bytes = pdf_from_objects(
            1,
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R >>"),
                (2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
                (3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
            ],
        );
        let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();

        // Patch the Pages node to include an Integer kid alongside the real Page ref.
        let mut pages_dict = Dictionary::new();
        pages_dict.insert("Type", Object::Name(b"Pages".to_vec()));
        pages_dict.insert(
            "Kids",
            Object::Array(vec![
                Object::Integer(999), // non-Reference: must be ignored
                Object::Reference(ObjectRef::new(3, 0)),
            ]),
        );
        pages_dict.insert("Count", Object::Integer(1));
        pdf.set_object(ObjectRef::new(2, 0), Object::Dictionary(pages_dict));

        let refs: Vec<ObjectRef> = PageWalk::new(&mut pdf)
            .unwrap()
            .collect::<Result<_>>()
            .unwrap();
        assert_eq!(refs, vec![ObjectRef::new(3, 0)]);
    }

    #[test]
    fn page_walk_unknown_type_node_is_skipped() {
        // A node with unknown /Type in the Kids list is silently skipped.
        let bytes = pdf_from_objects(
            1,
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R >>"),
                (2, "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 1 >>"),
                (3, "<< /Type /Widget /Parent 2 0 R >>"),
                (4, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
            ],
        );
        let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
        let refs: Vec<ObjectRef> = PageWalk::new(&mut pdf)
            .unwrap()
            .collect::<Result<_>>()
            .unwrap();
        assert_eq!(
            refs,
            vec![ObjectRef::new(4, 0)],
            "Widget node must be skipped"
        );
    }

    #[test]
    fn page_walk_matches_page_refs() {
        // Regression: PageWalk and page_refs must produce identical results.
        let bytes = pdf_from_objects(
            1,
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R >>"),
                (2, "<< /Type /Pages /Kids [3 0 R 6 0 R] /Count 3 >>"),
                (
                    3,
                    "<< /Type /Pages /Parent 2 0 R /Kids [4 0 R 5 0 R] /Count 2 >>",
                ),
                (4, "<< /Type /Page /Parent 3 0 R /MediaBox [0 0 612 792] >>"),
                (5, "<< /Type /Page /Parent 3 0 R /MediaBox [0 0 612 792] >>"),
                (6, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
            ],
        );
        let bytes2 = bytes.clone();
        let mut pdf1 = Pdf::open(Cursor::new(bytes)).unwrap();
        let mut pdf2 = Pdf::open(Cursor::new(bytes2)).unwrap();

        let from_page_refs = page_refs(&mut pdf1).unwrap();
        let from_walk: Vec<ObjectRef> = PageWalk::new(&mut pdf2)
            .unwrap()
            .collect::<Result<_>>()
            .unwrap();
        assert_eq!(from_page_refs, from_walk);
    }
}