rusty_pdf_core 0.1.0

Pure-Rust PDF reader core: objects, classic and stream cross-reference tables, object streams, incremental updates, broken-xref repair, RC4 and AES-128/256 decryption, stream filters, page tree, content streams, editing and save. Hostile input errors or stays bounded. No C, no unsafe.
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
//! The document: loading, object access, stream decoding and editing.

use crate::crypt::Security;
use crate::error::{Error, Result};
use crate::filters::{self, Cap};
use crate::object::{Blob, Dictionary, Object, ObjectId, Stream, NULL};
use crate::parser::{find, Parser};
use crate::xref::{self, Loc};
use crate::Limits;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};

/// How deep object loading may recurse (an indirect `/Length`, an object
/// stream container). Real files need two or three levels.
const MAX_LOAD_DEPTH: u32 = 8;
/// How many references in a row [`Document::resolve`] follows.
const MAX_REFERENCE_CHAIN: usize = 32;

/// Options for [`Document::load_with`].
#[derive(Debug, Clone, Default)]
pub struct LoadOptions {
    /// The user or owner password, for an encrypted file. Empty is what a
    /// file with no user password opens with.
    pub password: Vec<u8>,
    /// Bounds on what the file may ask for.
    pub limits: Limits,
}

impl LoadOptions {
    /// Options with `password` and default limits.
    #[must_use]
    pub fn with_password(password: impl Into<Vec<u8>>) -> Self {
        Self { password: password.into(), limits: Limits::default() }
    }
}

#[derive(Debug)]
enum SlotLoc {
    File(Loc),
    /// Created or changed in memory; the cell always holds the value.
    Memory,
}

#[derive(Debug)]
struct Slot {
    generation: u16,
    loc: SlotLoc,
    cell: OnceLock<Object>,
}

impl Slot {
    const fn file(generation: u16, loc: Loc) -> Self {
        Self { generation, loc: SlotLoc::File(loc), cell: OnceLock::new() }
    }

    fn memory(generation: u16, object: Object) -> Self {
        let cell = OnceLock::new();
        // A fresh cell: setting it cannot fail.
        let _ = cell.set(object);
        Self { generation, loc: SlotLoc::Memory, cell }
    }
}

/// A decoded object stream: its bytes and the (object number, offset) table.
#[derive(Debug)]
struct ObjectStream {
    data: Vec<u8>,
    index: Vec<(u32, usize)>,
}

/// A PDF document.
///
/// Loading reads the cross-reference data only. Objects are parsed (and
/// decrypted) the first time they are asked for, and kept. A `Document` is
/// `Sync`: pages can be read from several threads.
#[derive(Debug)]
pub struct Document {
    pub(crate) data: Arc<[u8]>,
    version: (u8, u8),
    slots: BTreeMap<u32, Slot>,
    pub(crate) trailer: Dictionary,
    security: Option<Security>,
    encrypt_object: Option<u32>,
    pub(crate) limits: Limits,
    repaired: bool,
    /// Offset of the newest cross-reference section, and whether it is a
    /// stream. `None` when there is nothing valid to chain an incremental
    /// save onto.
    pub(crate) previous_xref: Option<(usize, bool)>,
    object_streams: Mutex<BTreeMap<u32, Arc<ObjectStream>>>,
    object_stream_bytes: AtomicU64,
    pages: OnceLock<Vec<ObjectId>>,
    /// Object numbers changed, added or deleted since loading.
    pub(crate) dirty: BTreeSet<u32>,
    pub(crate) deleted: BTreeSet<u32>,
}

fn direct_length(l: &Object) -> Option<usize> {
    l.as_i64().ok().and_then(|v| usize::try_from(v).ok())
}

/// `%PDF-M.m` near the start of the file.
fn header_version(data: &[u8]) -> Option<(u8, u8)> {
    let at = find(&data[..data.len().min(1024)], b"%PDF-", 0)?;
    let rest = data.get(at + 5..at + 8)?;
    match rest {
        [major @ b'0'..=b'9', b'.', minor @ b'0'..=b'9'] => Some((major - b'0', minor - b'0')),
        _ => Some((1, 4)),
    }
}

