pdfrum-edit 0.5.0

PDF serializer: full/incremental save, page import, subsetting
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
//! The attachment writers: embedded files added, replaced, described and
//! removed through the document editor. The `/EmbeddedFiles` name tree is
//! rewritten flat on every change, a shape every reader accepts.

use crate::{EditDoc, Error};
use pdfrum_common::{Diagnostics, Limits};
use pdfrum_object::{
    Array, ByteSpan, Dict, Name, ObjRef, Object, PdfString, Resolve, Stream, encode_text,
};

/// An attachment write either applies or names why it could not.
type Result<T> = core::result::Result<T, Error>;

/// What an attachment carries besides its name and bytes.
///
/// A config struct with [`Default`]. `#[non_exhaustive]` so a field added
/// later is not a major break; fill one in with [`AttachmentOptions::builder`].
/// Every field is optional and an absent one writes no key.
///
/// ```
/// use pdfrum_edit::AttachmentOptions;
///
/// let options = AttachmentOptions::builder()
///     .description("The source data")
///     .mime_type("text/csv")
///     .build();
/// assert!(options.modified.is_none());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct AttachmentOptions {
    /// The file specification's `/Desc`, the text a viewer shows beside the
    /// name. Read back by `Attachment::description`.
    pub description: Option<String>,
    /// The embedded file's MIME type — `text/plain`, `application/pdf` —
    /// written as the stream's `/Subtype` name. Read back by
    /// the facade's `Attachment::subtype`.
    pub mime_type: Option<String>,
    /// The file's own modification time as a PDF date string
    /// (`D:YYYYMMDDHHmmSS…`, ISO 32000-1 §7.9.4), written to `/Params
    /// /ModDate`. [`pdf_date`](crate::pdf_date) spells a `SystemTime` that
    /// way. Read back by the facade's `Attachment::param`.
    pub modified: Option<String>,
}

/// Builds an [`AttachmentOptions`] a setting at a time.
///
/// The way to change one field from outside this crate: the type is
/// `#[non_exhaustive]`, so struct-update syntax is a same-crate spelling.
/// Each method takes an `impl Into<String>`, so the `Some(…into())` the
/// fields need is written once here rather than at every call site.
///
/// ```
/// use pdfrum_edit::AttachmentOptions;
///
/// let options = AttachmentOptions::builder()
///     .description("The source data")
///     .mime_type("text/csv")
///     .build();
///
/// assert_eq!(options.description.as_deref(), Some("The source data"));
/// assert!(options.modified.is_none());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[must_use]
pub struct AttachmentOptionsBuilder(AttachmentOptions);

impl AttachmentOptionsBuilder {
    /// The text a viewer shows beside the name —
    /// [`AttachmentOptions::description`].
    ///
    /// ```
    /// let options = pdfrum::AttachmentOptions::builder().description("notes").build();
    /// assert_eq!(options.description.as_deref(), Some("notes"));
    /// ```
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.0.description = Some(description.into());
        self
    }

    /// The embedded file's MIME type — [`AttachmentOptions::mime_type`].
    ///
    /// ```
    /// let options = pdfrum::AttachmentOptions::builder().mime_type("text/csv").build();
    /// assert_eq!(options.mime_type.as_deref(), Some("text/csv"));
    /// ```
    pub fn mime_type(mut self, mime_type: impl Into<String>) -> Self {
        self.0.mime_type = Some(mime_type.into());
        self
    }

    /// The file's modification time as a PDF date string —
    /// [`AttachmentOptions::modified`]. [`pdf_date`](crate::pdf_date) spells
    /// a `SystemTime` that way.
    ///
    /// ```
    /// let options = pdfrum::AttachmentOptions::builder()
    ///     .modified("D:20260906120000Z")
    ///     .build();
    /// assert!(options.modified.is_some());
    /// ```
    pub fn modified(mut self, modified: impl Into<String>) -> Self {
        self.0.modified = Some(modified.into());
        self
    }

    /// The options as built.
    ///
    /// ```
    /// let options = pdfrum::AttachmentOptions::builder().build();
    /// assert_eq!(options, pdfrum::AttachmentOptions::default());
    /// ```
    #[must_use]
    pub fn build(self) -> AttachmentOptions {
        self.0
    }
}

