flpdf 0.1.7

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
use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr;

/// Maximum inline structural nesting depth any operation walks when descending
/// into a single resolved object's `Array` / `Dictionary` / `Stream`-dictionary
/// structure. Indirect references are followed iteratively (a caller-driven
/// BFS/DFS with a visited set), so this bounds only inline nesting within one
/// object and guards every post-parse structural walker against stack overflow
/// on adversarial input.
///
/// Exceeding it is a hard error, never a silent stop: a walker that returned
/// early would under-collect or under-rewrite references and corrupt its output
/// (garbage collection would delete still-reachable objects; renumbering would
/// emit mixed old/new object numbers). Returning [`crate::Error::Unsupported`]
/// preserves the no-panic/no-abort core guarantee even for parser-accepted but
/// pathological objects.
///
/// Independent of (and may be lower than) the parser's `MAX_PARSE_DEPTH`:
/// operations cap inline traversal more tightly than parsing. Real PDFs never
/// nest inline structures this deeply — deep hierarchies use indirect
/// references, which travel through the iterative queue rather than this
/// recursion.
pub(crate) const MAX_INLINE_DEPTH: usize = 256;

/// Indirect-object reference (`N G R` in PDF syntax).
///
/// `ObjectRef` is a thin value type: it identifies an object by `(number, generation)`
/// and is what every other API in the crate uses to fetch, replace, or describe an object.
///
/// # Examples
///
/// ```
/// use flpdf::ObjectRef;
///
/// let object_ref = ObjectRef::new(12, 0);
/// assert_eq!(object_ref.to_string(), "12 0 R");
///
/// let parsed: ObjectRef = "12 0 R".parse().unwrap();
/// assert_eq!(parsed, object_ref);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ObjectRef {
    pub number: u32,
    pub generation: u16,
}

impl ObjectRef {
    /// Construct an `ObjectRef` from a raw `(number, generation)` pair.
    pub fn new(number: u32, generation: u16) -> Self {
        Self { number, generation }
    }

    /// Parse `"N G"` or `"N G R"` (the textual form used by qpdf-style CLIs).
    ///
    /// Whitespace between tokens is collapsed and the trailing `R` is optional, mirroring
    /// the indirect-reference syntax that qpdf accepts on its command line.
    ///
    /// # Errors
    ///
    /// Returns [`ParseObjectRefError`] when `input` is not a valid reference:
    /// - it does not split into exactly two or three whitespace-separated tokens;
    /// - it has three tokens but the third is not `R`;
    /// - the first token does not parse as a [`u32`] object number;
    /// - the second token does not parse as a [`u16`] generation.
    ///
    /// # Examples
    ///
    /// ```
    /// use flpdf::ObjectRef;
    ///
    /// assert_eq!(ObjectRef::parse("12 0").unwrap(), ObjectRef::new(12, 0));
    /// assert_eq!(ObjectRef::parse("12 0 R").unwrap(), ObjectRef::new(12, 0));
    /// assert!(ObjectRef::parse("bad").is_err());
    /// ```
    pub fn parse(input: &str) -> std::result::Result<Self, ParseObjectRefError> {
        let parts: Vec<&str> = input.split_whitespace().collect();
        if parts.len() != 2 && parts.len() != 3 {
            return Err(ParseObjectRefError::new(format!(
                "invalid object ref '{input}'"
            )));
        }
        if parts.len() == 3 && parts[2] != "R" {
            return Err(ParseObjectRefError::new(format!(
                "invalid object ref '{input}'"
            )));
        }
        let number = parts[0]
            .parse::<u32>()
            .map_err(|_| ParseObjectRefError::new(format!("invalid object number in '{input}'")))?;
        let generation = parts[1].parse::<u16>().map_err(|_| {
            ParseObjectRefError::new(format!("invalid object generation in '{input}'"))
        })?;
        Ok(Self::new(number, generation))
    }
}

impl fmt::Display for ObjectRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {} R", self.number, self.generation)
    }
}

impl FromStr for ObjectRef {
    type Err = ParseObjectRefError;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Self::parse(s)
    }
}

/// Error returned when [`ObjectRef::parse`] / `<ObjectRef as FromStr>::from_str` cannot
/// interpret an input string as an indirect-object reference.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseObjectRefError {
    message: String,
}

impl ParseObjectRefError {
    fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }
}

impl fmt::Display for ParseObjectRefError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

impl std::error::Error for ParseObjectRefError {}

/// Direct PDF object value (ISO 32000-1 §7.3).
///
/// All node types in the PDF object graph are represented here. Indirect references
/// are stored as [`Object::Reference`] until they are explicitly resolved with
/// [`Pdf::resolve`](crate::Pdf::resolve).
#[derive(Debug, Clone, PartialEq)]
pub enum Object {
    Null,
    Boolean(bool),
    Integer(i64),
    Real(f64),
    Name(Vec<u8>),
    String(Vec<u8>),
    Array(Vec<Object>),
    Dictionary(Dictionary),
    Stream(Stream),
    Reference(ObjectRef),
}

