flpdf 0.5.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
//! qpdf correspondence: QPDFJob.cc attachment enumeration and display formatting.
//! Structured enumeration and formatted display of PDF attachments.
//!
//! Two independent views of a document's embedded files live here:
//!
//! * [`list_attachment_info`] returns a structured [`AttachmentInfo`] per
//!   attachment, for programs that want the metadata rather than a rendering.
//! * [`format_attachment_list`] reproduces the listing `qpdf
//!   --list-attachments [--verbose]` writes to its info log.
//!
//! # Listing format
//!
//! Without `verbose` each attachment contributes exactly one line, naming the
//! name-tree key and the object/generation of its embedded file stream:
//!
//! ```text
//! potato.png -> 6,0
//! ```
//!
//! With `verbose` the header line is followed by the preferred name, every
//! recognized name key, and every `/EF` entry with that stream's parameters:
//!
//! ```text
//! potato.png -> 6,0
//!   description: <only when /Desc is non-empty>
//!   preferred name: π.png
//!   all names:
//!     /F -> π.png
//!     /UF -> π.png
//!   all data streams:
//!     /F -> 6,0
//!       creation date: D:20220215153939-05'00'
//!       modification date: D:20220215153939-05'00'
//!       mime type:
//!       checksum: c55e70c0c72d7eaf01230124fe5ff2d9
//! ```
//!
//! Absent values render as an empty string after the label — the label and its
//! single trailing space are still written, as in the `mime type:` line above.
//!
//! # Example
//!
//! ```no_run
//! use std::fs::File;
//! use std::io::{BufReader, Write};
//! use flpdf::{format_attachment_list, Pdf};
//!
//! let mut pdf = Pdf::open(BufReader::new(File::open("with-attachments.pdf")?))?;
//! match format_attachment_list(&mut pdf, false)? {
//!     Some(listing) => std::io::stdout().write_all(&listing)?,
//!     None => println!("with-attachments.pdf has no embedded files"),
//! }
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use super::checksum_to_hex;
use crate::embedded_files::list_embedded_files;
use crate::filespec_helper::{EmbeddedFileStream, FileSpec};
use crate::object_handle::ObjectHandle;
use crate::{ObjectRef, Pdf, Result};
use std::io::{Read, Seek};

// ── AttachmentInfo ────────────────────────────────────────────────────────────

/// Structured metadata for a single PDF attachment.
///
/// Fields are `Option<Vec<u8>>` (or `Option<i64>` for `size`) because any
/// field may be absent in a well-formed or partially-formed PDF.
///
/// `key` and `filespec_ref` are always present — they come from the
/// `/Names /EmbeddedFiles` name tree and are required to have found the entry
/// in the first place.
#[derive(Debug, Clone, PartialEq)]
pub struct AttachmentInfo {
    /// Raw name-tree key (the bytes used to look up this attachment).
    pub key: Vec<u8>,
    /// Object reference of the `/Filespec` dictionary.
    pub filespec_ref: ObjectRef,
    /// Display name: decoded `/UF` (preferred) or decoded `/F`.  `None` when
    /// both are absent.
    pub display_name: Option<String>,
    /// Uncompressed file size from `/Params /Size`.
    pub size: Option<i64>,
    /// MIME type from `/EmbeddedFile /Subtype` (raw bytes from PDF Name).
    pub mimetype: Option<Vec<u8>>,
    /// Raw PDF date string from `/Params /CreationDate`.
    pub creation_date: Option<Vec<u8>>,
    /// Raw PDF date string from `/Params /ModDate`.
    pub modification_date: Option<Vec<u8>>,
    // ── verbose-only fields ───────────────────────────────────────────────
    /// Human-readable description from `/Filespec /Desc`.
    pub description: Option<Vec<u8>>,
    /// Associated-file relationship from `/Filespec /AFRelationship`.
    pub af_relationship: Option<Vec<u8>>,
    /// MD5 checksum from `/Params /CheckSum` (raw bytes; displayed as hex).
    pub checksum: Option<Vec<u8>>,
}

// ── UTF-16BE decoder ──────────────────────────────────────────────────────────

/// Decode a PDF text string (ISO 32000-1 §7.9.2) to a UTF-8 `String` for
/// display.
///
/// Delegates to the single canonical decoder
/// [`crate::json_inspect::decode_pdf_text_string`], which handles UTF-16BE /
/// UTF-16LE BOM-prefixed strings **and** the full PDFDocEncoding table
/// (ISO 32000-1 Annex D.3) — so non-ASCII `/F`, `/UF`, and `/Desc` values are
/// decoded correctly instead of being mangled by a lossy UTF-8 fallback
/// (roborev #953).  If the bytes cannot be interpreted as a PDF text string,
/// fall back to lossy UTF-8 so the listing still shows *something* rather than
/// failing.
fn decode_pdf_text_string(bytes: &[u8]) -> String {
    crate::json_inspect::decode_pdf_text_string(bytes)
        .unwrap_or_else(|| String::from_utf8_lossy(bytes).into_owned())
}

// ── list_attachment_info ──────────────────────────────────────────────────────

/// Enumerate all attachments in `pdf` and return their structured metadata.
///
/// Iterates the `/Names /EmbeddedFiles` name tree via
/// [`list_embedded_files`], then reads each `/Filespec` dictionary and its
/// associated `/EmbeddedFile` stream for metadata.
///
/// An empty list is returned — without error — when the document has no
/// embedded files.
///
/// For a runnable walkthrough see `examples/pull_attachments.rs`.
///
/// # Errors
///
/// Propagates any error from [`Pdf::resolve`] or the embedded-files walker.
pub fn list_attachment_info<R: Read + Seek>(pdf: &mut Pdf<R>) -> Result<Vec<AttachmentInfo>> {
    let entries = list_embedded_files(pdf)?;
    let mut out = Vec::with_capacity(entries.len());

    for (key, filespec_ref) in entries {
        let info = collect_one(pdf, key, filespec_ref)?;
        out.push(info);
    }

    Ok(out)
}