impl AttachmentOptions {
    /// A builder starting from the defaults.
    ///
    /// ```
    /// let options = pdfrum::AttachmentOptions::builder().mime_type("text/csv").build();
    /// ```
    pub fn builder() -> AttachmentOptionsBuilder {
        AttachmentOptionsBuilder::default()
    }
}

/// The embedded file stream (ISO 32000-1 §7.11.4): `/Type /EmbeddedFile`,
/// the MIME type as `/Subtype`, `/DL` and `/Params` with the size, an MD5
/// `/CheckSum` and the modification date when one was given. The save
/// flate-compresses it like every other filterless stream it writes.
fn embedded_file(bytes: &[u8], mime_type: Option<&str>, modified: Option<&str>) -> Stream {
    let len = i64::try_from(bytes.len()).unwrap_or(i64::MAX);
    let mut params = Dict::new();
    params.insert(Name::from("Size"), Object::Int(len));
    params.insert(
        Name::from("CheckSum"),
        Object::Str(PdfString::hex(pdfrum_crypt::md5(bytes))),
    );
    if let Some(modified) = modified.filter(|date| !date.is_empty()) {
        params.insert(
            Name::from("ModDate"),
            Object::Str(PdfString::literal(encode_text(modified))),
        );
    }
    let mut dict = Dict::new();
    dict.insert(Name::from("Type"), Object::Name(Name::from("EmbeddedFile")));
    if let Some(mime_type) = mime_type.filter(|mime| !mime.is_empty()) {
        dict.insert(
            Name::from("Subtype"),
            Object::Name(Name::from(mime_type.as_bytes())),
        );
    }
    dict.insert(Name::from("DL"), Object::Int(len));
    dict.insert(Name::from("Params"), Object::Dict(params));
    Stream::new(dict, ByteSpan::from(bytes.to_vec()))
}

/// The current attachments as (name, value) pairs, read through the
/// edits so far; empty without a tree.
pub(crate) fn attachment_entries(
    edit: &EditDoc<'_>,
    limits: &Limits,
) -> Result<Vec<(String, Object)>> {
    let Some(root) = edit.base().trailer().reference(&Name::from("Root")) else {
        return Err(Error::NoDestinationCatalog);
    };
    let Ok(catalog) = edit.fetch(root) else {
        return Ok(Vec::new());
    };
    let Some(catalog) = catalog.as_dict() else {
        return Ok(Vec::new());
    };
    let Some(names) = catalog.dict(&Name::from("Names"), edit) else {
        return Ok(Vec::new());
    };
    let Some(files) = names.dict(&Name::from("EmbeddedFiles"), edit) else {
        return Ok(Vec::new());
    };
    let tree = pdfrum_doc::NameTree { root: files };
    let mut diags = Diagnostics::default();
    let count = tree.count(edit, limits, &mut diags);
    Ok((0..count)
        .filter_map(|index| tree.lookup_by_index(index, edit, limits, &mut diags))
        .collect())
}

/// The tree's entries with their values **unresolved**.
///
/// [`attachment_entries`] goes through the name tree's `lookup_by_index`,
/// which resolves each value — so a specification written as a reference comes
/// back as a dictionary. That is right for reading, and wrong for every write
/// path here: rewriting the tree from resolved entries *inlines* every
/// specification that was indirect, which loses the object identity `/AF`
/// needs and duplicates the dictionary on the next save.
///
/// So the write paths read through here instead, keeping whatever spelling the
/// tree already had.
pub(crate) fn raw_attachment_entries(
    edit: &EditDoc<'_>,
    limits: &Limits,
) -> Result<Vec<(String, Object)>> {
    let named = attachment_entries(edit, limits)?;
    let mut out = Vec::with_capacity(named.len());
    for (index, (name, resolved)) in named.into_iter().enumerate() {
        let value = match attachment_spec_ref(edit, limits, index)? {
            Some(reference) => Object::Ref(reference),
            None => resolved,
        };
        out.push((name, value));
    }
    Ok(out)
}