impl Object {
    /// Convenience constructor for [`Object::Reference`].
    pub fn reference(object_ref: ObjectRef) -> Self {
        Self::Reference(object_ref)
    }

    /// Return this object as a dictionary, if it is [`Object::Dictionary`].
    pub fn as_dict(&self) -> Option<&Dictionary> {
        match self {
            Object::Dictionary(dict) => Some(dict),
            _ => None,
        }
    }

    /// Return this object as a mutable dictionary, if it is [`Object::Dictionary`].
    pub fn as_dict_mut(&mut self) -> Option<&mut Dictionary> {
        match self {
            Object::Dictionary(dict) => Some(dict),
            _ => None,
        }
    }

    /// Return this object as a stream, if it is [`Object::Stream`].
    pub fn as_stream(&self) -> Option<&Stream> {
        match self {
            Object::Stream(stream) => Some(stream),
            _ => None,
        }
    }

    /// Return this object as a mutable stream, if it is [`Object::Stream`].
    pub fn as_stream_mut(&mut self) -> Option<&mut Stream> {
        match self {
            Object::Stream(stream) => Some(stream),
            _ => None,
        }
    }

    /// Return this object as an array slice, if it is [`Object::Array`].
    pub fn as_array(&self) -> Option<&[Object]> {
        match self {
            Object::Array(values) => Some(values),
            _ => None,
        }
    }

    /// Return this object as a mutable array vector, if it is [`Object::Array`].
    pub fn as_array_mut(&mut self) -> Option<&mut Vec<Object>> {
        match self {
            Object::Array(values) => Some(values),
            _ => None,
        }
    }

    /// Return this object as decoded PDF name bytes, if it is [`Object::Name`].
    pub fn as_name(&self) -> Option<&[u8]> {
        match self {
            Object::Name(name) => Some(name),
            _ => None,
        }
    }

    /// Return this object as string bytes, if it is [`Object::String`].
    pub fn as_string(&self) -> Option<&[u8]> {
        match self {
            Object::String(value) => Some(value),
            _ => None,
        }
    }

    /// Return this object as an integer, if it is [`Object::Integer`].
    pub fn as_integer(&self) -> Option<i64> {
        match self {
            Object::Integer(value) => Some(*value),
            _ => None,
        }
    }

    /// Return this object as a real number, if it is [`Object::Real`].
    pub fn as_real(&self) -> Option<f64> {
        match self {
            Object::Real(value) => Some(*value),
            _ => None,
        }
    }