impl Document {
    /// Load a PDF from memory, with default limits and the empty password.
    pub fn load(bytes: &[u8]) -> Result<Self> {
        Self::load_with(bytes, &LoadOptions::default())
    }

    /// Load a PDF from memory.
    ///
    /// The cross-reference data the file declares is used when it is
    /// consistent. When it is missing, points at the wrong places or leads
    /// to no catalog, the file is scanned for objects instead and
    /// [`was_repaired`](Self::was_repaired) reports it.
    pub fn load_with(bytes: &[u8], options: &LoadOptions) -> Result<Self> {
        let data: Arc<[u8]> = bytes.into();
        let version = header_version(&data);
        let limits = &options.limits;

        let declared = match xref::read(&data, limits) {
            Ok(x) => x
                .entries
                .iter()
                .all(|(num, (_, loc))| match loc {
                    Loc::Offset(off) => xref::header_at(&data, *off, *num),
                    Loc::Compressed { .. } => true,
                })
                .then_some(x),
            Err(e @ Error::Limit { .. }) => return Err(e),
            Err(_) => None,
        };
        if let Some(x) = declared {
            let mut doc = Self::empty(Arc::clone(&data), version, limits.clone());
            doc.previous_xref = Some((x.start, x.stream));
            doc.trailer = x.trailer;
            doc.slots = x.entries.into_iter().map(|(n, (g, loc))| (n, Slot::file(g, loc))).collect();
            match doc.finish_load(options) {
                Ok(()) => return Ok(doc),
                // Passwords and limits are not something a rebuild changes.
                Err(e @ (Error::Password | Error::UnsupportedEncryption(_) | Error::Limit { .. })) => return Err(e),
                Err(_) => {}
            }
        }
        Self::load_by_scan(data, version, options)
    }

    fn empty(data: Arc<[u8]>, version: Option<(u8, u8)>, limits: Limits) -> Self {
        Self {
            data,
            version: version.unwrap_or((1, 4)),
            slots: BTreeMap::new(),
            trailer: Dictionary::new(),
            security: None,
            encrypt_object: None,
            limits,
            repaired: false,
            previous_xref: None,
            object_streams: Mutex::new(BTreeMap::new()),
            object_stream_bytes: AtomicU64::new(0),
            pages: OnceLock::new(),
            dirty: BTreeSet::new(),
            deleted: BTreeSet::new(),
        }
    }

    /// The repair path: rebuild everything from the object headers found in
    /// the bytes.
    fn load_by_scan(data: Arc<[u8]>, version: Option<(u8, u8)>, options: &LoadOptions) -> Result<Self> {
        let scan = xref::scan(&data, &options.limits)?;
        let mut doc = Self::empty(data, version, options.limits.clone());
        doc.repaired = true;
        doc.trailer = scan.trailer;
        doc.slots = scan
            .objects
            .iter()
            .map(|(n, (g, off))| (*n, Slot::file(*g, Loc::Offset(*off))))
            .collect();
        if !doc.trailer.has(b"Root") {
            if let Some(id) = scan.catalog {
                doc.trailer.set("Root", id);
            }
        }
        doc.setup_security(options)?;
        // Objects that live in object streams have no header to find. Add
        // them from each container, a later definition beating an earlier.
        for (container, at) in &scan.object_streams {
            if scan.objects.get(container).map(|(_, off)| *off) != Some(*at) {
                continue;
            }
            let Ok(stream) = doc.object_stream(*container, 0) else { continue };
            for (i, (num, _)) in stream.index.iter().enumerate() {
                let newer_in_file = matches!(
                    doc.slots.get(num),
                    Some(Slot { loc: SlotLoc::File(Loc::Offset(off)), .. }) if off > at
                );
                if !newer_in_file && num != container {
                    let index = u32::try_from(i).unwrap_or(u32::MAX);
                    doc.slots.insert(*num, Slot::file(0, Loc::Compressed { container: *container, index }));
                }
            }
            if doc.slots.len() > doc.limits.max_objects {
                return Err(Error::Limit { what: "object count", limit: doc.limits.max_objects as u64 });
            }
        }
        if doc.catalog().is_err() {
            // No trailer named a usable root: look for the catalog itself.
            let found = doc.slots.keys().copied().find(|num| {
                doc.load_object(*num, 0)
                    .is_ok_and(|o| o.as_dict().is_ok_and(|d| d.is_type(b"Catalog")))
            });
            match found {
                Some(num) => {
                    let generation = doc.slots.get(&num).map_or(0, |s| s.generation);
                    doc.trailer.set("Root", (num, generation));
                }
                None if version.is_none() => return Err(Error::NotPdf),
                None => return Err(Error::Xref("no document catalog could be found".into())),
            }
        }
        Ok(doc)
    }