/// The reference naming attachment `index`'s file specification, when the
/// tree holds one indirectly.
///
/// [`attachment_entries`] goes through the name tree's `lookup_by_index`,
/// which **resolves** each value — so a specification written as a reference
/// comes back as a dictionary and its identity is lost. `/AF` needs that
/// identity: an associated file is the *same object* as the attachment, not a
/// copy of it. So this walks the leaves itself and keeps the raw entry.
///
/// `None` when there is no such attachment, or when its specification really
/// is written inline.
pub(crate) fn attachment_spec_ref(
    edit: &EditDoc<'_>,
    limits: &Limits,
    index: usize,
) -> Result<Option<ObjRef>> {
    let Some(root) = edit.base().trailer().reference(&Name::from("Root")) else {
        return Err(Error::NoDestinationCatalog);
    };
    let Ok(catalog) = edit.fetch(root) else {
        return Ok(None);
    };
    let Some(files) = catalog
        .as_dict()
        .and_then(|catalog| catalog.dict(&Name::from("Names"), edit))
        .and_then(|names| names.dict(&Name::from("EmbeddedFiles"), edit))
    else {
        return Ok(None);
    };
    let mut cursor = 0;
    Ok(raw_entry_at(edit, limits, &files, index, &mut cursor, 0))
}

/// The raw value of the `index`-th entry of a name tree, without resolving it.
fn raw_entry_at(
    edit: &EditDoc<'_>,
    limits: &Limits,
    node: &Dict,
    target: usize,
    cursor: &mut usize,
    depth: u32,
) -> Option<ObjRef> {
    if depth > limits.max_name_tree_depth {
        return None;
    }
    if let Some(leaf) = node.array(&Name::from("Names"), edit) {
        let count = leaf.len() / 2;
        if target >= *cursor + count {
            *cursor += count;
            return None;
        }
        let slot = (target - *cursor) * 2;
        return leaf.reference_at(slot + 1);
    }
    let kids = node.array(&Name::from("Kids"), edit)?;
    for slot in 0..kids.len() {
        let Some(kid) = kids.dict_at(slot, edit) else {
            continue;
        };
        if let Some(found) = raw_entry_at(edit, limits, &kid, target, cursor, depth + 1) {
            return Some(found);
        }
    }
    None
}

/// The file specification of attachment `index` — its reference when it
/// is indirect — and its dictionary; `None` when out of range or not a
/// dictionary.
pub(crate) fn attachment_spec(
    edit: &EditDoc<'_>,
    limits: &Limits,
    index: usize,
) -> Result<Option<(Option<ObjRef>, Dict)>> {
    let entries = raw_attachment_entries(edit, limits)?;
    let Some(entry) = entries.get(index) else {
        return Ok(None);
    };
    Ok(match &entry.1 {
        Object::Ref(reference) => {
            let Ok(object) = edit.fetch(*reference) else {
                return Ok(None);
            };
            object
                .as_dict()
                .map(|dict| (Some(*reference), dict.clone()))
        }
        Object::Dict(dict) => Some((None, dict.clone())),
        _ => None,
    })
}