/// Build an [`AttachmentInfo`] for a single `(key, filespec_ref)` pair.
fn collect_one<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    key: Vec<u8>,
    filespec_ref: ObjectRef,
) -> Result<AttachmentInfo> {
    let mut fs = FileSpec::new(pdf.get_object_handle(filespec_ref), pdf)?;

    // ── Display name: /UF preferred, fall back to /F ─────────────────────
    let display_name: Option<String> = {
        let uf_raw = fs.uf()?;
        let f_raw = fs.filename()?;
        match (uf_raw, f_raw) {
            (Some(uf), _) => Some(decode_pdf_text_string(&uf)),
            (None, Some(f)) => Some(decode_pdf_text_string(&f)),
            (None, None) => None,
        }
    };

    // ── Verbose fields from /Filespec ─────────────────────────────────────
    let description = fs.description()?;
    let af_relationship = fs.af_relationship()?;

    // ── Metadata from /EmbeddedFile stream ────────────────────────────────
    let (size, mimetype, creation_date, modification_date, checksum) = match fs.embedded_file()? {
        Some(ef) => (
            ef.size()?,
            ef.mimetype()?,
            ef.creation_date()?,
            ef.modification_date()?,
            ef.checksum()?,
        ),
        None => (None, None, None, None, None),
    };

    Ok(AttachmentInfo {
        key,
        filespec_ref,
        display_name,
        size,
        mimetype,
        creation_date,
        modification_date,
        description,
        af_relationship,
        checksum,
    })
}

// ── format_attachment_list ────────────────────────────────────────────────────

/// Render the `qpdf --list-attachments [--verbose]` listing for `pdf`.
///
/// Returns `None` when the document catalog has no `/Names /EmbeddedFiles`
/// dictionary; callers report that case with the input file name, the way
/// `qpdf` prints `<file> has no embedded files`.  A document that *does* carry
/// an `/EmbeddedFiles` name tree returns `Some`, even when the tree is empty —
/// an empty tree lists nothing and is not the "no embedded files" case.
///
/// The listing is returned as bytes, not [`String`]: names, descriptions and
/// dates go through the same UTF-8 view qpdf uses for PDF strings, which may
/// carry an explicit UTF-8 BOM followed by bytes that are not valid UTF-8.
///
/// Without `verbose` each attachment contributes only its header line, naming
/// the name-tree key and the object/generation of the embedded file stream
/// selected by [`FileSpec::get_embedded_file_stream`].  A filespec with no
/// usable stream reports `0,0`.
///
/// With `verbose` the header is followed by `/Desc` (only when non-empty), the
/// preferred name, every recognized name key, and one block per `/EF` entry
/// carrying that stream's creation date, modification date, MIME type and
/// hex-encoded checksum.  Absent values leave the text after the label empty.
///
/// # Errors
///
/// Propagates any error from the embedded-files name-tree walker or from
/// resolving a `/Filespec`, `/EF` entry or embedded file stream.
///
/// # Examples
///
/// ```no_run
/// # use std::fs::File;
/// # use std::io::{BufReader, Write};
/// # use flpdf::{format_attachment_list, Pdf};
/// # let mut pdf = Pdf::open(BufReader::new(File::open("a.pdf")?))?;
/// if let Some(listing) = format_attachment_list(&mut pdf, true)? {
///     std::io::stdout().write_all(&listing)?;
/// }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn format_attachment_list<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    verbose: bool,
) -> Result<Option<Vec<u8>>> {
    format_attachment_list_with_sink(pdf, verbose, |_| Ok(()))
}

/// Format the attachment list while forwarding each emitted fragment to a
/// caller-owned sink.
///
/// qpdf writes attachment output directly to its info pipeline.  Keeping the
/// sink boundary here lets the CLI preserve output already written when a
/// later verbose metadata accessor throws (for example, the `creation date:`
/// prefix before `getDict()` rejects a non-stream `/EF` value), while the
/// ordinary [`format_attachment_list`] API continues to return one buffer.
pub fn format_attachment_list_with_sink<R, F>(
    pdf: &mut Pdf<R>,
    verbose: bool,
    mut sink: F,
) -> Result<Option<Vec<u8>>>
where
    R: Read + Seek,
    F: FnMut(&[u8]) -> Result<()>,
{
    let mut helper = pdf.embedded_files();
    if !helper.has_embedded_files()? {
        return Ok(None);
    }
    // The name-tree walker already hands out qpdf's UTF-8 view of each key, so
    // the map is keyed and ordered by the converted bytes, as qpdf's is.
    let entries = helper.get_embedded_files()?;

    let mut out = ListingOutput::new(&mut sink);
    for (key, filespec) in entries {
        let ef_entries = {
            let mut file_spec = FileSpec::new(filespec, pdf)?;
            let stream = file_spec.get_embedded_file_stream("")?;
            out.extend_from_slice(&key)?;
            out.extend_from_slice(b" -> ")?;
            out.extend_from_slice(object_generation(&stream).as_bytes())?;
            out.push(b'\n')?;

            if !verbose {
                continue;
            }

            let description = file_spec.get_description()?;
            if !description.is_empty() {
                out.push_labelled(b"  description: ", &description)?;
            }
            let filename = file_spec.get_filename()?;
            out.push_labelled(b"  preferred name: ", &filename)?;
            out.extend_from_slice(b"  all names:\n")?;
            for (name_key, name) in file_spec.get_filenames()? {
                out.extend_from_slice(b"    ")?;
                out.extend_from_slice(name_key.as_bytes())?;
                out.extend_from_slice(b" -> ")?;
                out.extend_from_slice(&name)?;
                out.push(b'\n')?;
            }
            out.extend_from_slice(b"  all data streams:\n")?;
            file_spec.get_embedded_file_stream_entries()?
        };

        // qpdf walks the raw /EF dictionary, so an entry under a key outside
        // the recognized name keys is listed too; keys whose value is null are
        // skipped, as they are by QPDFObjectHandle::getKeys.
        for (stream_key, stream) in ef_entries {
            pdf.resolve(&stream)?;
            if stream.is_null() {
                continue;
            }
            out.extend_from_slice(b"    ")?;
            out.extend_from_slice(&stream_key)?;
            out.extend_from_slice(b" -> ")?;
            out.extend_from_slice(object_generation(&stream).as_bytes())?;
            out.push(b'\n')?;

            let embedded_file = EmbeddedFileStream::new(stream, pdf)?;
            out.extend_from_slice(b"      creation date: ")?;
            out.extend_from_slice(&embedded_file.get_creation_date()?)?;
            out.push(b'\n')?;
            out.extend_from_slice(b"      modification date: ")?;
            out.extend_from_slice(&embedded_file.get_mod_date()?)?;
            out.push(b'\n')?;
            out.extend_from_slice(b"      mime type: ")?;
            out.extend_from_slice(&embedded_file.get_subtype()?)?;
            out.push(b'\n')?;
            out.extend_from_slice(b"      checksum: ")?;
            out.extend_from_slice(checksum_to_hex(&embedded_file.get_checksum()?).as_bytes())?;
            out.push(b'\n')?;
        }
    }
    Ok(Some(out.finish()))
}