    /// Set up decryption and check that the catalog is reachable.
    fn finish_load(&mut self, options: &LoadOptions) -> Result<()> {
        self.setup_security(options)?;
        self.catalog().map(|_| ())
    }

    fn setup_security(&mut self, options: &LoadOptions) -> Result<()> {
        let Some(entry) = self.trailer.get(b"Encrypt").cloned() else {
            return Ok(());
        };
        if entry.is_null() {
            return Ok(());
        }
        if let Object::Reference(id) = entry {
            self.encrypt_object = Some(id.0);
        }
        // An `/Encrypt` that names nothing readable as a dictionary (a
        // damaged or missing object) leaves the file unencrypted, as in
        // pdf.js and lopdf. Anything that really was encrypted then reads as
        // noise, which every consumer already has to survive.
        let encrypt = match self.resolve(&entry)? {
            Object::Dictionary(d) => d.clone(),
            _ => {
                self.encrypt_object = None;
                return Ok(());
            }
        };
        let encrypt = self.resolved_copy(&encrypt, 3);
        let id0 = self
            .lookup(&self.trailer, b"ID")
            .ok()
            .and_then(|id| id.as_array().ok())
            .and_then(|a| a.first())
            .and_then(|o| self.resolve(o).ok())
            .and_then(|o| o.as_str().ok())
            .unwrap_or(&[])
            .to_vec();
        self.security = Some(Security::new(&encrypt, &id0, &options.password)?);
        // Anything loaded so far was loaded without decryption. Only the
        // encryption dictionary itself (never encrypted) may stay.
        for (num, slot) in &mut self.slots {
            if Some(*num) != self.encrypt_object {
                slot.cell = OnceLock::new();
            }
        }
        Ok(())
    }

    /// A copy of `dict` with references replaced by their targets, `depth`
    /// levels down. For small dictionaries that must be read without a
    /// document at hand (the encryption dictionary, decode parameters).
    fn resolved_copy(&self, dict: &Dictionary, depth: u32) -> Dictionary {
        let mut out = Dictionary::new();
        for (k, v) in dict.iter() {
            let v = self.resolve(v).unwrap_or(&NULL);
            let v = match v {
                Object::Dictionary(d) if depth > 0 => Object::Dictionary(self.resolved_copy(d, depth - 1)),
                // A stream stays a reference: copying its data is never what
                // a parameter dictionary wants.
                Object::Stream(_) => dict.get(k).cloned().unwrap_or(Object::Null),
                other => other.clone(),
            };
            out.set(k, v);
        }
        out
    }

    // ------------------------------------------------------------ access

    /// The PDF version from the file header, as (major, minor).
    #[must_use]
    pub const fn version(&self) -> (u8, u8) {
        self.version
    }

    /// The trailer dictionary (for a file with cross-reference streams, the
    /// newest stream's dictionary).
    #[must_use]
    pub const fn trailer(&self) -> &Dictionary {
        &self.trailer
    }

    /// The trailer dictionary, mutably.
    pub fn trailer_mut(&mut self) -> &mut Dictionary {
        &mut self.trailer
    }

    /// The document catalog (`/Root`).
    pub fn catalog(&self) -> Result<&Dictionary> {
        match self.lookup(&self.trailer, b"Root")? {
            Object::Dictionary(d) => Ok(d),
            _ => Err(Error::MissingKey("Root".into())),
        }
    }

    /// Whether the file is encrypted.
    #[must_use]
    pub const fn is_encrypted(&self) -> bool {
        self.security.is_some()
    }

    /// Whether the owner password (rather than the user password) opened an
    /// encrypted file.
    #[must_use]
    pub fn opened_as_owner(&self) -> bool {
        self.security.as_ref().is_some_and(|s| s.owner)
    }