/// Writes `entries` back as a flat `/Names` array. `/Names` and
/// `/EmbeddedFiles` are created as new indirect objects when missing,
/// referenced from their parent; the innermost *indirect* holder is
/// replaced, and an inline holder is rewritten inside its parent, outward
/// to the catalog.
pub(crate) fn write_attachment_entries(
    edit: &mut EditDoc<'_>,
    entries: Vec<(String, Object)>,
) -> Result<()> {
    let k_root = Name::from("Root");
    let k_names = Name::from("Names");
    let k_ef = Name::from("EmbeddedFiles");
    let k_kids = Name::from("Kids");
    let k_limits = Name::from("Limits");
    let Some(root) = edit.base().trailer().reference(&k_root) else {
        return Err(Error::NoDestinationCatalog);
    };
    let dict_at = |edit: &EditDoc<'_>, reference: ObjRef| {
        edit.fetch(reference)
            .ok()
            .as_deref()
            .and_then(Object::as_dict)
            .cloned()
    };
    let mut catalog = dict_at(edit, root).unwrap_or_default();
    let mut names_array = Array::new();
    for (name, value) in entries {
        names_array.push(Object::Str(PdfString::literal(encode_text(&name))));
        names_array.push(value);
    }
    let tree_of = |existing: Option<Dict>| {
        let mut tree = existing.unwrap_or_default();
        tree.remove(&k_kids);
        tree.remove(&k_limits);
        tree.insert(k_names.clone(), Object::Array(names_array.clone()));
        tree
    };
    match catalog.raw(&k_names).cloned() {
        Some(Object::Ref(names_ref)) => {
            let mut names = dict_at(edit, names_ref).unwrap_or_default();
            match names.raw(&k_ef).cloned() {
                Some(Object::Ref(tree_ref)) => {
                    let existing = dict_at(edit, tree_ref);
                    edit.replace(tree_ref, Object::Dict(tree_of(existing)));
                }
                Some(Object::Dict(inline)) => {
                    names.insert(k_ef.clone(), Object::Dict(tree_of(Some(inline))));
                    edit.replace(names_ref, Object::Dict(names));
                }
                _ => {
                    let tree_ref = edit.add(Object::Dict(tree_of(None)));
                    names.insert(k_ef.clone(), Object::Ref(tree_ref));
                    edit.replace(names_ref, Object::Dict(names));
                }
            }
        }
        Some(Object::Dict(mut names)) => match names.raw(&k_ef).cloned() {
            Some(Object::Ref(tree_ref)) => {
                let existing = dict_at(edit, tree_ref);
                edit.replace(tree_ref, Object::Dict(tree_of(existing)));
            }
            Some(Object::Dict(inline)) => {
                names.insert(k_ef.clone(), Object::Dict(tree_of(Some(inline))));
                catalog.insert(k_names.clone(), Object::Dict(names));
                edit.replace(root, Object::Dict(catalog));
            }
            _ => {
                let tree_ref = edit.add(Object::Dict(tree_of(None)));
                names.insert(k_ef.clone(), Object::Ref(tree_ref));
                catalog.insert(k_names.clone(), Object::Dict(names));
                edit.replace(root, Object::Dict(catalog));
            }
        },
        _ => {
            let tree_ref = edit.add(Object::Dict(tree_of(None)));
            let mut names = Dict::new();
            names.insert(k_ef.clone(), Object::Ref(tree_ref));
            let names_ref = edit.add(Object::Dict(names));
            catalog.insert(k_names.clone(), Object::Ref(names_ref));
            edit.replace(root, Object::Dict(catalog));
        }
    }
    Ok(())
}

/// Stores a rewritten file specification for attachment `index`:
/// replaces it when it is indirect, otherwise rewrites the tree entry
/// inline.
pub(crate) fn store_attachment_spec(
    edit: &mut EditDoc<'_>,
    limits: &Limits,
    index: usize,
    reference: Option<ObjRef>,
    spec: Dict,
) -> Result<()> {
    if let Some(reference) = reference {
        edit.replace(reference, Object::Dict(spec));
        return Ok(());
    }
    let mut entries = raw_attachment_entries(edit, limits)?;
    if let Some(entry) = entries.get_mut(index) {
        entry.1 = Object::Dict(spec);
    }
    write_attachment_entries(edit, entries)
}

/// Removes attachment `index` from the name tree; `Ok(false)` when there
/// is no such attachment.
///
/// # Errors
///
/// When the document has no catalog to hold the tree.
pub fn delete_attachment(edit: &mut EditDoc<'_>, limits: &Limits, index: usize) -> Result<bool> {
    let mut entries = raw_attachment_entries(edit, limits)?;
    if index >= entries.len() {
        return Ok(false);
    }
    entries.remove(index);
    write_attachment_entries(edit, entries)?;
    Ok(true)
}