    /// Return this object as a boolean, if it is [`Object::Boolean`].
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Object::Boolean(value) => Some(*value),
            _ => None,
        }
    }

    /// Return this object as an indirect-object reference, if it is [`Object::Reference`].
    pub fn as_ref_id(&self) -> Option<ObjectRef> {
        match self {
            Object::Reference(object_ref) => Some(*object_ref),
            _ => None,
        }
    }

    /// Consume this object and return its dictionary, if it is [`Object::Dictionary`].
    pub fn into_dict(self) -> Option<Dictionary> {
        match self {
            Object::Dictionary(dict) => Some(dict),
            _ => None,
        }
    }

    /// Consume this object and return its stream, if it is [`Object::Stream`].
    pub fn into_stream(self) -> Option<Stream> {
        match self {
            Object::Stream(stream) => Some(stream),
            _ => None,
        }
    }

    /// Consume this object and return its array, if it is [`Object::Array`].
    pub fn into_array(self) -> Option<Vec<Object>> {
        match self {
            Object::Array(values) => Some(values),
            _ => None,
        }
    }

    /// Consume this object and return its decoded PDF name bytes, if it is [`Object::Name`].
    pub fn into_name(self) -> Option<Vec<u8>> {
        match self {
            Object::Name(name) => Some(name),
            _ => None,
        }
    }

    /// Consume this object and return its string bytes, if it is [`Object::String`].
    pub fn into_string(self) -> Option<Vec<u8>> {
        match self {
            Object::String(value) => Some(value),
            _ => None,
        }
    }

    /// Return true if this object is [`Object::Null`].
    pub fn is_null(&self) -> bool {
        matches!(self, Object::Null)
    }

    /// Serialize this object into PDF syntax, appending to `out`.
    ///
    /// Strings whose bytes are all printable are emitted as literal `(...)` strings;
    /// otherwise hex `<...>` strings are used. Streams are emitted as their dictionary
    /// followed by `stream` ... `endstream`.
    ///
    /// # Examples
    ///
    /// ```
    /// use flpdf::{Object, ObjectRef};
    /// let mut out = Vec::new();
    /// Object::reference(ObjectRef::new(7, 0)).write_pdf(&mut out);
    /// assert_eq!(out, b"7 0 R");
    /// ```
    ///
    /// Array whitespace follows the qpdf token-boundary convention: a space is
    /// inserted between adjacent tokens unless both sides are PDF delimiters.
    ///
    /// ```
    /// use flpdf::Object;
    ///
    /// // Numeric array: spaces between integers and at both ends.
    /// let nums = Object::Array(vec![
    ///     Object::Integer(0),
    ///     Object::Integer(0),
    ///     Object::Integer(612),
    ///     Object::Integer(792),
    /// ]);
    /// let mut out = Vec::new();
    /// nums.write_pdf(&mut out);
    /// assert_eq!(out, b"[ 0 0 612 792 ]");
    ///
    /// // Hex-string array (/ID): both elements are delimiters, so no spaces.
    /// let id_array = Object::Array(vec![
    ///     Object::String(vec![0xabu8, 0xcdu8]),
    ///     Object::String(vec![0xefu8, 0x01u8]),
    /// ]);
    /// let mut out = Vec::new();
    /// id_array.write_pdf(&mut out);
    /// assert_eq!(out, b"[<abcd><ef01>]");
    ///
    /// // Empty array.
    /// let empty = Object::Array(vec![]);
    /// let mut out = Vec::new();
    /// empty.write_pdf(&mut out);
    /// assert_eq!(out, b"[ ]");
    ///
    /// // Stream followed by a number: the stream's serialized form ends with
    /// // the `endstream` keyword (a letter, not a delimiter), so a separating
    /// // space must precede the next token.
    /// use flpdf::object::{Dictionary, Stream};
    /// let stream = Object::Stream(Stream::new(Dictionary::new(), vec![]));
    /// let mixed = Object::Array(vec![stream, Object::Integer(7)]);
    /// let mut out = Vec::new();
    /// mixed.write_pdf(&mut out);
    /// // The exact stream bytes vary; what matters is that a space appears
    /// // between `endstream` and `7`.
    /// assert!(
    ///     out.windows(b"endstream 7".len()).any(|w| w == b"endstream 7"),
    ///     "got: {:?}",
    ///     std::str::from_utf8(&out).unwrap_or("<binary>"),
    /// );
    /// ```
    pub fn write_pdf(&self, out: &mut Vec<u8>) {
        match self {
            Object::Null => out.extend_from_slice(b"null"),
            Object::Boolean(value) => {
                out.extend_from_slice(if *value { b"true" } else { b"false" })
            }
            Object::Integer(value) => out.extend_from_slice(value.to_string().as_bytes()),
            Object::Real(value) => out.extend_from_slice(value.to_string().as_bytes()),
            Object::Name(name) => {
                out.push(b'/');
                write_name_escaped(out, name);
            }
            Object::String(value) => {
                if is_printable_string(value) {
                    write_literal_string(out, value);
                } else {
                    write_hex_string(out, value);
                }
            }
            Object::Array(values) => {
                if values.is_empty() {
                    out.extend_from_slice(b"[ ]");
                    return;
                }
                out.push(b'[');
                // qpdf token-boundary rule: insert a space between adjacent tokens
                // unless both sides are PDF delimiters (`<`, `(`, `[`, `/`, `>`, `)`, `]`).
                // `[` itself counts as a delimiter on the left.
                // qpdf rule: omit the space only when BOTH sides are delimiters.
                // `[` is treated as a delimiter on the left for the first element.
                let mut prev_ends_with_delim = true; // treat `[` as delimiter
                for value in values.iter() {
                    // Insert a space unless both the previous token end AND the
                    // current token start are PDF delimiters.
                    if !(prev_ends_with_delim && starts_with_delim(value)) {
                        out.push(b' ');
                    }
                    value.write_pdf(out);
                    prev_ends_with_delim = ends_with_delim(value);
                }
                // Add trailing space before `]` unless the last token ends with a delimiter.
                // (`]` is also a delimiter, so we only omit if prev is also delimiter.)
                if !prev_ends_with_delim {
                    out.push(b' ');
                }
                out.push(b']');
            }
            Object::Dictionary(dict) => dict.write_pdf(out),
            Object::Stream(stream) => {
                stream.dict.write_pdf(out);
                out.extend_from_slice(b"\nstream\n");
                out.extend_from_slice(&stream.data);
                out.extend_from_slice(b"\nendstream");
            }
            Object::Reference(object_ref) => {
                out.extend_from_slice(object_ref.to_string().as_bytes())
            }
        }
    }

    /// Serialize this object into qpdf `--qdf` formatting conventions, appending
    /// to `out`. `indent` is the column (number of leading spaces) at which the
    /// *opening* delimiter of a container sits; children are indented by
    /// `indent + 2`, and a container's closing delimiter (`>>` / `]`) is emitted
    /// on its own line at column `indent`.
    ///
    /// Only container layout (dictionaries, arrays) and stream framing differ
    /// from [`Object::write_pdf`]; every scalar / name / string / number /
    /// reference delegates to the existing compact serializer so number
    /// formatting, string escaping, name encoding, and `N G R` references are
    /// byte-identical to the non-qdf path. Dictionary keys are emitted in the
    /// `Dictionary`'s natural (`BTreeMap`, lexicographic-by-raw-name) order,
    /// which is exactly qpdf's alphabetical key sort.
    ///
    /// This is used **only** on the qdf full-rewrite path; the non-qdf path is
    /// untouched.
    pub(crate) fn write_pdf_qdf(&self, out: &mut Vec<u8>, indent: usize) {
        match self {
            Object::Array(values) => {
                out.push(b'[');
                out.push(b'\n');
                for value in values.iter() {
                    push_spaces(out, indent + 2);
                    value.write_pdf_qdf(out, indent + 2);
                    out.push(b'\n');
                }
                push_spaces(out, indent);
                out.push(b']');
            }
            Object::Dictionary(dict) => dict.write_pdf_qdf(out, indent),
            Object::Stream(stream) => {
                stream.dict.write_pdf_qdf(out, indent);
                out.extend_from_slice(b"\nstream\n");
                out.extend_from_slice(&stream.data);
                out.extend_from_slice(b"\nendstream");
            }
            // Scalars, names, strings, numbers, references, null, booleans:
            // reuse the existing compact serialization verbatim.
            _ => self.write_pdf(out),
        }
    }
}