    /// Whether the document opened but its embedded files did not: only the
    /// attachments are encrypted and the password given does not open them.
    #[must_use]
    pub fn attachments_locked(&self) -> bool {
        self.security.as_ref().is_some_and(|s| s.attachments_locked)
    }

    /// Whether the cross-reference data had to be rebuilt by scanning.
    #[must_use]
    pub const fn was_repaired(&self) -> bool {
        self.repaired
    }

    /// The limits this document was loaded with.
    #[must_use]
    pub const fn limits(&self) -> &Limits {
        &self.limits
    }

    /// The ids of every object in the document, in object-number order.
    pub fn object_ids(&self) -> impl Iterator<Item = ObjectId> + '_ {
        self.slots.iter().map(|(n, s)| (*n, s.generation))
    }

    /// The highest object number in use.
    #[must_use]
    pub fn max_object_number(&self) -> u32 {
        self.slots.keys().next_back().copied().unwrap_or(0)
    }

    /// The object with this id.
    ///
    /// The generation is not checked: a reference with a stale generation
    /// number finds the object, as it does in other readers.
    pub fn get_object(&self, id: ObjectId) -> Result<&Object> {
        self.load_object(id.0, 0).map_err(|e| match e {
            Error::MissingObject(_) => Error::MissingObject(id),
            other => other,
        })
    }

    /// Follow references until something that is not one. A reference to an
    /// object that does not exist (or cannot be read) resolves to null, as
    /// the format specifies.
    pub fn resolve<'a>(&'a self, object: &'a Object) -> Result<&'a Object> {
        let mut current = object;
        for _ in 0..MAX_REFERENCE_CHAIN {
            match current {
                Object::Reference(id) => match self.load_object(id.0, 0) {
                    Ok(o) => current = o,
                    Err(e @ Error::Limit { .. }) => return Err(e),
                    Err(_) => return Ok(&NULL),
                },
                other => return Ok(other),
            }
        }
        Err(Error::Cycle("references"))
    }

    /// `dict[key]`, resolved. A missing key is null.
    pub fn lookup<'a>(&'a self, dict: &'a Dictionary, key: &[u8]) -> Result<&'a Object> {
        match dict.get(key) {
            Some(o) => self.resolve(o),
            None => Ok(&NULL),
        }
    }

    /// `dict[key]` as a dictionary, resolved; `None` when absent or not one.
    #[must_use]
    pub fn lookup_dict<'a>(&'a self, dict: &'a Dictionary, key: &[u8]) -> Option<&'a Dictionary> {
        self.lookup(dict, key).ok().and_then(|o| o.as_dict().ok())
    }

    /// The object with this id, as a dictionary (a stream answers with its
    /// dictionary).
    pub fn get_dictionary(&self, id: ObjectId) -> Result<&Dictionary> {
        self.get_object(id)?.as_dict()
    }

    fn load_object(&self, num: u32, depth: u32) -> Result<&Object> {
        let slot = self.slots.get(&num).ok_or(Error::MissingObject((num, 0)))?;
        if let Some(o) = slot.cell.get() {
            return Ok(o);
        }
        if depth > MAX_LOAD_DEPTH {
            return Err(Error::Cycle("object loading"));
        }
        let object = match &slot.loc {
            SlotLoc::Memory => Object::Null,
            SlotLoc::File(Loc::Offset(offset)) => {
                let mut p = Parser::new(&self.data, *offset, self.limits.max_nesting);
                let (id, mut object) = p.indirect_object(&self.data, &mut |l| match l {
                    Object::Reference(r) => self.load_object(r.0, depth + 1).ok().and_then(direct_length),
                    other => direct_length(other),
                })?;
                if id.0 != num {
                    return Err(Error::Xref(format!("object {num} is not at its offset")));
                }
                self.decrypt(id, &mut object);
                object
            }
            SlotLoc::File(Loc::Compressed { container, index }) => {
                self.compressed_object(*container, *index, num, depth)?
            }
        };
        Ok(slot.cell.get_or_init(|| object))
    }

    fn decrypt(&self, id: ObjectId, object: &mut Object) {
        let Some(security) = &self.security else { return };
        if Some(id.0) == self.encrypt_object {
            return;
        }
        if let Object::Stream(s) = object {
            // Cross-reference streams carry no encrypted strings either.
            if s.dict.is_type(b"XRef") {
                return;
            }
            if let Some(plain) = security.decrypt_stream(id, &s.dict, s.raw()) {
                let dict = std::mem::take(&mut s.dict);
                *s = Stream::from_blob(dict, Blob::owned(plain));
            }
        }
        security.decrypt_strings(id, object);
    }

    /// Object `num`, stored in object stream `container`.
    fn compressed_object(&self, container: u32, index: u32, num: u32, depth: u32) -> Result<Object> {
        let stream = self.object_stream(container, depth + 1)?;
        // The index from the cross-reference entry is a hint; the number is
        // what identifies the object.
        let entry = stream
            .index
            .get(index as usize)
            .filter(|(n, _)| *n == num)
            .or_else(|| stream.index.iter().find(|(n, _)| *n == num))
            .ok_or(Error::MissingObject((num, 0)))?;
        let mut p = Parser::new(&stream.data, entry.1, self.limits.max_nesting);
        // Objects in an object stream are not encrypted individually: the
        // container was decrypted as a whole.
        p.object()
    }

    /// The decoded object stream `container`, from the cache or freshly
    /// decoded.
    fn object_stream(&self, container: u32, depth: u32) -> Result<Arc<ObjectStream>> {
        let cached = self.lock_object_streams().get(&container).cloned();
        if let Some(s) = cached {
            return Ok(s);
        }
        // A container is an ordinary object in the file. One that claims to
        // live inside another object stream is refused, which also rules out
        // containers that contain each other.
        let in_file = matches!(
            self.slots.get(&container),
            Some(Slot { loc: SlotLoc::File(Loc::Offset(_)) | SlotLoc::Memory, .. })
        );
        if !in_file {
            return Err(Error::Xref(format!("object stream {container} is not an object in the file")));
        }
        let stream = self.load_object(container, depth)?.as_stream()?;
        let n = stream.dict.get_i64(b"N").and_then(|v| usize::try_from(v).ok()).unwrap_or(0);
        let first = self
            .lookup(&stream.dict, b"First")?
            .as_i64()
            .ok()
            .and_then(|v| usize::try_from(v).ok())
            .ok_or_else(|| Error::MissingKey("First".into()))?;
        let data = self.decode_stream(stream, self.limits.max_stream_bytes)?;
        // The decoded containers are kept for the life of the document, so
        // their total is budgeted.
        let total = self.object_stream_bytes.fetch_add(data.len() as u64, Ordering::Relaxed) + data.len() as u64;
        if total > self.limits.max_object_stream_total {
            return Err(Error::Limit { what: "decoded object streams", limit: self.limits.max_object_stream_total });
        }
        let mut index = Vec::new();
        let mut p = Parser::new(&data, 0, 0);
        // `n` is a claim; the header's own length is the bound.
        for _ in 0..n {
            p.skip_ws();
            if p.pos >= first.min(data.len()) {
                break;
            }
            let Some(num) = p.unsigned().and_then(|v| u32::try_from(v).ok()) else { break };
            p.skip_ws();
            let Some(offset) = p.unsigned().and_then(|v| usize::try_from(v).ok()) else { break };
            if let Some(at) = first.checked_add(offset).filter(|at| *at < data.len()) {
                index.push((num, at));
            }
        }
        let stream = Arc::new(ObjectStream { data, index });
        self.lock_object_streams().insert(container, Arc::clone(&stream));
        Ok(stream)
    }

    fn lock_object_streams(&self) -> std::sync::MutexGuard<'_, BTreeMap<u32, Arc<ObjectStream>>> {
        // The map is only ever inserted into; a panic elsewhere while it was
        // held cannot leave it inconsistent.
        self.object_streams.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    // ------------------------------------------------------------ streams

    /// The stream's filter chain, outermost first, with each filter's decode
    /// parameters (references resolved).
    pub(crate) fn filter_chain(&self, dict: &Dictionary) -> Result<Vec<(Vec<u8>, Option<Dictionary>)>> {
        // `/F` and `/DP` are the inline-image spellings.
        let entry = |long: &[u8], short: &[u8]| -> Result<&Object> {
            match self.lookup(dict, long)? {
                Object::Null => self.lookup(dict, short),
                o => Ok(o),
            }
        };
        let names: Vec<Vec<u8>> = match entry(b"Filter", b"F")? {
            Object::Name(n) => vec![n.clone()],
            Object::Array(a) => {
                let mut names = Vec::with_capacity(a.len().min(16));
                for item in a {
                    names.push(self.resolve(item)?.as_name()?.to_vec());
                }
                names
            }
            _ => Vec::new(),
        };
        if names.len() > 16 {
            return Err(Error::Limit { what: "filters on one stream", limit: 16 });
        }
        let parms = entry(b"DecodeParms", b"DP")?;
        let mut chain = Vec::with_capacity(names.len());
        for (i, name) in names.into_iter().enumerate() {
            let p = match parms {
                Object::Dictionary(d) if i == 0 => Some(d),
                Object::Array(a) => match a.get(i) {
                    Some(o) => self.resolve(o)?.as_dict().ok(),
                    None => None,
                },
                _ => None,
            };
            chain.push((name, p.map(|d| self.resolved_copy(d, 0))));
        }
        Ok(chain)
    }

    /// Run the stream's non-image filters. Stops in front of an image codec
    /// (which is always last) and returns it with its parameters.
    ///
    /// `cap` bounds the result. Intermediate results of a filter chain are
    /// bounded by [`Limits::max_stream_bytes`].
    pub(crate) fn decode_partial(&self, stream: &Stream, cap: Cap) -> Result<PartialDecode> {
        let chain = self.filter_chain(&stream.dict)?;
        let plain_filters = chain.iter().take_while(|(name, _)| !filters::is_image_filter(name)).count();
        let mut data: Option<Vec<u8>> = None;
        let mut complete = true;
        for (i, (name, parms)) in chain.into_iter().enumerate() {
            if filters::is_image_filter(&name) {
                let data = data.unwrap_or_else(|| stream.raw().to_vec());
                return Ok(PartialDecode { data, complete, image: Some((name, parms)) });
            }
            let input = data.as_deref().unwrap_or_else(|| stream.raw());
            let step = if i + 1 == plain_filters { cap } else { Cap::strict(self.limits.max_stream_bytes) };
            let (out, whole) = filters::decode(&name, parms.as_ref(), input, step)?;
            complete &= whole;
            data = Some(out);
        }
        let data = match data {
            Some(d) => d,
            None => {
                let raw = stream.raw();
                if raw.len() <= cap.max {
                    raw.to_vec()
                } else if cap.clip {
                    raw[..cap.max].to_vec()
                } else {
                    return Err(Error::Limit { what: "decoded stream size", limit: cap.max as u64 });
                }
            }
        };
        Ok(PartialDecode { data, complete, image: None })
    }

    /// The stream's data with every filter undone, at most `max` bytes.
    ///
    /// Fails with [`Error::Limit`] if the data would be larger, with
    /// [`Error::Filter`] if the encoded data is damaged or ends early, and
    /// with [`Error::UnsupportedFilter`] for an image codec (`DCTDecode`,
    /// `JPXDecode`, `CCITTFaxDecode`, `JBIG2Decode`): decode images with
    /// [`Document::decode_image`](crate::Document::decode_image).
    pub fn decode_stream(&self, stream: &Stream, max: usize) -> Result<Vec<u8>> {
        let (data, complete) = self.decode_stream_lenient(stream, max)?;
        if complete {
            Ok(data)
        } else {
            Err(Error::Filter {
                filter: "stream".into(),
                message: format!("encoded data is damaged or ends early ({} bytes recovered)", data.len()),
            })
        }
    }

    /// Like [`decode_stream`](Self::decode_stream), but damaged data yields
    /// what could be recovered, with `false` for "not complete". A viewer
    /// wants this; anything that must not act on a partial page does not.
    pub fn decode_stream_lenient(&self, stream: &Stream, max: usize) -> Result<(Vec<u8>, bool)> {
        let partial = self.decode_partial(stream, Cap::strict(max))?;
        match partial.image {
            Some((name, _)) => Err(Error::UnsupportedFilter(String::from_utf8_lossy(&name).into_owned())),
            None => Ok((partial.data, partial.complete)),
        }
    }

    // ------------------------------------------------------------ pages

    /// The ids of the document's pages, in order.
    pub fn pages(&self) -> Result<&[ObjectId]> {
        if let Some(p) = self.pages.get() {
            return Ok(p);
        }
        let pages = crate::page::collect_pages(self)?;
        Ok(self.pages.get_or_init(|| pages))
    }

    /// Number of pages. A document whose page tree cannot be read has none.
    #[must_use]
    pub fn page_count(&self) -> usize {
        self.pages().map_or(0, <[ObjectId]>::len)
    }

    /// Page `index`, counting from zero.
    pub fn page(&self, index: usize) -> Result<crate::Page<'_>> {
        let id = *self
            .pages()?
            .get(index)
            .ok_or_else(|| Error::Page(format!("no page {index}")))?;
        crate::Page::new(self, id)
    }

    // ------------------------------------------------------------ editing

    /// An object number not in use, reserved for the caller with a null
    /// object until [`set_object`](Self::set_object) fills it.
    pub fn new_object_id(&mut self) -> ObjectId {
        let num = self.max_object_number().saturating_add(1);
        self.slots.insert(num, Slot::memory(0, Object::Null));
        self.dirty.insert(num);
        self.deleted.remove(&num);
        (num, 0)
    }

    /// Add `object` under a new id.
    pub fn add_object(&mut self, object: impl Into<Object>) -> ObjectId {
        let id = self.new_object_id();
        self.set_object(id, object);
        id
    }

    /// Put `object` at `id`, replacing what was there.
    pub fn set_object(&mut self, id: ObjectId, object: impl Into<Object>) {
        self.slots.insert(id.0, Slot::memory(id.1, object.into()));
        self.dirty.insert(id.0);
        self.deleted.remove(&id.0);
        self.pages = OnceLock::new();
    }

    /// The object with this id, for changing in place. The object counts as
    /// changed from here on.
    pub fn get_object_mut(&mut self, id: ObjectId) -> Result<&mut Object> {
        self.load_object(id.0, 0)?;
        self.dirty.insert(id.0);
        self.pages = OnceLock::new();
        let slot = self.slots.get_mut(&id.0).ok_or(Error::MissingObject(id))?;
        slot.loc = SlotLoc::Memory;
        slot.cell.get_mut().ok_or(Error::MissingObject(id))
    }

    /// Remove the object. References to it resolve to null afterwards.
    pub fn delete_object(&mut self, id: ObjectId) -> Option<Object> {
        let slot = self.slots.remove(&id.0)?;
        self.dirty.remove(&id.0);
        self.deleted.insert(id.0);
        self.pages = OnceLock::new();
        slot.cell.into_inner()
    }

    /// Whether anything was added, changed or deleted since loading.
    #[must_use]
    pub fn is_modified(&self) -> bool {
        !self.dirty.is_empty() || !self.deleted.is_empty()
    }

    /// A new, empty document: a catalog and an empty page tree.
    #[must_use]
    pub fn new() -> Self {
        let mut doc = Self::empty(Arc::from(&[][..]), Some((1, 7)), Limits::default());
        let pages = doc.add_object(crate::dictionary! {
            "Type" => "Pages", "Kids" => Vec::<Object>::new(), "Count" => 0,
        });
        let catalog = doc.add_object(crate::dictionary! { "Type" => "Catalog", "Pages" => pages });
        doc.trailer.set("Root", catalog);
        doc
    }

    /// Set the version written in the header by a full rewrite.
    pub fn set_version(&mut self, major: u8, minor: u8) {
        self.version = (major.min(9), minor.min(9));
    }

    pub(crate) fn generation_of(&self, num: u32) -> u16 {
        self.slots.get(&num).map_or(0, |s| s.generation)
    }

    pub(crate) const fn security(&self) -> Option<&Security> {
        self.security.as_ref()
    }
}

impl Default for Document {
    fn default() -> Self {
        Self::new()
    }
}

/// What [`Document::decode_partial`] produced.
pub(crate) struct PartialDecode {
    pub(crate) data: Vec<u8>,
    pub(crate) complete: bool,
    /// The image codec still to run, with its parameters.
    pub(crate) image: Option<(Vec<u8>, Option<Dictionary>)>,
}