/// Adds an embedded file named `name`, sorted into the `/EmbeddedFiles`
/// name tree by name — creating the tree when the document has none —
/// and returns its index among the attachments.
///
/// The file specification is `<< /Type /Filespec /UF (name) /F (name)
/// /Desc (…) /EF << /F stream >> >>`, a new indirect object; the stream
/// is `/Type /EmbeddedFile` with `/Subtype` as the MIME type, `/DL`, and
/// `/Params` holding `/Size`, an MD5 `/CheckSum` and `/ModDate`, and the
/// save flate-compresses it. A second attachment with the same name is
/// a second entry, not a replacement.
///
/// ```
/// use pdfrum::{AttachmentOptions, Document, SaveOptions};
///
/// let doc = Document::open("tests/fixtures/hello_world.pdf")?;
/// let mut edit = doc.edit();
/// edit.add_attachment(
///     "notes.txt",
///     b"Read me",
///     &AttachmentOptions::builder().mime_type("text/plain").build(),
/// )?;
/// let mut bytes = Vec::new();
/// edit.write_to(&mut bytes, &SaveOptions::default())?;
///
/// let saved = Document::from_bytes(bytes)?;
/// let attachment = &saved.attachments()[0];
/// assert_eq!(attachment.file_name(), "notes.txt");
/// assert_eq!(attachment.data().as_deref(), Some(&b"Read me"[..]));
/// assert_eq!(attachment.subtype().as_deref(), Some("text/plain"));
/// # Ok::<(), pdfrum::Error>(())
/// ```
///
/// # Errors
///
/// When the document has no catalog to hold the tree.
pub fn add_attachment(
    edit: &mut EditDoc<'_>,
    limits: &Limits,
    name: &str,
    bytes: &[u8],
    options: &AttachmentOptions,
) -> Result<usize> {
    let mut entries = raw_attachment_entries(edit, limits)?;
    let stream_ref = edit.add(Object::Stream(Box::new(embedded_file(
        bytes,
        options.mime_type.as_deref(),
        options.modified.as_deref(),
    ))));
    let mut spec = Dict::new();
    spec.insert(Name::from("Type"), Object::Name(Name::from("Filespec")));
    spec.insert(
        Name::from("UF"),
        Object::Str(PdfString::literal(encode_text(name))),
    );
    spec.insert(
        Name::from("F"),
        Object::Str(PdfString::literal(encode_text(name))),
    );
    if let Some(description) = options.description.as_deref().filter(|d| !d.is_empty()) {
        spec.insert(
            Name::from("Desc"),
            Object::Str(PdfString::literal(encode_text(description))),
        );
    }
    let mut ef = Dict::new();
    ef.insert(Name::from("F"), Object::Ref(stream_ref));
    spec.insert(Name::from("EF"), Object::Dict(ef));
    let reference = edit.add(Object::Dict(spec));
    let index = entries
        .iter()
        .position(|(existing, _)| existing.as_str() > name)
        .unwrap_or(entries.len());
    entries.insert(index, (name.to_owned(), Object::Ref(reference)));
    write_attachment_entries(edit, entries)?;
    Ok(index)
}

/// Removes every attachment named `name` from the name tree; `Ok(false)`
/// when there is none. The objects go with the next full save's garbage
/// collection.
///
/// ```
/// use pdfrum::Document;
///
/// let doc = Document::open("tests/fixtures/embedded_attachments.pdf")?;
/// let mut edit = doc.edit();
/// assert!(edit.remove_attachment("1.txt")?);
/// assert!(!edit.remove_attachment("1.txt")?, "already gone");
/// # Ok::<(), pdfrum::Error>(())
/// ```
///
/// # Errors
///
/// When the document has no catalog to hold the tree.
pub fn remove_attachment(edit: &mut EditDoc<'_>, limits: &Limits, name: &str) -> Result<bool> {
    let mut entries = raw_attachment_entries(edit, limits)?;
    let before = entries.len();
    entries.retain(|(existing, _)| existing != name);
    if entries.len() == before {
        return Ok(false);
    }
    write_attachment_entries(edit, entries)?;
    Ok(true)
}