/// Append `n` ASCII space bytes to `out`.
fn push_spaces(out: &mut Vec<u8>, n: usize) {
    out.resize(out.len() + n, b' ');
}

/// Escape a name's raw (logical) bytes into PDF name-token syntax per
/// ISO 32000-1 §7.3.5: any byte outside the printable ASCII range
/// `0x21..=0x7E`, any PDF delimiter (`( ) < > [ ] { } / %`), and `#`
/// itself are written as `#XX` (two uppercase hex digits). All other
/// bytes pass through unchanged.
///
/// `Object::Name` always holds *decoded* bytes (the parser unescapes
/// `#XX` on read — see `Parser::name`), so escaping on write keeps the
/// read/write pair symmetric: `Name(b"application/pdf")` serializes to
/// `/application#2Fpdf` and round-trips back to `application/pdf`.
/// Conventional names (`Type`, `Page`, `FlateDecode`, …) contain no
/// escapable bytes, so their output is byte-identical to before.
pub(crate) fn write_name_escaped(out: &mut Vec<u8>, raw: &[u8]) {
    const HEX: &[u8; 16] = b"0123456789ABCDEF";
    for &b in raw {
        let needs_escape = !(0x21..=0x7E).contains(&b)
            || matches!(
                b,
                b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%' | b'#'
            );
        if needs_escape {
            out.push(b'#');
            out.push(HEX[(b >> 4) as usize]);
            out.push(HEX[(b & 0x0F) as usize]);
        } else {
            out.push(b);
        }
    }
}

/// Returns `true` when the serialized form of `o` starts with a self-separating
/// PDF delimiter byte (`<`, `(`, `[`, `<<`). Used by [`Object::write_pdf`] to
/// decide whether to insert a space before this token inside an array.
///
/// Note: [`Object::Name`] starts with `/` — technically a delimiter byte — but
/// qpdf inserts a space before names anyway (`[ /PDF /Text ]` rather than
/// `[/PDF /Text]`), so names are deliberately excluded from this set to match
/// qpdf's array-writer convention.
fn starts_with_delim(o: &Object) -> bool {
    matches!(
        o,
        Object::String(_) | Object::Array(_) | Object::Dictionary(_) | Object::Stream(_)
    )
}

/// Returns `true` when the serialized form of `o` ends with a PDF delimiter byte
/// (`>`, `)`, `]`). Used by [`Object::write_pdf`] to decide whether to insert
/// a space after this token inside an array.
///
/// Excluded types end with a letter (`Name` → arbitrary letter from the name;
/// `Stream` → the `endstream` keyword), so a following token in an array would
/// run together without a separating space if these were treated as
/// delimiter-terminated.
fn ends_with_delim(o: &Object) -> bool {
    matches!(
        o,
        Object::String(_) | Object::Array(_) | Object::Dictionary(_)
    )
}

