Skip to main content

pdf/edit/
full.rs

1// edit::full -- a document written again in full (Update::save_full): every object the trailer
2// reaches (/Root, /Info), as the update has it, in a new file with one cross-reference section.
3// What no object reaches any longer, and the older revisions of the incremental updates, are
4// left out; the objects keep their numbers (the section lists the runs of numbers there are, so
5// a number far up costs nothing between), and the new ones (object streams, /Encrypt, a direct
6// /Root) come after every number an object refers to, also of objects deleted or missing.  A file whose newest section is a cross-reference
7// stream, or that has object streams, gets object streams (of up to 100 objects) and a
8// cross-reference stream again; any other a table.
9//
10//   let out = up.save_full(&Full::default())?;                              // its encryption
11//   let out = up.save_full(&Full { security: Security::None, ..Full::default() })?;  // decrypted
12//   let out = up.save_full(&Full { security: Security::Encrypt(&enc), ..Full::default() })?;
13//
14// Security::Keep keeps /Encrypt, the key and the first /ID string, and copies the streams that
15// stay the same objects as they are; Security::None and Security::Encrypt decrypt every string
16// and stream (a /Crypt filter of a stream is taken off; bytes AES cannot have made are an error,
17// not an empty stream; no bytes at all are an empty stream, as viewers read them) and write them in the clear or with the new key.  Changing or removing the
18// encryption of an encrypted file needs the owner password (read::Document::opened_as_owner), as
19// viewers ask for it.  A file with signatures (a signed field of the document as it was opened, a
20// signature dictionary with /ByteRange anywhere the trailer reaches now, usage rights or a
21// certification in /Perms) is not written in full unless Full::break_signatures: the bytes they
22// cover are gone, so they no longer verify.  The first /ID string stays (a new file has it from
23// the bytes, or from the seed when it is encrypted); the second is a hash of the new bytes.
24// AES-256 in a file older than PDF 2.0 adds Adobe's extension level 8 to the catalog, as the
25// writer does.  Objects go into object streams only where their strings stay as protected as
26// they were (not when a file encrypts strings but not streams), and the catalog of an encrypted
27// file stays out of them (ISO 32000-2, 7.5.7).
28
29use super::{exempt, ser, stream_obj, Item, Update, MAX_NUM};
30use crate::read::crypt::Crypt;
31use crate::read::xref::Entry;
32use crate::read::{Dict, Error, Object, Ref};
33use alloc::collections::{BTreeMap, BTreeSet};
34use alloc::vec;
35use alloc::vec::Vec;
36use compress::zlib;
37use core::fmt::Write as _;
38
39/// the encryption of a document written in full
40#[derive(Clone, Copy, Debug)]
41pub enum Security<'e> {
42    /// as the document has it (its /Encrypt and key; none when it has none)
43    Keep,
44    /// not encrypted
45    None,
46    /// encrypted anew
47    Encrypt(&'e crate::Encryption),
48}
49
50/// how save_full writes the document
51#[derive(Clone, Copy, Debug)]
52pub struct Full<'e> {
53    pub security: Security<'e>,
54    /// write a document with signatures although they will not verify (save_full refuses it
55    /// otherwise)
56    pub break_signatures: bool,
57}
58
59impl Default for Full<'_> {
60    fn default() -> Self {
61        Full { security: Security::Keep, break_signatures: false }
62    }
63}
64
65/// objects per object stream
66const PER_OBJSTM: usize = 100;
67
68/// what an object number holds, to be written
69enum Body {
70    Obj(Object),
71    Stream(Dict, Data),
72}
73
74/// a stream's data
75enum Data {
76    /// encoded by its filters, not encrypted
77    Clear(Vec<u8>),
78    /// its bytes in the file (start, end), encrypted with the key of an object (if at all)
79    File(usize, usize, Option<Ref>),
80}
81
82/// a signature dictionary (crypt.rs leaves its /Contents clear for the same reason)
83fn is_sig(d: &Dict) -> bool {
84    d.contains("ByteRange") && d.contains("Contents") && (d.is("Type", "Sig") || d.is("Type", "DocTimeStamp") || d.contains("SubFilter"))
85}
86
87/// the references in an object, and whether it holds a signature dictionary
88fn refs(o: &Object, out: &mut Vec<Ref>, signed: &mut bool) {
89    let mut stack: Vec<(&Object, u32)> = vec![(o, 0)];
90    while let Some((o, depth)) = stack.pop() {
91        if depth > crate::read::lex::MAX_DEPTH {
92            continue;
93        }
94        match o {
95            Object::Ref(r) => out.push(*r),
96            Object::Array(a) => stack.extend(a.iter().map(|v| (v, depth + 1))),
97            Object::Dict(d) => {
98                *signed |= is_sig(d);
99                stack.extend(d.iter().map(|(_, v)| (v, depth + 1)));
100            }
101            Object::Stream(s) => stack.extend(s.dict.iter().map(|(_, v)| (v, depth + 1))),
102            _ => {}
103        }
104    }
105}
106
107/// the references of what a number holds
108fn body_refs(b: &Body, out: &mut Vec<Ref>, signed: &mut bool) {
109    match b {
110        Body::Obj(o) => refs(o, out, signed),
111        Body::Stream(d, _) => {
112            for (_, v) in d.iter() {
113                refs(v, out, signed);
114            }
115        }
116    }
117}
118
119/// the name of a stream's /Crypt filter when its first filter is one (Identity when unnamed);
120/// /Filter and /DecodeParms resolved (direct_filters)
121fn crypt_filter(d: &Dict) -> Option<Vec<u8>> {
122    let first_is_crypt = match d.get("Filter") {
123        Some(Object::Name(n)) => n.0 == b"Crypt",
124        Some(Object::Array(a)) => a.first().and_then(Object::as_name) == Some(b"Crypt"),
125        _ => false,
126    };
127    if !first_is_crypt {
128        return None;
129    }
130    let parms = match d.get("DecodeParms") {
131        Some(Object::Array(a)) => a.first().cloned(),
132        Some(o) => Some(o.clone()),
133        None => None,
134    };
135    let name = parms.as_ref().and_then(Object::as_dict).and_then(|p| p.name("Name")).unwrap_or(b"Identity");
136    Some(name.to_vec())
137}
138
139/// a stream's dictionary without its first filter (the /Crypt one); the other filters keep
140/// their parameters
141fn strip_crypt(d: &mut Dict) {
142    match d.get("Filter").cloned() {
143        Some(Object::Array(mut a)) if a.len() > 1 => {
144            a.remove(0);
145            d.insert("Filter", Object::Array(a));
146            match d.get("DecodeParms").cloned() {
147                Some(Object::Array(mut p)) => {
148                    if !p.is_empty() {
149                        p.remove(0);
150                    }
151                    if p.iter().all(Object::is_null) {
152                        d.remove("DecodeParms");
153                    } else {
154                        d.insert("DecodeParms", Object::Array(p));
155                    }
156                }
157                // one dictionary for a chain of several filters belongs to the first
158                Some(_) => {
159                    d.remove("DecodeParms");
160                }
161                None => {}
162            }
163        }
164        _ => {
165            d.remove("Filter");
166            d.remove("DecodeParms");
167        }
168    }
169}
170
171/// whether the document as it was opened is signed: a field with a signature over byte
172/// ranges, or usage rights or a certification in the catalog's /Perms
173fn opened_signed(doc: &crate::read::Document) -> bool {
174    let perms = doc.catalog().get("Perms").map(|p| doc.resolve(p));
175    let has_perms = matches!(&perms, Some(Object::Dict(d)) if d.contains("DocMDP") || d.contains("UR3") || d.contains("UR"));
176    has_perms || doc.fields().iter().any(|f| f.signature.as_ref().is_some_and(|s| !s.byte_range.is_empty()))
177}
178
179impl Update<'_> {
180    /// /Filter and /DecodeParms of a stream as direct objects (references resolved, also those
181    /// in their arrays), as the reader takes them
182    fn direct_filters(&self, d: &mut Dict) {
183        for k in ["Filter", "DecodeParms"] {
184            if let Some(o) = d.get(k) {
185                let v = match self.resolve(o) {
186                    Object::Array(a) => Object::Array(a.iter().map(|e| self.resolve(e)).collect()),
187                    v => v,
188                };
189                d.insert(k, v);
190            }
191        }
192    }
193
194    /// the document written again in full, with the update's changes (see edit::full)
195    pub fn save_full(&self, opts: &Full) -> Result<Vec<u8>, Error> {
196        let doc = self.doc;
197        let keep = matches!(opts.security, Security::Keep);
198        if !keep && doc.is_encrypted() && !doc.opened_as_owner() {
199            return Err(Error::Invalid("changing a document's encryption needs its owner password"));
200        }
201        let fonts = self.font_items()?;
202        let mut items: BTreeMap<u32, (u16, &Item)> = self.objs.iter().map(|(&n, (g, it))| (n, (*g, it))).collect();
203        for (r, it) in &fonts {
204            items.insert(r.num, (r.generation, it));
205        }
206        let encrypt_ref = doc.encrypt_ref();
207        let fetch = |r: Ref| -> Option<Body> {
208            if let Some(&(g, it)) = items.get(&r.num) {
209                if g != r.generation {
210                    return None;
211                }
212                return match it {
213                    Item::Obj(o) => Some(Body::Obj(o.clone())),
214                    Item::Stream(d, data) => Some(Body::Stream(d.clone(), Data::Clear(data.clone()))),
215                    Item::Raw(d, s, e) => Some(Body::Stream(d.clone(), Data::File(*s, *e, Some(r)))),
216                    Item::Free => None,
217                };
218            }
219            match doc.get(r) {
220                Object::Null => None,
221                Object::Stream(s) => {
222                    let mut d = s.dict.clone();
223                    d.remove("Length");
224                    Some(Body::Stream(d, Data::File(s.start, s.end, s.owner)))
225                }
226                o => Some(Body::Obj(o)),
227            }
228        };
229
230        // what the trailer reaches, through its references and through a direct /Root or /Info;
231        // the direct ones get numbers once all that is known
232        let t = doc.trailer();
233        let mut bodies: BTreeMap<u32, (u16, Body)> = BTreeMap::new();
234        let mut signed = false;
235        let mut stack: Vec<Ref> = Vec::new();
236        let mut roots: BTreeMap<&str, Ref> = BTreeMap::new();
237        let mut direct: Vec<(&str, Object)> = Vec::new();
238        for k in ["Root", "Info"] {
239            match t.get(k) {
240                Some(Object::Ref(r)) => {
241                    stack.push(*r);
242                    roots.insert(k, *r);
243                }
244                Some(o @ Object::Dict(_)) => {
245                    refs(o, &mut stack, &mut signed);
246                    direct.push((k, o.clone()));
247                }
248                _ => {}
249            }
250        }
251        // the highest number referred to, also where the object is deleted or missing: new numbers
252        // come after it, so no reference that pointed to nothing points to a new object
253        let mut referred = 0u32;
254        while let Some(r) = stack.pop() {
255            if r.num == 0 || r.num > MAX_NUM {
256                continue;
257            }
258            referred = referred.max(r.num);
259            if bodies.contains_key(&r.num) || encrypt_ref == Some(r) {
260                continue;
261            }
262            let Some(body) = fetch(r) else { continue };
263            body_refs(&body, &mut stack, &mut signed);
264            bodies.insert(r.num, (r.generation, body));
265        }
266        roots.retain(|_, r| bodies.contains_key(&r.num));
267        let mut next = bodies.keys().next_back().map_or(1, |&n| n + 1).max(encrypt_ref.map_or(0, |r| r.num + 1)).max(referred + 1);
268        let mut take = || -> Result<u32, Error> {
269            if next > MAX_NUM {
270                return Err(Error::Limit("more objects than a PDF file can number"));
271            }
272            next += 1;
273            Ok(next - 1)
274        };
275        for (k, o) in direct {
276            let n = take()?;
277            bodies.insert(n, (0, Body::Obj(o)));
278            roots.insert(k, Ref { num: n, generation: 0 });
279        }
280        let Some(&root) = roots.get("Root") else { return Err(Error::Damaged("the catalog")) };
281        if (signed || opened_signed(doc)) && !opts.break_signatures {
282            return Err(Error::Invalid("a document with signatures written in full (Full::break_signatures)"));
283        }
284
285        // the first /ID string, the handler the objects are written with, its dictionary
286        let id0: Option<Vec<u8>> = match t.get("ID") {
287            Some(Object::Array(a)) => a.first().and_then(Object::as_bytes).filter(|b| !b.is_empty()).map(<[u8]>::to_vec),
288            _ => None,
289        };
290        let mut made: Option<(Crypt, Dict)> = None;
291        let mut id0 = id0;
292        let mut aes256 = false;
293        let crypt: Option<&Crypt> = match opts.security {
294            Security::Keep => doc.crypt(),
295            Security::None => None,
296            Security::Encrypt(e) => {
297                let seed = e.seed().ok_or(Error::Invalid("encryption without the system's random numbers needs Encryption::with_seed"))?;
298                let id = id0.get_or_insert_with(|| crate::encrypt::derive(&seed, b"file id")[..16].to_vec());
299                made = Some(Crypt::create(e, &seed, id)?);
300                aes256 = e.cipher == crate::Cipher::Aes256;
301                made.as_ref().map(|m| &m.0)
302            }
303        };
304        // the /Encrypt of the new file: (its reference, its dictionary) or a direct dictionary
305        let mut enc_obj: Option<(Ref, Object)> = None;
306        let mut enc_direct: Option<Object> = None;
307        match opts.security {
308            Security::Keep if doc.is_encrypted() => match encrypt_ref {
309                Some(r) => enc_obj = Some((r, doc.get(r))),
310                None => enc_direct = t.get("Encrypt").cloned(),
311            },
312            Security::Encrypt(_) => {
313                if let Some((_, d)) = &made {
314                    enc_obj = Some((Ref { num: take()?, generation: 0 }, Object::Dict(d.clone())));
315                }
316            }
317            _ => {}
318        }
319
320        // AES-256 below PDF 2.0: Adobe's extension level 8 in the catalog
321        let (mut major, mut minor) = doc.version();
322        if aes256 && (major, minor) < (2, 0) {
323            if let Some((g, Body::Obj(Object::Dict(cat)))) = bodies.get(&root.num) {
324                let mut cat = cat.clone();
325                let mut ext = match cat.get("Extensions").map(|e| self.resolve(e)) {
326                    Some(Object::Dict(d)) => d,
327                    _ => Dict::new(),
328                };
329                let level = self.dict(&ext.get("ADBE").cloned().unwrap_or_default()).int("ExtensionLevel").unwrap_or(0);
330                if level < 8 {
331                    let mut adbe = Dict::new();
332                    adbe.insert("BaseVersion", Object::name("1.7"));
333                    adbe.insert("ExtensionLevel", Object::Int(8));
334                    ext.insert("ADBE", Object::Dict(adbe));
335                    cat.insert("Extensions", Object::Dict(ext));
336                    let g = *g;
337                    bodies.insert(root.num, (g, Body::Obj(Object::Dict(cat))));
338                }
339            }
340            if (major, minor) < (1, 7) {
341                (major, minor) = (1, 7);
342            }
343        } else if matches!(opts.security, Security::Encrypt(_)) && (major, minor) < (1, 6) {
344            (major, minor) = (1, 6);
345        }
346
347        // the streams not copied as they are: their filters direct, a /Crypt filter taken off
348        // (its name kept for decrypting); one the update added with a /Crypt filter other than
349        // Identity says nothing of where its bytes came from
350        let mut cfs: BTreeMap<u32, Vec<u8>> = BTreeMap::new();
351        for (&num, (generation, body)) in bodies.iter_mut() {
352            let Body::Stream(dict, data) = body else { continue };
353            let r = Ref { num, generation: *generation };
354            let copied = match data {
355                Data::File(_, _, key) => keep && (*key == Some(r) || !doc.is_encrypted()),
356                Data::Clear(_) => keep,
357            };
358            if copied {
359                continue;
360            }
361            self.direct_filters(dict);
362            if let Some(cf) = crypt_filter(dict) {
363                if matches!(data, Data::Clear(_)) && cf != b"Identity" {
364                    return Err(Error::Unsupported("a stream of the update with a /Crypt filter other than Identity"));
365                }
366                strip_crypt(dict);
367                cfs.insert(num, cf);
368            }
369        }
370
371        // what the roots reach now (the catalog or a stream may have lost a reference above)
372        let mut reached: BTreeSet<u32> = BTreeSet::new();
373        let mut stack: Vec<u32> = roots.values().map(|r| r.num).collect();
374        let mut no_sig = false;
375        while let Some(n) = stack.pop() {
376            if !reached.insert(n) {
377                continue;
378            }
379            if let Some((_, b)) = bodies.get(&n) {
380                let mut found = Vec::new();
381                body_refs(b, &mut found, &mut no_sig);
382                stack.extend(found.into_iter().map(|r| r.num).filter(|n| bodies.contains_key(n)));
383            }
384        }
385        bodies.retain(|n, _| reached.contains(n));
386
387        let mut out = Vec::new();
388        let _ = write!(crate::obj::Fmt(&mut out), "%PDF-{major}.{minor}\n");
389        // the binary comment: four bytes above 127
390        out.extend_from_slice(b"%\xE2\xE3\xCF\xD3\n");
391
392        // object streams as the file had them, where the strings keep their protection
393        let objstm = (doc.xref_start().is_some_and(|s| s.1) || doc.xref_entries().values().any(|e| matches!(e.0, Entry::InStream(..)))) && crypt.is_none_or(|c| c.streams_cover_strings());
394        // (offset or (object stream, index), generation) of each object written
395        #[derive(Clone, Copy)]
396        enum At {
397            Off(usize, u16),
398            In(u32, u32),
399        }
400        let mut written: BTreeMap<u32, At> = BTreeMap::new();
401        let mut members: Vec<(u32, Object)> = Vec::new();
402        let data = doc.data();
403        for (&num, (generation, body)) in &bodies {
404            let r = Ref { num, generation: *generation };
405            match body {
406                Body::Obj(o) => {
407                    let in_stream = objstm && *generation == 0 && !matches!(o, Object::Dict(d) if is_sig(d)) && !(crypt.is_some() && num == root.num);
408                    if in_stream {
409                        members.push((num, o.clone()));
410                        continue;
411                    }
412                    written.insert(num, At::Off(out.len(), *generation));
413                    let _ = write!(crate::obj::Fmt(&mut out), "{num} {generation} obj\n");
414                    let mut o = o.clone();
415                    if let Some(c) = crypt {
416                        c.seal_strings(r, &mut o);
417                    }
418                    ser::object(&mut out, &o)?;
419                }
420                Body::Stream(d, body) => {
421                    let dict = d.clone();
422                    let bytes: Vec<u8> = match body {
423                        Data::File(s, e, key) => {
424                            let raw = data.get(*s..*e).ok_or(Error::Damaged("a stream outside the file"))?;
425                            if keep && (*key == Some(r) || !doc.is_encrypted()) {
426                                // as the file has it: encrypted with this object's key, if at all
427                                raw.to_vec()
428                            } else {
429                                let cf = cfs.get(&num).map(Vec::as_slice);
430                                let clear = match (doc.crypt(), key) {
431                                    (Some(c), Some(k)) if !(dict.is("Type", "XRef") || (!c.encrypt_metadata && dict.is("Type", "Metadata"))) => {
432                                        c.stream_checked(*k, raw, cf, dict.is("Type", "EmbeddedFile")).ok_or(Error::Damaged("an encrypted stream of bytes AES cannot have made"))?
433                                    }
434                                    _ => raw.to_vec(),
435                                };
436                                match crypt {
437                                    Some(c) if !exempt(c, &dict) => c.seal_stream(r, &clear, dict.is("Type", "EmbeddedFile")),
438                                    _ => clear,
439                                }
440                            }
441                        }
442                        Data::Clear(v) => match crypt {
443                            Some(c) if !exempt(c, &dict) => c.seal_stream(r, v, dict.is("Type", "EmbeddedFile")),
444                            _ => v.clone(),
445                        },
446                    };
447                    let mut o = Object::Dict(dict);
448                    if let Some(c) = crypt {
449                        c.seal_strings(r, &mut o);
450                    }
451                    written.insert(num, At::Off(out.len(), *generation));
452                    stream_obj(&mut out, r, &o, &bytes)?;
453                }
454            }
455            out.extend_from_slice(b"\nendobj\n");
456        }
457        // the objects of object streams: their strings are not encrypted, the stream is
458        for chunk in members.chunks(PER_OBJSTM) {
459            let n = take()?;
460            let mut head = Vec::new();
461            let mut body = Vec::new();
462            for (i, (num, o)) in chunk.iter().enumerate() {
463                let _ = write!(crate::obj::Fmt(&mut head), "{num} {} ", body.len());
464                ser::object(&mut body, o)?;
465                body.push(b'\n');
466                written.insert(*num, At::In(n, i as u32));
467            }
468            let first = head.len();
469            head.extend_from_slice(&body);
470            let r = Ref { num: n, generation: 0 };
471            let z = zlib::compress(&head, 6);
472            let z = match crypt {
473                Some(c) => c.seal_stream(r, &z, false),
474                None => z,
475            };
476            let mut d = Dict::new();
477            d.insert("Type", Object::name("ObjStm"));
478            d.insert("N", Object::Int(chunk.len() as i64));
479            d.insert("First", Object::Int(first as i64));
480            d.insert("Filter", Object::name("FlateDecode"));
481            written.insert(n, At::Off(out.len(), 0));
482            stream_obj(&mut out, r, &Object::Dict(d), &z)?;
483            out.extend_from_slice(b"\nendobj\n");
484        }
485        if let Some((r, d)) = &enc_obj {
486            written.insert(r.num, At::Off(out.len(), r.generation));
487            let _ = write!(crate::obj::Fmt(&mut out), "{} {} obj\n", r.num, r.generation);
488            ser::object(&mut out, d)?;
489            out.extend_from_slice(b"\nendobj\n");
490        }
491
492        // the trailer
493        let mut tr = Dict::new();
494        tr.insert("Root", Object::Ref(root));
495        if let Some(&i) = roots.get("Info") {
496            tr.insert("Info", Object::Ref(i));
497        }
498        if let Some((r, _)) = &enc_obj {
499            tr.insert("Encrypt", Object::Ref(*r));
500        } else if let Some(e) = enc_direct {
501            tr.insert("Encrypt", e);
502        }
503        let second = crypto::md5(&out).to_vec();
504        let first = id0.unwrap_or_else(|| second.clone());
505        tr.insert("ID", Object::Array(vec![Object::String(first), Object::String(second)]));
506        let list: BTreeMap<u32, (Entry, u16)> = written
507            .iter()
508            .map(|(&n, &a)| {
509                (n, match a {
510                    At::Off(o, g) => (Entry::At(o), g),
511                    At::In(s, i) => (Entry::InStream(s, i), 0),
512                })
513            })
514            .collect();
515        full_xref(&mut out, tr, list, objstm, &mut take)?;
516        Ok(out)
517    }
518}
519
520/// the one cross-reference section of a file written in full: a stream (when `as_stream`) or a
521/// table, object 0 as the head of an empty free list, then the runs of numbers written (the
522/// numbers between are free; a number far up costs no more than its own entry)
523fn full_xref(out: &mut Vec<u8>, mut tr: Dict, mut list: BTreeMap<u32, (Entry, u16)>, as_stream: bool, take: &mut dyn FnMut() -> Result<u32, Error>) -> Result<(), Error> {
524    let xref_num = if as_stream { Some(take()?) } else { None };
525    let at = out.len();
526    if let Some(n) = xref_num {
527        list.insert(n, (Entry::At(at), 0));
528    }
529    list.insert(0, (Entry::Free, 65535));
530    let size = list.keys().next_back().map_or(1, |&n| n + 1);
531    tr.insert("Size", Object::Int(size as i64));
532    // the runs of consecutive numbers: (first, count)
533    let mut runs: Vec<(u32, u32)> = Vec::new();
534    for &n in list.keys() {
535        match runs.last_mut() {
536            Some((s, c)) if *s + *c == n => *c += 1,
537            _ => runs.push((n, 1)),
538        }
539    }
540    if let Some(n) = xref_num {
541        let max = list.values().map(|e| match e.0 {
542            Entry::At(o) => o as u64,
543            Entry::InStream(s, _) => s as u64,
544            Entry::Free => 0,
545        }).max().unwrap_or(0);
546        let w1 = if max < 1 << 32 { 4 } else { 8 };
547        let mut rows = Vec::with_capacity(list.len() * (3 + w1));
548        for &(kind_e, g) in list.values() {
549            let (kind, f2, f3): (u8, u64, u64) = match kind_e {
550                Entry::At(o) => (1, o as u64, g as u64),
551                Entry::InStream(s, i) => (2, s as u64, i as u64),
552                Entry::Free => (0, 0, g as u64),
553            };
554            if f3 > 0xFFFF {
555                return Err(Error::Limit("an object stream of more than 65535 objects"));
556            }
557            rows.push(kind);
558            rows.extend_from_slice(&f2.to_be_bytes()[8 - w1..]);
559            rows.extend_from_slice(&f3.to_be_bytes()[6..]);
560        }
561        tr.insert("Type", Object::name("XRef"));
562        tr.insert("W", Object::Array(vec![Object::Int(1), Object::Int(w1 as i64), Object::Int(2)]));
563        tr.insert("Index", Object::Array(runs.iter().flat_map(|&(s, c)| [Object::Int(s as i64), Object::Int(c as i64)]).collect()));
564        tr.insert("Filter", Object::name("FlateDecode"));
565        let z = zlib::compress(&rows, 6);
566        stream_obj(out, Ref { num: n, generation: 0 }, &Object::Dict(tr), &z)?;
567        out.extend_from_slice(b"\nendobj\n");
568    } else {
569        out.extend_from_slice(b"xref\n");
570        for &(s, c) in &runs {
571            let _ = write!(crate::obj::Fmt(out), "{s} {c}\n");
572            for (_, &(e, g)) in list.range(s..s + c) {
573                let _ = match e {
574                    Entry::At(o) => write!(crate::obj::Fmt(out), "{o:010} {g:05} n\r\n"),
575                    _ => write!(crate::obj::Fmt(out), "0000000000 {g:05} f\r\n"),
576                };
577            }
578        }
579        out.extend_from_slice(b"trailer\n");
580        ser::object(out, &Object::Dict(tr))?;
581        out.push(b'\n');
582    }
583    let _ = write!(crate::obj::Fmt(out), "startxref\n{at}\n%%EOF\n");
584    Ok(())
585}