/// Replaces attachment `index`'s embedded file with a new stream carrying
/// `/Type /EmbeddedFile`, `/DL <len>` and `/Params << /Size <len>
/// /CheckSum <md5> >>`, linked as `/EF << /F <ref> >>` on the file
/// specification; a MIME type or date the old stream had is not carried
/// over. `Ok(false)` when there is no such attachment.
///
/// # Errors
///
/// When the document has no catalog to hold the tree.
pub fn set_attachment_file(
    edit: &mut EditDoc<'_>,
    limits: &Limits,
    index: usize,
    bytes: &[u8],
) -> Result<bool> {
    let Some((reference, mut spec)) = attachment_spec(edit, limits, index)? else {
        return Ok(false);
    };
    let stream_ref = edit.add(Object::Stream(Box::new(embedded_file(bytes, None, None))));
    let mut ef = Dict::new();
    ef.insert(Name::from("F"), Object::Ref(stream_ref));
    spec.insert(Name::from("EF"), Object::Dict(ef));
    store_attachment_spec(edit, limits, index, reference, spec)?;
    Ok(true)
}

/// Replaces attachment `index`'s embedded file, carrying the MIME type and
/// date `options` names.
///
/// [`set_attachment_file`] drops both, which is documented but rarely what a
/// caller means: an attachment that had a `/Subtype` of `text/csv` and a
/// `/Params /ModDate` loses them on a replace, so a viewer stops offering the
/// right application and the file's own time is gone. This is that function
/// with somewhere to put them.
///
/// `Ok(false)` when there is no such attachment.
///
/// # Errors
///
/// When the document has no catalog to hold the tree.
pub fn set_attachment_file_with(
    edit: &mut EditDoc<'_>,
    limits: &Limits,
    index: usize,
    bytes: &[u8],
    options: &AttachmentOptions,
) -> Result<bool> {
    let Some((reference, mut spec)) = attachment_spec(edit, limits, index)? else {
        return Ok(false);
    };
    let stream_ref = edit.add(Object::Stream(Box::new(embedded_file(
        bytes,
        options.mime_type.as_deref(),
        options.modified.as_deref(),
    ))));
    let mut ef = Dict::new();
    ef.insert(Name::from("F"), Object::Ref(stream_ref));
    spec.insert(Name::from("EF"), Object::Dict(ef));
    // `/Desc` lives on the file specification, not on the stream, so it is
    // set here rather than passed to `embedded_file`.
    if let Some(description) = options.description.as_deref() {
        spec.insert(
            Name::from("Desc"),
            Object::Str(PdfString::literal(encode_text(description))),
        );
    }
    store_attachment_spec(edit, limits, index, reference, spec)?;
    Ok(true)
}

/// Renames attachment `index`, answering whether there was one to rename.
///
/// The name is the tree **key**, and it is also written to the specification's
/// `/F` and `/UF` so that the two agree — a reader shows one and looks the
/// attachment up by the other, and a document where they disagree is a
/// document whose attachment cannot be saved under the name it displays.
///
/// A name already in use is refused with [`Error::DuplicateAttachmentName`]:
/// the tree is keyed by name, so writing it would make one of the two
/// unreachable.
///
/// # Errors
///
/// - When the document has no catalog to hold the tree.
/// - [`Error::DuplicateAttachmentName`] when another attachment has that name.
pub fn set_attachment_name(
    edit: &mut EditDoc<'_>,
    limits: &Limits,
    index: usize,
    name: &str,
) -> Result<bool> {
    let mut entries = raw_attachment_entries(edit, limits)?;
    let Some((existing, _)) = entries.get(index) else {
        return Ok(false);
    };
    if existing == name {
        return Ok(true);
    }
    if entries
        .iter()
        .enumerate()
        .any(|(other, (taken, _))| other != index && taken == name)
    {
        return Err(Error::DuplicateAttachmentName(name.to_owned()));
    }

    // The specification's own `/F` and `/UF` are rewritten alongside the key,
    // so the displayed name and the lookup name stay the same string.
    if let Some((reference, mut spec)) = attachment_spec(edit, limits, index)? {
        let value = Object::Str(PdfString::literal(encode_text(name)));
        spec.insert(Name::from("F"), value.clone());
        spec.insert(Name::from("UF"), value);
        store_attachment_spec(edit, limits, index, reference, spec)?;
        entries = raw_attachment_entries(edit, limits)?;
    }

    if let Some(slot) = entries.get_mut(index) {
        name.clone_into(&mut slot.0);
    }
    // The tree is sorted by key, so a rename can move the entry; rewriting the
    // whole tree is what keeps it ordered.
    entries.sort_by(|(a, _), (b, _)| a.cmp(b));
    write_attachment_entries(edit, entries)?;
    Ok(true)
}