/// Returns `true` when `value` can be emitted as a single-line literal string
/// `(...)`. qpdf uses the literal form whenever every byte is printable ASCII
/// (0x20–0x7e) even if the value contains `(`, `)`, or `\` — those simply
/// need escaping. We mirror that: only CR / LF force the hex fallback because
/// flpdf does not currently emit multi-line literals.
fn is_printable_string(value: &[u8]) -> bool {
    value
        .iter()
        .all(|byte| (0x20..=0x7e).contains(byte) && !matches!(*byte, b'\r' | b'\n'))
}

pub(crate) fn write_literal_string(out: &mut Vec<u8>, value: &[u8]) {
    out.push(b'(');
    for byte in value {
        match byte {
            b'\\' | b'(' | b')' => {
                out.push(b'\\');
                out.push(*byte);
            }
            _ => out.push(*byte),
        }
    }
    out.push(b')');
}

fn write_hex_string(out: &mut Vec<u8>, value: &[u8]) {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    out.push(b'<');
    for byte in value {
        out.push(HEX[(byte >> 4) as usize]);
        out.push(HEX[(byte & 0x0f) as usize]);
    }
    out.push(b'>');
}

/// Callback that writes a trailer's `/ID` array value at the current output
/// position, used by [`Dictionary::write_pdf_trailer`] to emit a value computed
/// from the bytes written so far (the deterministic-`/ID` direct-write path).
pub(crate) type TrailerIdWriter<'a> = &'a mut dyn FnMut(&mut Vec<u8>);

/// Like [`TrailerIdWriter`] but with the borrow lifetime (`'r`) and the closure
/// data lifetime (`'d`) decoupled, so the same `Option<&mut dyn FnMut>` can be
/// reborrowed (`as_deref_mut`) and forwarded to more than one callee. The
/// linearized writer emits `/ID` at two trailer sites in one pass, so it needs
/// this two-lifetime form; the single-lifetime [`TrailerIdWriter`] suffices for
/// the flat path's single trailer.
pub(crate) type ReborrowableIdWriter<'r, 'd> = &'r mut (dyn FnMut(&mut Vec<u8>) + 'd);

/// PDF dictionary, keyed by raw byte slices (PDF names are arbitrary byte strings).
///
/// Backed by a `BTreeMap`, so iteration order is the lexicographic order of the keys —
/// not the order entries were inserted in. Use [`get`](Self::get) /
/// [`get_ref`](Self::get_ref) for typed access.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Dictionary {
    entries: BTreeMap<Vec<u8>, Object>,
}

impl Dictionary {
    /// Create an empty dictionary.
    pub fn new() -> Self {
        Self::default()
    }

    /// Insert (or replace) `key` with `value`.
    pub fn insert(&mut self, key: impl AsRef<[u8]>, value: Object) {
        self.entries.insert(key.as_ref().to_vec(), value);
    }

    /// Look up `key`. Returns `None` if the dictionary does not contain that name.
    pub fn get(&self, key: impl AsRef<[u8]>) -> Option<&Object> {
        self.entries.get(key.as_ref())
    }

    /// Like [`get`](Self::get) but returns the [`ObjectRef`] only when the value is an
    /// indirect reference. Helpful when the spec mandates a reference and you want to
    /// follow it without matching `Object::Reference` manually.
    pub fn get_ref(&self, key: impl AsRef<[u8]>) -> Option<ObjectRef> {
        match self.get(key) {
            Some(Object::Reference(object_ref)) => Some(*object_ref),
            _ => None,
        }
    }

    /// Remove `key`, returning the previous value if any.
    pub fn remove(&mut self, key: impl AsRef<[u8]>) -> Option<Object> {
        self.entries.remove(key.as_ref())
    }

    /// Iterate `(name, value)` pairs in lexicographic order of names.
    pub fn iter(&self) -> impl Iterator<Item = (&[u8], &Object)> {
        self.entries
            .iter()
            .map(|(key, value)| (key.as_slice(), value))
    }

    pub(crate) fn values_mut(&mut self) -> impl Iterator<Item = &mut Object> {
        self.entries.values_mut()
    }

    pub(crate) fn write_pdf(&self, out: &mut Vec<u8>) {
        out.extend_from_slice(b"<<");
        for (key, value) in self.iter() {
            out.extend_from_slice(b" /");
            out.extend_from_slice(key);
            out.push(b' ');
            value.write_pdf(out);
        }
        out.extend_from_slice(b" >>");
    }