struct ListingOutput<'a, F> {
    bytes: Vec<u8>,
    sink: &'a mut F,
}

impl<'a, F> ListingOutput<'a, F>
where
    F: FnMut(&[u8]) -> Result<()>,
{
    fn new(sink: &'a mut F) -> Self {
        Self {
            bytes: Vec::new(),
            sink,
        }
    }

    fn extend_from_slice(&mut self, data: &[u8]) -> Result<()> {
        self.bytes.extend_from_slice(data);
        (self.sink)(data)
    }

    fn push(&mut self, byte: u8) -> Result<()> {
        self.bytes.push(byte);
        (self.sink)(&[byte])
    }

    /// Append `label`, `value`, and a newline in qpdf's expression order.
    fn push_labelled(&mut self, label: &[u8], value: &[u8]) -> Result<()> {
        self.extend_from_slice(label)?;
        self.extend_from_slice(value)?;
        self.push(b'\n')
    }

    fn finish(self) -> Vec<u8> {
        self.bytes
    }
}

/// Render a handle's object and generation the way `QPDFObjGen::unparse(',')`
/// does, reporting `0,0` for a direct object.
fn object_generation(handle: &ObjectHandle) -> String {
    match handle.object_ref() {
        Some(object_ref) => format!("{},{}", object_ref.number, object_ref.generation),
        None => "0,0".to_owned(),
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::embedded_files::insert_embedded_file;
    use crate::filespec_helper::{
        encode_utf16be, format_pdf_date, FileParamDates, FileSpecBuilder,
    };
    use crate::{ObjectHandle, ObjectRef, Pdf};
    use std::io::Cursor;
    use std::rc::Rc;

    // ── Minimal PDF fixture ───────────────────────────────────────────────────

    fn minimal_pdf_bytes() -> 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
    }

    fn inline_non_dictionary_filespec_pdf_bytes() -> 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 /Names << /EmbeddedFiles << /Names [(k.txt) (not-a-filespec)] >> >> >>\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
    }

    fn open_minimal() -> Pdf<Cursor<Vec<u8>>> {
        Pdf::open(Cursor::new(minimal_pdf_bytes())).expect("open minimal PDF")
    }

    // ── Fixture PDF with actual attachment ────────────────────────────────────

    #[test]
    fn fixture_attachment_two_page_returns_one_or_more() {
        let path = concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/compat/attachment-two-page.pdf"
        );
        let f = std::fs::File::open(path);
        if f.is_err() {
            // Fixture absent — skip gracefully.
            return;
        }
        let mut pdf = Pdf::open(std::io::BufReader::new(f.unwrap())).expect("open fixture");
        let infos = list_attachment_info(&mut pdf).expect("list");
        assert!(
            !infos.is_empty(),
            "fixture must have at least one attachment"
        );
        // First entry must have a display name
        let first = &infos[0];
        assert!(
            first.display_name.is_some(),
            "display_name must be present for fixture attachment"
        );
    }

    // ── Empty document → empty list ───────────────────────────────────────────

    #[test]
    fn empty_document_returns_empty_list() {
        let mut pdf = open_minimal();
        let infos = list_attachment_info(&mut pdf).expect("list");
        assert!(infos.is_empty(), "no attachments → empty list");
    }

    // ── Filespec construction helpers ─────────────────────────────────────────

    fn next_ref(pdf: &mut Pdf<Cursor<Vec<u8>>>) -> ObjectRef {
        pdf.next_available_object_ref()
            .expect("object-number space must have room in the test fixture")
    }

    fn object_ref(pdf: &mut Pdf<Cursor<Vec<u8>>>, object_ref: ObjectRef) -> ObjectHandle {
        pdf.get_object_handle(object_ref)
    }

    #[derive(Clone)]
    struct HandleDict(ObjectHandle);

    impl HandleDict {
        fn new() -> Self {
            Self(ObjectHandle::dictionary(Vec::new()))
        }

        fn from_entries(entries: Vec<(Vec<u8>, ObjectHandle)>) -> Self {
            Self(ObjectHandle::dictionary(entries))
        }

        fn insert(&self, key: &str, value: ObjectHandle) {
            let mut key_bytes = Vec::with_capacity(key.len() + 1);
            key_bytes.push(b'/');
            key_bytes.extend_from_slice(key.as_bytes());
            self.0
                .replace_key(&key_bytes, value)
                .expect("test fixture dictionary insertion");
        }

        fn into_handle(self) -> ObjectHandle {
            self.0
        }
    }

    /// Store an `/EmbeddedFile` stream and return its reference.
    ///
    /// `params` populates `/Params`; `subtype` populates `/Subtype`.  Both are
    /// omitted entirely when `None`, which is what an attachment written by a
    /// producer that records no metadata looks like.
    fn add_ef_stream(
        pdf: &mut Pdf<Cursor<Vec<u8>>>,
        params: Option<HandleDict>,
        subtype: Option<&[u8]>,
    ) -> ObjectRef {
        let stream_ref = next_ref(pdf);
        let dict = HandleDict::new();
        dict.insert("Type", ObjectHandle::name(b"EmbeddedFile".to_vec()));
        dict.insert("Length", ObjectHandle::integer(4));
        if let Some(subtype) = subtype {
            dict.insert("Subtype", ObjectHandle::name(subtype.to_vec()));
        }
        if let Some(params) = params {
            dict.insert("Params", params.into_handle());
        }
        pdf.replace_object(
            stream_ref,
            ObjectHandle::stream(dict.into_handle(), Rc::new(b"data".to_vec())),
        )
        .expect("install embedded-file stream fixture");
        stream_ref
    }

    /// Store `filespec` and register it in the EmbeddedFiles name tree.
    fn attach(pdf: &mut Pdf<Cursor<Vec<u8>>>, key: &[u8], filespec: HandleDict) -> ObjectRef {
        let filespec_ref = next_ref(pdf);
        pdf.replace_object(filespec_ref, filespec.into_handle())
            .expect("install Filespec fixture");
        insert_embedded_file(pdf, key, filespec_ref).expect("insert");
        filespec_ref
    }

    /// Build `/Params` with the standard four entries.
    fn full_params() -> HandleDict {
        let params = HandleDict::new();
        params.insert("Size", ObjectHandle::integer(4));
        params.insert(
            "CreationDate",
            ObjectHandle::string(b"D:20240101000000Z".to_vec()),
        );
        params.insert(
            "ModDate",
            ObjectHandle::string(b"D:20240102000000Z".to_vec()),
        );
        params.insert(
            "CheckSum",
            ObjectHandle::string(vec![0x00, 0x1f, 0xa0, 0xff]),
        );
        params
    }

    fn listing(pdf: &mut Pdf<Cursor<Vec<u8>>>, verbose: bool) -> Vec<u8> {
        format_attachment_list(pdf, verbose)
            .expect("format")
            .expect("document has an EmbeddedFiles name tree")
    }

    fn as_text(bytes: &[u8]) -> String {
        String::from_utf8(bytes.to_vec()).expect("listing must be valid UTF-8 in these fixtures")
    }

    // ── Non-verbose output is one line per attachment ─────────────────────────

    #[test]
    fn non_verbose_lists_only_the_header_line() {
        let mut pdf = open_minimal();
        let stream_ref = add_ef_stream(&mut pdf, Some(full_params()), Some(b"text/plain"));
        let ef = HandleDict::new();
        ef.insert("F", object_ref(&mut pdf, stream_ref));
        let filespec = HandleDict::new();
        filespec.insert("Type", ObjectHandle::name(b"Filespec".to_vec()));
        filespec.insert("F", ObjectHandle::string(b"a.txt".to_vec()));
        filespec.insert("Desc", ObjectHandle::string(b"described".to_vec()));
        filespec.insert("EF", HandleDict::into_handle(ef));
        attach(&mut pdf, b"a.txt", filespec);

        let out = listing(&mut pdf, false);
        assert_eq!(
            as_text(&out),
            format!("a.txt -> {},0\n", stream_ref.number),
            "qpdf writes the header line outside its verbose block, so plain \
             mode emits nothing else"
        );
    }

    // ── Header object/generation comes from the embedded file stream ──────────

    #[test]
    fn header_objgen_is_the_stream_not_the_filespec() {
        let mut pdf = open_minimal();
        let stream_ref = add_ef_stream(&mut pdf, None, None);
        let ef = HandleDict::new();
        ef.insert("F", object_ref(&mut pdf, stream_ref));
        let filespec = HandleDict::new();
        filespec.insert("F", ObjectHandle::string(b"a.txt".to_vec()));
        filespec.insert("EF", HandleDict::into_handle(ef));
        let filespec_ref = attach(&mut pdf, b"a.txt", filespec);

        assert_ne!(
            stream_ref.number, filespec_ref.number,
            "fixture must distinguish the two objects"
        );
        let out = as_text(&listing(&mut pdf, false));
        assert_eq!(out, format!("a.txt -> {},0\n", stream_ref.number));
        assert!(
            !out.contains(&format!("{},0", filespec_ref.number)),
            "the /Filespec object number must not appear: {out:?}"
        );
    }

    // ── Verbose block structure ───────────────────────────────────────────────

    #[test]
    fn verbose_block_matches_qpdf_structure() {
        let mut pdf = open_minimal();
        let stream_ref = add_ef_stream(&mut pdf, Some(full_params()), Some(b"text/plain"));
        let ef = HandleDict::new();
        ef.insert("F", object_ref(&mut pdf, stream_ref));
        ef.insert("UF", object_ref(&mut pdf, stream_ref));
        let filespec = HandleDict::new();
        filespec.insert("Type", ObjectHandle::name(b"Filespec".to_vec()));
        filespec.insert("F", ObjectHandle::string(b"a.txt".to_vec()));
        filespec.insert("UF", ObjectHandle::string(encode_utf16be("π.txt")));
        filespec.insert("EF", HandleDict::into_handle(ef));
        attach(&mut pdf, b"a.txt", filespec);

        let n = stream_ref.number;
        let expected = format!(
            "a.txt -> {n},0\n\
             \x20 preferred name: π.txt\n\
             \x20 all names:\n\
             \x20   /F -> a.txt\n\
             \x20   /UF -> π.txt\n\
             \x20 all data streams:\n\
             \x20   /F -> {n},0\n\
             \x20     creation date: D:20240101000000Z\n\
             \x20     modification date: D:20240102000000Z\n\
             \x20     mime type: text/plain\n\
             \x20     checksum: 001fa0ff\n\
             \x20   /UF -> {n},0\n\
             \x20     creation date: D:20240101000000Z\n\
             \x20     modification date: D:20240102000000Z\n\
             \x20     mime type: text/plain\n\
             \x20     checksum: 001fa0ff\n"
        );
        assert_eq!(as_text(&listing(&mut pdf, true)), expected);
    }

    // ── /Desc placement ───────────────────────────────────────────────────────

    #[test]
    fn description_precedes_preferred_name_and_only_when_present() {
        let mut pdf = open_minimal();
        let stream_ref = add_ef_stream(&mut pdf, None, None);
        let ef = HandleDict::new();
        ef.insert("F", object_ref(&mut pdf, stream_ref));
        let filespec = HandleDict::new();
        filespec.insert("F", ObjectHandle::string(b"a.txt".to_vec()));
        filespec.insert("Desc", ObjectHandle::string(b"my description".to_vec()));
        filespec.insert("EF", HandleDict::into_handle(ef));
        attach(&mut pdf, b"a.txt", filespec);

        let with_desc = as_text(&listing(&mut pdf, true));
        let lines: Vec<&str> = with_desc.lines().collect();
        assert_eq!(lines[1], "  description: my description");
        assert_eq!(lines[2], "  preferred name: a.txt");

        // An empty /Desc drops the line entirely rather than printing a label.
        let mut pdf = open_minimal();
        let stream_ref = add_ef_stream(&mut pdf, None, None);
        let ef = HandleDict::new();
        ef.insert("F", object_ref(&mut pdf, stream_ref));
        let filespec = HandleDict::new();
        filespec.insert("F", ObjectHandle::string(b"a.txt".to_vec()));
        filespec.insert("Desc", ObjectHandle::string(Vec::new()));
        filespec.insert("EF", HandleDict::into_handle(ef));
        attach(&mut pdf, b"a.txt", filespec);

        let without_desc = as_text(&listing(&mut pdf, true));
        assert!(
            !without_desc.contains("description:"),
            "an empty /Desc must not produce a line: {without_desc:?}"
        );
        assert_eq!(without_desc.lines().nth(1), Some("  preferred name: a.txt"));
    }

    // ── Absent metadata leaves the value empty ────────────────────────────────

    #[test]
    fn absent_values_render_empty_after_the_label() {
        let mut pdf = open_minimal();
        let stream_ref = add_ef_stream(&mut pdf, None, None);
        let ef = HandleDict::new();
        ef.insert("F", object_ref(&mut pdf, stream_ref));
        let filespec = HandleDict::new();
        filespec.insert("F", ObjectHandle::string(b"a.txt".to_vec()));
        filespec.insert("EF", HandleDict::into_handle(ef));
        attach(&mut pdf, b"a.txt", filespec);

        let out = as_text(&listing(&mut pdf, true));
        assert!(out.contains("      creation date: \n"), "{out:?}");
        assert!(out.contains("      modification date: \n"), "{out:?}");
        assert!(out.contains("      mime type: \n"), "{out:?}");
        assert!(out.contains("      checksum: \n"), "{out:?}");
        assert!(
            !out.contains("(none)"),
            "qpdf never substitutes a placeholder: {out:?}"
        );
        assert!(
            !out.contains("size:") && !out.contains("af relationship:"),
            "qpdf's listing has no size or AFRelationship line: {out:?}"
        );
    }

    // ── /EF keys outside the recognized name keys ─────────────────────────────

    #[test]
    fn data_streams_list_every_ef_key_but_names_stay_recognized() {
        let mut pdf = open_minimal();
        let stream_ref = add_ef_stream(&mut pdf, None, None);
        let ef = HandleDict::new();
        ef.insert("F", object_ref(&mut pdf, stream_ref));
        ef.insert("Zed", object_ref(&mut pdf, stream_ref));
        let filespec = HandleDict::new();
        filespec.insert("F", ObjectHandle::string(b"a.txt".to_vec()));
        filespec.insert("Zed", ObjectHandle::string(b"ignored.txt".to_vec()));
        filespec.insert("EF", HandleDict::into_handle(ef));
        attach(&mut pdf, b"a.txt", filespec);

        let out = as_text(&listing(&mut pdf, true));
        assert!(
            out.contains(&format!("    /Zed -> {},0\n", stream_ref.number)),
            "an /EF key outside the name keys is still a data stream: {out:?}"
        );
        assert!(
            !out.contains("/Zed -> ignored.txt"),
            "`all names` only covers the recognized name keys: {out:?}"
        );
    }

    // ── Null /EF entries are skipped ──────────────────────────────────────────

    #[test]
    fn null_ef_entries_are_skipped() {
        let mut pdf = open_minimal();
        let stream_ref = add_ef_stream(&mut pdf, None, None);
        let missing = ObjectRef::new(stream_ref.number + 40, 0);
        let ef = HandleDict::from_entries(vec![(b"/UF".to_vec(), ObjectHandle::null())]);
        ef.insert("F", object_ref(&mut pdf, stream_ref));
        ef.insert("Unix", object_ref(&mut pdf, missing));
        let filespec = HandleDict::new();
        filespec.insert("F", ObjectHandle::string(b"a.txt".to_vec()));
        filespec.insert("EF", HandleDict::into_handle(ef));
        attach(&mut pdf, b"a.txt", filespec);

        let out = as_text(&listing(&mut pdf, true));
        assert!(out.contains("    /F -> "), "{out:?}");
        assert!(
            !out.contains("    /UF -> "),
            "a direct null /EF value is not a key: {out:?}"
        );
        assert!(
            !out.contains("    /Unix -> "),
            "a reference to a missing object resolves to null: {out:?}"
        );
    }

    // ── A filespec with no usable stream ──────────────────────────────────────

    #[test]
    fn filespec_without_ef_reports_zero_objgen() {
        let mut pdf = open_minimal();
        let filespec = HandleDict::new();
        filespec.insert("F", ObjectHandle::string(b"c.txt".to_vec()));
        attach(&mut pdf, b"c.txt", filespec);

        assert_eq!(
            as_text(&listing(&mut pdf, true)),
            "c.txt -> 0,0\n  preferred name: c.txt\n  all names:\n    /F -> c.txt\n  \
             all data streams:\n",
            "a missing /EF still prints the header and both section labels"
        );

        let diagnostics = pdf.repair_diagnostics();
        let warnings: Vec<_> = diagnostics
            .entries()
            .iter()
            .filter(|diagnostic| {
                diagnostic
                    .message
                    .contains("operation for dictionary attempted on object of type null")
            })
            .collect();
        assert_eq!(
            warnings.len(),
            2,
            "qpdf ditems() asks the missing /EF null for keys at begin and end"
        );
        assert!(warnings
            .iter()
            .all(|diagnostic| diagnostic.message.contains("treating as empty")));
    }

    #[test]
    fn ef_value_that_is_not_a_stream_fails_when_metadata_is_read() {
        let mut pdf = open_minimal();
        let dict_ref = next_ref(&mut pdf);
        let not_a_stream = HandleDict::new();
        not_a_stream.insert("Type", ObjectHandle::name(b"EmbeddedFile".to_vec()));
        pdf.replace_object(dict_ref, HandleDict::into_handle(not_a_stream))
            .expect("install non-stream fixture");
        let ef = HandleDict::new();
        ef.insert("F", object_ref(&mut pdf, dict_ref));
        let filespec = HandleDict::new();
        filespec.insert("F", ObjectHandle::string(b"g.txt".to_vec()));
        filespec.insert("EF", HandleDict::into_handle(ef));
        attach(&mut pdf, b"g.txt", filespec);

        let error = format_attachment_list(&mut pdf, true)
            .expect_err("qpdf reads stream metadata after listing a raw non-stream /EF value");
        assert_eq!(
            error.to_string(),
            "operation for stream attempted on object of type dictionary"
        );
        assert_eq!(dict_ref.generation, 0);
    }

    // ── Name tree presence decides the "no embedded files" branch ─────────────

    #[test]
    fn document_without_name_tree_returns_none() {
        let mut pdf = open_minimal();
        assert!(
            format_attachment_list(&mut pdf, true)
                .expect("format")
                .is_none(),
            "no /Names /EmbeddedFiles is the caller's `has no embedded files` case"
        );
    }

    #[test]
    fn empty_name_tree_lists_nothing_but_is_not_none() {
        let mut pdf = open_minimal();
        let root = pdf.root_ref().expect("catalog");
        let catalog = pdf.get_object_handle(root);
        pdf.resolve(&catalog).expect("resolve catalog");
        let tree = HandleDict::new();
        tree.insert("Names", ObjectHandle::array(Vec::new()));
        let names = HandleDict::new();
        names.insert("EmbeddedFiles", tree.into_handle());
        catalog
            .replace_key(b"/Names", names.into_handle())
            .expect("install empty EmbeddedFiles tree");
        pdf.mark_object_handle_dirty(&catalog)
            .expect("mark catalog dirty");

        assert_eq!(
            format_attachment_list(&mut pdf, true).expect("format"),
            Some(Vec::new()),
            "an empty tree lists nothing, but the document does have the tree"
        );
    }

    /// Point `/Names /EmbeddedFiles` straight at `[key value]`, bypassing the
    /// name-tree writer so the value shape can be chosen freely.
    fn attach_raw_tree_value(pdf: &mut Pdf<Cursor<Vec<u8>>>, key: &[u8], value: ObjectHandle) {
        let root = pdf.root_ref().expect("catalog");
        let catalog = pdf.get_object_handle(root);
        pdf.resolve(&catalog).expect("resolve catalog");
        let tree = HandleDict::new();
        tree.insert(
            "Names",
            ObjectHandle::array(vec![ObjectHandle::string(key.to_vec()), value]),
        );
        let names = HandleDict::new();
        names.insert("EmbeddedFiles", tree.into_handle());
        catalog
            .replace_key(b"/Names", names.into_handle())
            .expect("install raw EmbeddedFiles tree fixture");
        pdf.mark_object_handle_dirty(&catalog)
            .expect("mark catalog dirty");
    }

    // ── Name-tree value shapes ────────────────────────────────────────────────

    #[test]
    fn inline_filespec_value_is_listed() {
        let mut pdf = open_minimal();
        let stream_ref = add_ef_stream(&mut pdf, None, None);
        let ef = HandleDict::new();
        ef.insert("F", object_ref(&mut pdf, stream_ref));
        let filespec = HandleDict::new();
        filespec.insert("Type", ObjectHandle::name(b"Filespec".to_vec()));
        filespec.insert("F", ObjectHandle::string(b"j.txt".to_vec()));
        filespec.insert("EF", HandleDict::into_handle(ef));
        // A name-tree leaf may hold the /Filespec inline instead of by
        // reference; it must list exactly as an indirect one does.
        attach_raw_tree_value(&mut pdf, b"j.txt", HandleDict::into_handle(filespec));

        let n = stream_ref.number;
        assert_eq!(
            as_text(&listing(&mut pdf, true)),
            format!(
                "j.txt -> {n},0\n\
                 \x20 preferred name: j.txt\n\
                 \x20 all names:\n\
                 \x20   /F -> j.txt\n\
                 \x20 all data streams:\n\
                 \x20   /F -> {n},0\n\
                 \x20     creation date: \n\
                 \x20     modification date: \n\
                 \x20     mime type: \n\
                 \x20     checksum: \n"
            )
        );
    }

    #[test]
    fn non_dictionary_filespec_value_still_lists_the_key() {
        // qpdf warns ("Embedded file object is not a dictionary") and carries
        // on with empty values rather than failing the listing.
        let mut direct_pdf = Pdf::open(Cursor::new(inline_non_dictionary_filespec_pdf_bytes()))
            .expect("open direct non-dictionary Filespec fixture");
        assert_eq!(
            as_text(&listing(&mut direct_pdf, true)),
            "k.txt -> 0,0\n  preferred name: \n  all names:\n  all data streams:\n",
        );
        assert!(
            direct_pdf
                .repair_diagnostics()
                .entries()
                .iter()
                .any(|diagnostic| diagnostic
                    .message
                    .contains("Embedded file object is not a dictionary")),
            "QPDFFileSpecObjectHelper must warn for a direct non-dictionary Filespec"
        );

        let mut dangling_pdf = open_minimal();
        let dangling = object_ref(&mut dangling_pdf, ObjectRef::new(4096, 0));
        attach_raw_tree_value(&mut dangling_pdf, b"k.txt", dangling);
        assert_eq!(
            as_text(&listing(&mut dangling_pdf, true)),
            "k.txt -> 0,0\n  preferred name: \n  all names:\n  all data streams:\n",
        );
        assert!(
            dangling_pdf
                .repair_diagnostics()
                .entries()
                .iter()
                .any(|diagnostic| diagnostic
                    .message
                    .contains("Embedded file object is not a dictionary")),
            "QPDFFileSpecObjectHelper must warn for a dangling Filespec"
        );
    }

    // ── Name-tree keys use qpdf's UTF-8 view ──────────────────────────────────

    #[test]
    fn header_key_uses_the_qpdf_utf8_view() {
        let mut pdf = open_minimal();
        // Name-tree keys are qpdf's UTF-8 view on the way in; the tree stores
        // them as UTF-16BE PDF strings, so a listing that echoed the stored
        // bytes would be mojibake.
        for (key, filename) in [
            ("π.txt".as_bytes().to_vec(), b"pi.txt".as_slice()),
            ("café.txt".as_bytes().to_vec(), b"cafe.txt".as_slice()),
        ] {
            let stream_ref = add_ef_stream(&mut pdf, None, None);
            let ef = HandleDict::new();
            ef.insert("F", object_ref(&mut pdf, stream_ref));
            let filespec = HandleDict::new();
            filespec.insert("F", ObjectHandle::string(filename.to_vec()));
            filespec.insert("EF", HandleDict::into_handle(ef));
            attach(&mut pdf, &key, filespec);
        }

        let out = as_text(&listing(&mut pdf, false));
        let keys: Vec<&str> = out
            .lines()
            .map(|line| line.split(" -> ").next().expect("header key"))
            .collect();
        assert_eq!(
            keys,
            vec!["café.txt", "π.txt"],
            "keys decode through qpdf's UTF-8 view and order by the converted \
             bytes: {out:?}"
        );
    }

    // ── /UF absent → /F used as display name ─────────────────────────────────

    #[test]
    fn f_only_filespec_uses_f_as_display_name() {
        let mut pdf = open_minimal();

        // Minimal EmbeddedFile stream (no /Params → missing size/dates/checksum).
        let stream_ref = add_ef_stream(&mut pdf, None, None);
        let ef_sub = HandleDict::new();
        ef_sub.insert("F", object_ref(&mut pdf, stream_ref));

        // Filespec with /F only (no /UF).
        let fs_dict = HandleDict::new();
        fs_dict.insert("Type", ObjectHandle::name(b"Filespec".to_vec()));
        fs_dict.insert("F", ObjectHandle::string(b"only-f.txt".to_vec()));
        fs_dict.insert("EF", HandleDict::into_handle(ef_sub));
        attach(&mut pdf, b"only-f.txt", fs_dict);

        let infos = list_attachment_info(&mut pdf).expect("list");
        assert_eq!(infos.len(), 1);
        assert_eq!(
            infos[0].display_name.as_deref(),
            Some("only-f.txt"),
            "/F must be used as display name when /UF is absent"
        );

        let listed = as_text(&listing(&mut pdf, true));
        assert!(
            listed.contains("  preferred name: only-f.txt\n"),
            "the listing falls back to /F for the preferred name: {listed:?}"
        );
    }

    // ── /UF (UTF-16BE) is decoded correctly ──────────────────────────────────

    #[test]
    fn uf_utf16be_is_decoded_for_display() {
        let mut pdf = open_minimal();

        // FileSpecBuilder writes /UF as UTF-16BE.
        let fs_ref = FileSpecBuilder::new("hello.txt", b"hi")
            .build(&mut pdf)
            .expect("build");
        insert_embedded_file(&mut pdf, b"hello.txt", fs_ref).expect("insert");

        let infos = list_attachment_info(&mut pdf).expect("list");
        assert_eq!(infos.len(), 1);
        assert_eq!(
            infos[0].display_name.as_deref(),
            Some("hello.txt"),
            "/UF must decode to the original filename"
        );
    }

    // ── checksum is hex-encoded ───────────────────────────────────────────────

    #[test]
    fn checksum_displayed_as_lowercase_hex() {
        let mut pdf = open_minimal();

        let payload = b"checksum test";
        let fs_ref = FileSpecBuilder::new("chk.txt", payload.as_ref())
            .build(&mut pdf)
            .expect("build");
        insert_embedded_file(&mut pdf, b"chk.txt", fs_ref).expect("insert");

        let infos = list_attachment_info(&mut pdf).expect("list");
        assert_eq!(infos.len(), 1);

        let verbose = as_text(&listing(&mut pdf, true));
        // The checksum line must contain lowercase hex, not raw bytes.
        // The actual MD5 of b"checksum test" is deterministic; verify format.
        let chk_line = verbose
            .lines()
            .find(|l| l.trim_start().starts_with("checksum:"))
            .expect("checksum line must be present");
        let hex_part = chk_line.split(':').nth(1).unwrap_or("").trim();
        // Must be all hex digits (32 chars for MD5).
        assert!(
            hex_part.len() == 32 && hex_part.chars().all(|c| c.is_ascii_hexdigit()),
            "checksum must be 32-char lowercase hex: {hex_part:?}"
        );
        assert!(
            hex_part == hex_part.to_lowercase(),
            "checksum must be lowercase: {hex_part:?}"
        );
    }

    // ── dates and full metadata with FileSpecBuilder ──────────────────────────

    #[test]
    fn full_metadata_attachment() {
        let mut pdf = open_minimal();

        let dates = FileParamDates {
            creation: Some((2026, 1, 1, 0, 0, 0)),
            modification: Some((2026, 6, 15, 12, 30, 0)),
        };
        let fs_ref = FileSpecBuilder::new("full.txt", b"full payload")
            .mimetype(b"text/plain")
            .description(b"Full test attachment")
            .af_relationship(b"Data")
            .dates(dates)
            .build(&mut pdf)
            .expect("build");
        insert_embedded_file(&mut pdf, b"full.txt", fs_ref).expect("insert");

        let infos = list_attachment_info(&mut pdf).expect("list");
        assert_eq!(infos.len(), 1);
        let info = &infos[0];

        assert_eq!(info.key, b"full.txt");
        assert_eq!(info.display_name.as_deref(), Some("full.txt"));
        assert_eq!(info.size, Some(12));
        assert_eq!(
            info.mimetype.as_deref(),
            Some(b"text/plain".as_ref()),
            "mimetype must match"
        );
        assert_eq!(
            info.creation_date.as_deref(),
            Some(format_pdf_date(2026, 1, 1, 0, 0, 0).as_slice()),
        );
        assert_eq!(
            info.modification_date.as_deref(),
            Some(format_pdf_date(2026, 6, 15, 12, 30, 0).as_slice()),
        );
        assert_eq!(
            info.description.as_deref(),
            Some(b"Full test attachment".as_ref())
        );
        assert_eq!(info.af_relationship.as_deref(), Some(b"Data".as_ref()));
        assert!(info.checksum.is_some(), "checksum must be present");

        // The listing renders the same document through qpdf's layout.
        let formatted = as_text(&listing(&mut pdf, true));
        assert!(
            formatted.contains("      mime type: text/plain\n"),
            "{formatted:?}"
        );
        assert!(
            formatted.contains("      creation date: D:20260101000000Z\n"),
            "{formatted:?}"
        );
        assert!(
            formatted.contains("      modification date: D:20260615123000Z\n"),
            "{formatted:?}"
        );
        assert!(
            formatted.contains("  description: Full test attachment\n"),
            "{formatted:?}"
        );
        assert!(
            !formatted.contains("af relationship"),
            "qpdf's listing has no /AFRelationship line: {formatted:?}"
        );
    }

    // ── decode_pdf_text_string ────────────────────────────────────────────────

    #[test]
    fn decode_utf16be_bom() {
        let bytes = encode_utf16be("hello");
        assert_eq!(decode_pdf_text_string(&bytes), "hello");
    }

    #[test]
    fn decode_ascii_fallback() {
        let bytes = b"plain ascii".to_vec();
        assert_eq!(decode_pdf_text_string(&bytes), "plain ascii");
    }

    // Regression for roborev #953: non-ASCII PDFDocEncoding must decode via
    // the canonical ISO 32000-1 Annex D.3 table, not a lossy UTF-8 cast.
    #[test]
    fn decode_non_ascii_pdfdocencoding() {
        // 0x18 → U+02D8 BREVE (a PDF-specific PDFDocEncoding code point).
        assert_eq!(decode_pdf_text_string(&[0x18]), "\u{02D8}");
        // 0xE9 → U+00E9 'é' (PDFDocEncoding follows ISO-8859-1 in 0xA0..=0xFF).
        assert_eq!(decode_pdf_text_string(&[0xE9]), "é");
        // Mixed ASCII + non-ASCII PDFDocEncoding round-trips correctly rather
        // than emitting U+FFFD replacement characters.
        assert_eq!(decode_pdf_text_string(b"caf\xE9"), "café");
    }

    // Regression for roborev #953: /Desc verbose output must decode PDF text
    // strings (here UTF-16BE) instead of showing mojibake.
    #[test]
    fn verbose_description_decodes_utf16be() {
        let mut pdf = open_minimal();
        let stream_ref = add_ef_stream(&mut pdf, None, None);
        let ef = HandleDict::new();
        ef.insert("F", object_ref(&mut pdf, stream_ref));
        let filespec = HandleDict::new();
        filespec.insert("F", ObjectHandle::string(b"k.txt".to_vec()));
        filespec.insert("Desc", ObjectHandle::string(encode_utf16be("dé")));
        filespec.insert("EF", HandleDict::into_handle(ef));
        attach(&mut pdf, b"k.txt", filespec);

        let formatted = as_text(&listing(&mut pdf, true));
        assert!(
            formatted.contains("  description: dé\n"),
            "UTF-16BE /Desc must be decoded: {formatted:?}"
        );
    }
}