/// Sets a `/Params` text entry on attachment `index`'s embedded file —
/// `CreationDate`, `ModDate`, any key — creating `/Params` when missing;
/// a `CheckSum` given as `<HEX…>` is stored as that hex string.
/// `Ok(false)` when the attachment has no embedded file.
///
/// # Errors
///
/// When the document has no catalog to hold the tree.
pub fn set_attachment_param(
    edit: &mut EditDoc<'_>,
    limits: &Limits,
    index: usize,
    key: &str,
    text: &str,
) -> Result<bool> {
    let Some((_, spec)) = attachment_spec(edit, limits, index)? else {
        return Ok(false);
    };
    let Some(ef) = spec.dict(&Name::from("EF"), edit) else {
        return Ok(false);
    };
    let Some(stream_ref) = ef.reference(&Name::from("F")) else {
        return Ok(false);
    };
    let Some(stream) = edit
        .fetch(stream_ref)
        .ok()
        .and_then(|object| object.as_stream().cloned())
    else {
        return Ok(false);
    };
    let mut params = stream
        .dict
        .dict(&Name::from("Params"), edit)
        .unwrap_or_default();
    let hex = if key == "CheckSum" {
        hex_bytes(text)
    } else {
        None
    };
    let value = hex.map_or_else(
        || Object::Str(PdfString::literal(encode_text(text))),
        |bytes| Object::Str(PdfString::hex(bytes)),
    );
    params.insert(Name::from(key), value);
    let mut dict = stream.dict.clone();
    dict.insert(Name::from("Params"), Object::Dict(params));
    edit.replace(
        stream_ref,
        Object::Stream(Box::new(Stream::new(dict, stream.data.clone()))),
    );
    Ok(true)
}

/// Sets the file specification's `/Desc`; `Ok(false)` when there is no
/// such attachment.
///
/// # Errors
///
/// When the document has no catalog to hold the tree.
pub fn set_attachment_description(
    edit: &mut EditDoc<'_>,
    limits: &Limits,
    index: usize,
    text: &str,
) -> Result<bool> {
    let Some((reference, mut spec)) = attachment_spec(edit, limits, index)? else {
        return Ok(false);
    };
    spec.insert(
        Name::from("Desc"),
        Object::Str(PdfString::literal(encode_text(text))),
    );
    store_attachment_spec(edit, limits, index, reference, spec)?;
    Ok(true)
}

/// `<HEXPAIRS>` — angle brackets, an even count of hex digits, whitespace
/// ignored — as bytes; `None` for anything else.
fn hex_bytes(text: &str) -> Option<Vec<u8>> {
    let mut digits = Vec::new();
    for c in text.strip_prefix('<')?.strip_suffix('>')?.chars() {
        if c.is_ascii_whitespace() {
            continue;
        }
        digits.push(u8::try_from(c.to_digit(16)?).ok()?);
    }
    if !digits.len().is_multiple_of(2) {
        return None;
    }
    Some(
        digits
            .as_chunks::<2>()
            .0
            .iter()
            .map(|&[hi, lo]| (hi << 4) | lo)
            .collect(),
    )
}