    /// Serialize this dictionary like [`write_pdf`](Self::write_pdf) (compact,
    /// plain lexicographic key order), but when `id_writer` is `Some` produce
    /// the `/ID` *value* from that closure instead of serializing the stored
    /// value (the ` /ID ` key token is still emitted at its sorted position).
    ///
    /// Every other key — and the `/ID` key itself when `id_writer` is `None` —
    /// is written byte-for-byte identically to [`write_pdf`](Self::write_pdf),
    /// so the two serializers agree except for the substituted `/ID` value.
    /// This lets the caller compute the `/ID` directly from the bytes written so
    /// far — used by the deterministic-`/ID` writer to emit a content-derived
    /// identifier inline rather than via a placeholder-then-patch step. Unlike
    /// the trailer, the cross-reference *stream* dictionary keeps `/ID` at its
    /// lexicographic position (it is not forced last), so the closure runs
    /// mid-iteration when the `/ID` key is reached.
    pub(crate) fn write_pdf_with_id_writer(
        &self,
        out: &mut Vec<u8>,
        id_writer: Option<TrailerIdWriter>,
    ) {
        out.extend_from_slice(b"<<");
        let mut id_writer = id_writer;
        for (key, value) in self.iter() {
            out.extend_from_slice(b" /");
            out.extend_from_slice(key);
            out.push(b' ');
            match (key == b"ID", id_writer.as_mut()) {
                (true, Some(write_id)) => write_id(out),
                _ => value.write_pdf(out),
            }
        }
        out.extend_from_slice(b" >>");
    }

    /// Serialize a stream's dictionary using qpdf's stream-dictionary key
    /// ordering, appending to `out`.
    ///
    /// qpdf (see `QPDFWriter::unparseObject`, stream branch) does not emit a
    /// stream dictionary in plain lexicographic order. It pulls `/Length` out
    /// of the key iteration and writes it explicitly after the remaining keys;
    /// and when it re-encodes ("filters") the stream, it also pulls `/Filter`
    /// and `/DecodeParms` out and re-appends `/Filter /FlateDecode` after
    /// `/Length`. The remaining keys keep their sorted order, which already
    /// matches this dictionary's `BTreeMap` iteration.
    ///
    /// The resulting layout is therefore:
    /// - re-filtered: `[other keys sorted] /Length N /Filter /FlateDecode`
    /// - preserved:   `[other keys sorted, incl. /Filter] /Length N`
    ///
    /// `refiltered` selects between the two. The `/Length` value is taken from
    /// this dictionary (the writer stores the on-disk byte count before
    /// serialization); if `/Length` is absent it is simply omitted.
    pub(crate) fn write_pdf_stream(&self, out: &mut Vec<u8>, refiltered: bool) {
        out.extend_from_slice(b"<<");
        // Capture /Length during the single iteration (it is appended after the
        // other keys) instead of looking it up again afterwards.
        let mut length_value: Option<&Object> = None;
        for (key, value) in self.iter() {
            if key == b"Length" {
                length_value = Some(value);
                continue;
            }
            if refiltered && (key == b"Filter" || key == b"DecodeParms") {
                continue;
            }
            out.extend_from_slice(b" /");
            out.extend_from_slice(key);
            out.push(b' ');
            value.write_pdf(out);
        }
        if let Some(length) = length_value {
            out.extend_from_slice(b" /Length ");
            length.write_pdf(out);
        }
        if refiltered {
            out.extend_from_slice(b" /Filter /FlateDecode");
        }
        out.extend_from_slice(b" >>");
    }

    /// Serialize a document trailer dictionary in qpdf's trailer key order,
    /// appending to `out`.
    ///
    /// qpdf writes the trailer with every key in sorted (`BTreeMap`) order
    /// **except `/ID`, which is pulled out and emitted last** — structurally the
    /// same special-casing it applies to `/Length` in stream dictionaries (see
    /// [`write_pdf_stream`](Self::write_pdf_stream)). Verified against
    /// `qpdf --static-id` 11.9.0: `<< /Info .. /Root .. /Size N /ID [..] >>`.
    /// Layout otherwise matches [`write_pdf`](Self::write_pdf) (compact, one
    /// line). If `/ID` is absent the output is plain sorted order.
    ///
    /// When `id_writer` is `Some`, the `/ID` *value* is produced by that closure
    /// (the `b" /ID "` key token is still emitted) instead of serializing the
    /// dictionary's stored `/ID` value. This lets the caller compute the `/ID`
    /// directly from the bytes written so far — used by the deterministic-`/ID`
    /// writer to emit qpdf's content-derived identifier inline rather than via a
    /// placeholder-then-patch step. The closure runs only when the `/ID` key is
    /// present in the dictionary; if it is absent, `id_writer` is ignored.
    pub(crate) fn write_pdf_trailer(&self, out: &mut Vec<u8>, id_writer: Option<TrailerIdWriter>) {
        out.extend_from_slice(b"<<");
        let mut id_value: Option<&Object> = None;
        for (key, value) in self.iter() {
            if key == b"ID" {
                id_value = Some(value);
                continue;
            }
            out.extend_from_slice(b" /");
            out.extend_from_slice(key);
            out.push(b' ');
            value.write_pdf(out);
        }
        if let Some(value) = id_value {
            out.extend_from_slice(b" /ID ");
            match id_writer {
                Some(write_id) => write_id(out),
                None => value.write_pdf(out),
            }
        }
        out.extend_from_slice(b" >>");
    }

    /// Serialize this dictionary in qpdf `--qdf` formatting: `<<` then one
    /// `  /Key value` entry per line (keys in lexicographic-by-raw-name order,
    /// which is qpdf's alphabetical sort, with exactly one ASCII space between
    /// key and value), then `>>` on its own line at column `indent`. Values are
    /// serialized with [`Object::write_pdf_qdf`] so nested containers add
    /// another `+2` indent level. An empty dictionary renders as
    /// `<<\n<indent>>>`.
    ///
    /// `/Length` (and every other key) is emitted verbatim — this serializer
    /// never recomputes or special-cases `/Length`; the stream-write path has
    /// already stored the correct value before serialization.
    pub(crate) fn write_pdf_qdf(&self, out: &mut Vec<u8>, indent: usize) {
        out.extend_from_slice(b"<<\n");
        for (key, value) in self.iter() {
            push_spaces(out, indent + 2);
            out.push(b'/');
            write_name_escaped(out, key);
            out.push(b' ');
            value.write_pdf_qdf(out, indent + 2);
            out.push(b'\n');
        }
        push_spaces(out, indent);
        out.extend_from_slice(b">>");
    }
}

/// PDF content stream: a dictionary plus an opaque byte payload.
///
/// `data` holds the raw, on-disk bytes — i.e. they are still encoded with whatever
/// filter chain `dict["Filter"]` declares. Use [`crate::filters::decode_stream_data`]
/// to obtain the decoded payload.
#[derive(Debug, Clone, PartialEq)]
pub struct Stream {
    pub dict: Dictionary,
    pub data: Vec<u8>,
}

impl Stream {
    /// Build a stream from its dictionary and its encoded payload.
    pub fn new(dict: Dictionary, data: Vec<u8>) -> Self {
        Self { dict, data }
    }
}

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

    /// A QDF dict key containing PDF delimiter / whitespace / non-ASCII bytes
    /// must be `#`-escaped exactly like the compact name serializer does, so the
    /// emitted `/Key` is a single valid PDF name token (regression: the QDF
    /// serializer previously wrote raw key bytes).
    #[test]
    fn qdf_dict_key_is_name_escaped() {
        let mut d = Dictionary::new();
        // space, '#', '/', and a non-ASCII byte all require escaping.
        d.insert(b"A B#C/D\x80E", Object::Integer(1));
        let mut out = Vec::new();
        d.write_pdf_qdf(&mut out, 0);
        let s = String::from_utf8(out).unwrap();
        assert!(
            s.contains("/A#20B#23C#2FD#80E 1"),
            "key not escaped in QDF output: {s:?}"
        );
        // No raw delimiter/space leaked into the name token.
        assert!(!s.contains("/A B"), "raw space leaked: {s:?}");
    }

    /// Keys that need no escaping are emitted verbatim (parity with qpdf).
    #[test]
    fn qdf_dict_plain_key_unescaped() {
        let mut d = Dictionary::new();
        d.insert(b"Type", Object::Name(b"Catalog".to_vec()));
        let mut out = Vec::new();
        d.write_pdf_qdf(&mut out, 0);
        assert_eq!(out, b"<<\n  /Type /Catalog\n>>");
    }
}

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

    /// A re-filtered two-key content-stream dict serializes `/Length` first,
    /// then `/Filter /FlateDecode`, matching `qpdf --static-id` output
    /// (`<< /Length 82 /Filter /FlateDecode >>`).
    #[test]
    fn refiltered_two_key_emits_length_then_filter() {
        let mut d = Dictionary::new();
        // Stored in lexicographic order by BTreeMap; the serializer reorders.
        d.insert(b"Filter", Object::Name(b"FlateDecode".to_vec()));
        d.insert(b"Length", Object::Integer(82));
        let mut out = Vec::new();
        d.write_pdf_stream(&mut out, true);
        assert_eq!(out, b"<< /Length 82 /Filter /FlateDecode >>");
    }

    /// When not re-filtered (qpdf preserves the existing filter), `/Filter`
    /// stays in its sorted position and `/Length` is emitted last.
    #[test]
    fn preserved_two_key_emits_filter_then_length_last() {
        let mut d = Dictionary::new();
        d.insert(b"Filter", Object::Name(b"FlateDecode".to_vec()));
        d.insert(b"Length", Object::Integer(82));
        let mut out = Vec::new();
        d.write_pdf_stream(&mut out, false);
        assert_eq!(out, b"<< /Filter /FlateDecode /Length 82 >>");
    }

    /// Preserved multi-key dict: `/Length` is pulled past later-sorting keys
    /// (`/Params`, `/Type`) to the very end, while `/Filter` stays in its
    /// sorted position. This is the qpdf order that makes the
    /// `attachment-two-page` `/EmbeddedFile` stream byte-identical, and it is
    /// the case that distinguishes `write_pdf_stream(false)` from the plain
    /// lexicographic [`Dictionary::write_pdf`] (which would leave `/Length` in
    /// its sorted position, before `/Params`).
    #[test]
    fn preserved_multi_key_moves_length_last_filter_stays_sorted() {
        let mut d = Dictionary::new();
        d.insert(b"Type", Object::Name(b"EmbeddedFile".to_vec()));
        d.insert(b"Params", Object::Dictionary(Dictionary::new()));
        d.insert(b"Length", Object::Integer(90));
        d.insert(b"Filter", Object::Name(b"FlateDecode".to_vec()));
        let mut out = Vec::new();
        d.write_pdf_stream(&mut out, false);
        assert_eq!(
            out,
            b"<< /Filter /FlateDecode /Params << >> /Type /EmbeddedFile /Length 90 >>".to_vec()
        );
    }

    /// The document trailer serializes every key in sorted order with `/ID`
    /// forced last, matching `qpdf --static-id`
    /// (`trailer << /Info .. /Root .. /Size N /ID [..] >>`).
    #[test]
    fn trailer_emits_sorted_keys_with_id_last() {
        let mut d = Dictionary::new();
        // Inserted out of order; BTreeMap sorts, write_pdf_trailer pulls /ID last.
        d.insert(b"Size", Object::Integer(8));
        d.insert(
            b"ID",
            Object::Array(vec![Object::Integer(1), Object::Integer(2)]),
        );
        d.insert(b"Info", Object::reference(ObjectRef::new(2, 0)));
        d.insert(b"Root", Object::reference(ObjectRef::new(1, 0)));
        let mut out = Vec::new();
        d.write_pdf_trailer(&mut out, None);
        assert_eq!(
            out,
            b"<< /Info 2 0 R /Root 1 0 R /Size 8 /ID [ 1 2 ] >>".to_vec()
        );
    }

    /// With an `id_writer`, the trailer substitutes the `/ID` *value* from the
    /// closure while still forcing `/ID` last in qpdf's order; every other key
    /// stays byte-identical to the `None` arm. Production only ever passes
    /// `Some` (the deterministic-`/ID` direct-write), so this pins that contract.
    #[test]
    fn trailer_id_writer_substitutes_value_but_keeps_id_last() {
        let mut d = Dictionary::new();
        d.insert(b"Size", Object::Integer(8));
        d.insert(
            b"ID",
            Object::Array(vec![Object::Integer(1), Object::Integer(2)]),
        );
        d.insert(b"Root", Object::reference(ObjectRef::new(1, 0)));
        let mut out = Vec::new();
        let mut id_writer = |o: &mut Vec<u8>| o.extend_from_slice(b"[<aa><bb>]");
        d.write_pdf_trailer(&mut out, Some(&mut id_writer));
        assert_eq!(out, b"<< /Root 1 0 R /Size 8 /ID [<aa><bb>] >>".to_vec());
    }

    /// A trailer without `/ID` is plain sorted order (no special handling).
    #[test]
    fn trailer_without_id_is_sorted() {
        let mut d = Dictionary::new();
        d.insert(b"Size", Object::Integer(3));
        d.insert(b"Root", Object::reference(ObjectRef::new(1, 0)));
        let mut out = Vec::new();
        d.write_pdf_trailer(&mut out, None);
        assert_eq!(out, b"<< /Root 1 0 R /Size 3 >>".to_vec());
    }

    /// Re-filtered multi-key dict: the other keys stay sorted, `/Filter` and
    /// `/DecodeParms` are dropped from the iteration, then `/Length` and the
    /// regenerated `/Filter /FlateDecode` are appended (qpdf's order).
    #[test]
    fn refiltered_multi_key_orders_others_then_length_then_filter() {
        let mut d = Dictionary::new();
        d.insert(b"Type", Object::Name(b"Foo".to_vec()));
        d.insert(b"Width", Object::Integer(100));
        d.insert(b"DecodeParms", Object::Dictionary(Dictionary::new()));
        d.insert(b"Filter", Object::Name(b"FlateDecode".to_vec()));
        d.insert(b"Length", Object::Integer(21));
        let mut out = Vec::new();
        d.write_pdf_stream(&mut out, true);
        assert_eq!(
            out,
            b"<< /Type /Foo /Width 100 /Length 21 /Filter /FlateDecode >>".to_vec()
        );
    }
}