pdfrum-edit 0.1.0

PDF serializer: full/incremental save, page import, subsetting
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
//! Importing pages between documents, and the four bugs this crate fixes
//! rather than ports.
//!
//! Each fix has its own test here, because "we deliberately diverge" is only
//! a claim until something pins the divergence. Every other quirk in the
//! import path is ported verbatim and tested alongside them.

// Every helper below is only ever called from a `#[test]`, so an `expect` in
// one is a test failure rather than a library panic. `allow-expect-in-tests`
// recognises test *functions*, not the helpers they share, so the allowance is
// stated once here for the file.
#![expect(
    clippy::format_push_string,
    reason = "the fixture builders below assemble PDF source line by line; \
              `write!` into a String cannot fail, so the `let _ =` it needs \
              reads worse than the `push_str` it replaces"
)]
#![expect(
    clippy::expect_used,
    reason = "helpers shared by the tests below; a panic here is a failure"
)]

use std::sync::Arc;

use pdfrum_common::PageIndex;
use pdfrum_edit::{
    EditDoc, IdSource, ImportOptions, NUpOptions, PageRange, SaveMode, SaveOptions, import_pages,
    n_page_to_one, save,
};
use pdfrum_object::{Name, ObjRef, Object, Resolve, names};
use pdfrum_parser::{Document, LoadOptions, load};

fn open(bytes: &[u8]) -> Document {
    load(Arc::from(bytes), &LoadOptions::default()).expect("opens")
}

/// Save an edited document and reopen it, which is the only way to see what
/// the edits actually produced.
fn commit(edit: &EditDoc<'_>) -> Document {
    let options = SaveOptions {
        mode: SaveMode::Full,
        id_source: IdSource::Fixed([0x11; 16]),
        ..SaveOptions::default()
    };
    let mut out = Vec::new();
    save(edit, &options, &mut out).expect("saves");
    open(&out)
}

/// A source document of `count` pages, each with a distinguishing key and a
/// shared font so deduplication has something to deduplicate.
fn source(count: usize) -> Vec<u8> {
    let mut out = String::from("%PDF-1.7\n");
    out.push_str("1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
    let kids: Vec<String> = (0..count).map(|i| format!("{} 0 R", i + 4)).collect();
    out.push_str(&format!(
        "2 0 obj\n<< /Type /Pages /Count {count} /Kids [{}] \
         /MediaBox [0 0 400 500] /Resources << /Font << /F1 3 0 R >> >> >>\nendobj\n",
        kids.join(" ")
    ));
    out.push_str("3 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n");
    for i in 0..count {
        out.push_str(&format!(
            "{} 0 obj\n<< /Type /Page /Parent 2 0 R /Marker {i} >>\nendobj\n",
            i + 4
        ));
    }
    out.push_str("trailer\n<< /Root 1 0 R /Size 99 >>\n");
    out.into_bytes()
}

/// A destination with one page of its own.
fn destination() -> Vec<u8> {
    b"%PDF-1.7\n\
1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n\
2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n\
3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Existing true >>\nendobj\n\
trailer\n<< /Root 1 0 R /Size 4 >>\n"
        .to_vec()
}

/// The `/Marker` of each page, in order — how a test names which source page
/// landed where.
fn markers(doc: &Document) -> Vec<Option<i64>> {
    (0..doc.page_count())
        .filter_map(|i| doc.page(i).ok())
        .map(|p| p.dict.direct_int(&Name::from("Marker")))
        .collect()
}

// ---------------------------------------------------------------------------
// The basics
// ---------------------------------------------------------------------------

#[test]
fn importing_appends_pages_in_the_order_named() {
    let src = open(&source(3));
    let dest_bytes = destination();
    let dest = open(&dest_bytes);
    let mut edit = EditDoc::new(&dest);

    import_pages(
        &mut edit,
        &src,
        &PageRange::all(3),
        &ImportOptions {
            at: PageIndex::new(1),
            ..ImportOptions::default()
        },
    )
    .expect("imports");

    let result = commit(&edit);
    assert_eq!(result.page_count(), 4);
    assert_eq!(markers(&result), vec![None, Some(0), Some(1), Some(2)]);
}

// XFAImportTest (:714): the definitive insertion-index test — the pages land
// as a contiguous run at the index named, shifting what was there.
#[test]
fn pages_land_at_the_index_named_and_shift_the_rest() {
    let src = open(&source(4));
    let dest_bytes = destination();
    let dest = open(&dest_bytes);
    let mut edit = EditDoc::new(&dest);

    // "1, 4, 2" — note the spaces the grammar strips.
    let range = PageRange::parse("1, 4, 2", 4).expect("parses");
    import_pages(
        &mut edit,
        &src,
        &range,
        &ImportOptions {
            at: PageIndex::FIRST,
            ..ImportOptions::default()
        },
    )
    .expect("imports");

    let result = commit(&edit);
    assert_eq!(result.page_count(), 4);
    // Source pages 0, 3, 1 at destination 0, 1, 2; the existing page shifts.
    assert_eq!(markers(&result), vec![Some(0), Some(3), Some(1), None]);
}

#[test]
fn an_index_past_the_end_appends() {
    let src = open(&source(1));
    let dest_bytes = destination();
    let dest = open(&dest_bytes);
    let mut edit = EditDoc::new(&dest);

    import_pages(
        &mut edit,
        &src,
        &PageRange::all(1),
        &ImportOptions {
            at: PageIndex::new(999),
            ..ImportOptions::default()
        },
    )
    .expect("imports");
    assert_eq!(markers(&commit(&edit)), vec![None, Some(0)]);
}

// GoodIndices (:454): a page named twice is imported twice.
#[test]
fn a_page_named_twice_lands_twice() {
    let src = open(&source(2));
    let dest_bytes = destination();
    let dest = open(&dest_bytes);
    let mut edit = EditDoc::new(&dest);

    import_pages(
        &mut edit,
        &src,
        &PageRange::of([0, 0, 0]),
        &ImportOptions::default(),
    )
    .expect("imports");

    let result = commit(&edit);
    assert_eq!(result.page_count(), 4);
    assert_eq!(markers(&result), vec![Some(0), Some(0), Some(0), None]);
}

// BadIndices (:428): a page the source does not have fails the import.
#[test]
fn an_out_of_range_index_fails() {
    let src = open(&source(1));
    let dest_bytes = destination();
    let dest = open(&dest_bytes);
    let mut edit = EditDoc::new(&dest);

    assert!(matches!(
        import_pages(
            &mut edit,
            &src,
            &PageRange::of([42]),
            &ImportOptions::default()
        ),
        Err(pdfrum_edit::Error::PageIndexOutOfRange(index)) if index.get() == 42
    ));
}

// ---------------------------------------------------------------------------
// Import is transactional
// ---------------------------------------------------------------------------

// The C++ leaves a stray blank page behind a failed import, and leaves the
// earlier pages of a failed batch in place. Ours stages every mutation in the
// overlay and commits only on success.
#[test]
fn a_failed_import_leaves_the_destination_untouched() {
    let src = open(&source(2));
    let dest_bytes = destination();
    let dest = open(&dest_bytes);
    let mut edit = EditDoc::new(&dest);

    // The second index is out of range, so the whole import must fail — and
    // the first page must not have been created.
    assert!(
        import_pages(
            &mut edit,
            &src,
            &PageRange::of([0, 99]),
            &ImportOptions::default()
        )
        .is_err()
    );

    let result = commit(&edit);
    assert_eq!(result.page_count(), 1, "no stray page was created");
    assert_eq!(markers(&result), vec![None]);
}

// ---------------------------------------------------------------------------
// `/Type /Pages` resolves to the destination's real node
// ---------------------------------------------------------------------------

// The C++ hardcodes object 4, which is right only because a freshly created
// document happens to number its pages node 4. A destination numbered any
// other way gets a reference to whatever object 4 happens to be.
#[test]
fn a_source_pages_node_resolves_to_the_destinations_own() {
    // A destination whose pages node is object 7, not 4.
    let dest_bytes = b"%PDF-1.7\n\
7 0 obj\n<< /Type /Pages /Count 1 /Kids [8 0 R] >>\nendobj\n\
8 0 obj\n<< /Type /Page /Parent 7 0 R /MediaBox [0 0 612 792] >>\nendobj\n\
9 0 obj\n<< /Type /Catalog /Pages 7 0 R >>\nendobj\n\
trailer\n<< /Root 9 0 R /Size 10 >>\n"
        .to_vec();
    let dest = open(&dest_bytes);
    let src = open(&source(1));
    let mut edit = EditDoc::new(&dest);

    import_pages(
        &mut edit,
        &src,
        &PageRange::all(1),
        &ImportOptions::default(),
    )
    .expect("imports");

    let result = commit(&edit);
    assert_eq!(result.page_count(), 2);

    // Every imported page's `/Parent` names the destination's own node, and
    // that node really is a `/Pages` — not whatever object 4 held.
    for i in 0..result.page_count() {
        let page = result.page(i).expect("a page");
        let parent = page
            .dict
            .reference(names::PARENT)
            .expect("a parent reference");
        let node = result.fetch(parent).expect("resolves");
        assert_eq!(
            node.as_dict().and_then(|d| d.name(names::TYPE)),
            Some(names::PAGES),
            "page {i}'s parent is not a pages node"
        );
    }
}

// ---------------------------------------------------------------------------
// Importing never mutates the source
// ---------------------------------------------------------------------------

// PDFium's page constructor writes `/Type /Page` into a source dictionary
// that lacked one, so its import path is not read-only with respect to what
// it copies from. Ours cannot be: the source is shared immutable bytes.
#[test]
fn importing_never_mutates_the_source() {
    // A source page with no `/Type` at all.
    let src_bytes = b"%PDF-1.7\n\
1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n\
2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n\
3 0 obj\n<< /Parent 2 0 R /MediaBox [0 0 100 100] /Marker 7 >>\nendobj\n\
trailer\n<< /Root 1 0 R /Size 4 >>\n"
        .to_vec();
    let src = open(&src_bytes);
    let before = src.page(0).expect("a page").dict.clone();
    assert!(
        !before.contains_key(names::TYPE),
        "the fixture has no /Type"
    );

    let dest_bytes = destination();
    let dest = open(&dest_bytes);
    let mut edit = EditDoc::new(&dest);
    import_pages(
        &mut edit,
        &src,
        &PageRange::all(1),
        &ImportOptions::default(),
    )
    .expect("imports");

    // The source is unchanged...
    assert_eq!(src.page(0).expect("a page").dict, before);
    // ...and the *copy* got the `/Type` it needed.
    let result = commit(&edit);
    let imported = result.page(0).expect("the imported page");
    assert_eq!(imported.dict.name(names::TYPE), Some(names::PAGE));
    assert_eq!(imported.dict.direct_int(&Name::from("Marker")), Some(7));
}

// ---------------------------------------------------------------------------
// Inheritance flattening
// ---------------------------------------------------------------------------

// An imported page is detached from its `/Parent` chain, so what it was
// inheriting has to be written onto the copy.
#[test]
fn inherited_attributes_are_flattened_onto_the_copy() {
    let src = open(&source(1));
    let dest_bytes = destination();
    let dest = open(&dest_bytes);
    let mut edit = EditDoc::new(&dest);
    import_pages(
        &mut edit,
        &src,
        &PageRange::all(1),
        &ImportOptions::default(),
    )
    .expect("imports");

    let result = commit(&edit);
    let page = result.page(0).expect("the imported page");
    // The source page stated neither, and inherited both from its `/Pages`.
    let media = page.dict.array(names::MEDIA_BOX, &result).expect("a box");
    // The box came through as the source's numbers, so an exact comparison
    // is what the assertion means.
    #[expect(clippy::float_cmp, reason = "the box is copied, not computed")]
    {
        assert_eq!(media.as_rect().width(), 400.0);
    }
    assert!(
        page.dict.raw(names::RESOURCES).is_some(),
        "the inherited resources came with it"
    );
}

// A page inheriting nothing gets US Letter and an empty resource dictionary,
// which is what makes an unopenable source page still import.
#[test]
fn a_page_inheriting_nothing_gets_letter_and_empty_resources() {
    let src_bytes = b"%PDF-1.7\n\
1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n\
2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n\
3 0 obj\n<< /Type /Page /Parent 2 0 R >>\nendobj\n\
trailer\n<< /Root 1 0 R /Size 4 >>\n"
        .to_vec();
    let src = open(&src_bytes);
    let dest_bytes = destination();
    let dest = open(&dest_bytes);
    let mut edit = EditDoc::new(&dest);
    import_pages(
        &mut edit,
        &src,
        &PageRange::all(1),
        &ImportOptions::default(),
    )
    .expect("imports");

    let result = commit(&edit);
    let page = result.page(0).expect("the imported page");
    let media = page.dict.array(names::MEDIA_BOX, &result).expect("a box");
    assert_eq!(
        (media.as_rect().width(), media.as_rect().height()),
        (612.0, 792.0),
        "US Letter is the last fallback"
    );
    assert!(page.dict.raw(names::RESOURCES).is_some());
}

// ---------------------------------------------------------------------------
// Deduplication
// ---------------------------------------------------------------------------

// The object map is not cleared between pages, so a font two imported pages
// share is copied once and both point at it.
#[test]
fn two_imported_pages_sharing_a_font_get_one_copy() {
    let src = open(&source(2));
    let dest_bytes = destination();
    let dest = open(&dest_bytes);
    let mut edit = EditDoc::new(&dest);
    import_pages(
        &mut edit,
        &src,
        &PageRange::all(2),
        &ImportOptions::default(),
    )
    .expect("imports");

    let result = commit(&edit);
    let font_of = |i: u32| -> Option<ObjRef> {
        result
            .page(i)
            .ok()?
            .dict
            .dict(names::RESOURCES, &result)?
            .dict(&Name::from("Font"), &result)?
            .reference(&Name::from("F1"))
    };
    let first = font_of(0).expect("page 0's font");
    assert_eq!(first, font_of(1).expect("page 1's font"), "one copy");
}

// ---------------------------------------------------------------------------
// Damage tolerance
// ---------------------------------------------------------------------------

// A `/Parent` chain that cycles makes the attribute simply not inheritable,
// rather than hanging.
#[test]
fn a_self_referential_page_parent_imports() {
    let src_bytes = b"%PDF-1.7\n\
1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n\
2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] /Parent 2 0 R >>\nendobj\n\
3 0 obj\n<< /Type /Page /Parent 3 0 R /Marker 1 >>\nendobj\n\
trailer\n<< /Root 1 0 R /Size 4 >>\n"
        .to_vec();
    let src = open(&src_bytes);
    let dest_bytes = destination();
    let dest = open(&dest_bytes);
    let mut edit = EditDoc::new(&dest);
    import_pages(
        &mut edit,
        &src,
        &PageRange::all(1),
        &ImportOptions::default(),
    )
    .expect("imports");
    assert_eq!(commit(&edit).page_count(), 2);
}

// InitDestDoc's repairs: a destination whose `/Kids` is not an array has both
// `/Kids` and `/Count` rewritten, because the two are written together.
#[test]
fn a_destination_with_a_broken_kids_is_repaired() {
    let dest_bytes = b"%PDF-1.7\n\
1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n\
2 0 obj\n<< /Type /Pages /Count 5 /Kids 99 >>\nendobj\n\
trailer\n<< /Root 1 0 R /Size 3 >>\n"
        .to_vec();
    let Ok(dest) = load(Arc::from(&dest_bytes[..]), &LoadOptions::default()) else {
        // A destination with no usable page tree may refuse to open, which
        // is the reader's call and not this crate's.
        return;
    };
    let src = open(&source(1));
    let mut edit = EditDoc::new(&dest);
    import_pages(
        &mut edit,
        &src,
        &PageRange::all(1),
        &ImportOptions::default(),
    )
    .expect("imports");

    let result = commit(&edit);
    // The lying `/Count 5` did not survive.
    assert_eq!(result.page_count(), 1);
}

// A destination with a wrong-but-present catalog `/Type` is left alone: a
// producer that wrote something else may have meant it.
#[test]
fn a_wrong_catalog_type_is_not_repaired() {
    let dest_bytes = b"%PDF-1.7\n\
1 0 obj\n<< /Type /Whatever /Pages 2 0 R >>\nendobj\n\
2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n\
3 0 obj\n<< /Type /Page /Parent 2 0 R >>\nendobj\n\
trailer\n<< /Root 1 0 R /Size 4 >>\n"
        .to_vec();
    let dest = open(&dest_bytes);
    let src = open(&source(1));
    let mut edit = EditDoc::new(&dest);
    import_pages(
        &mut edit,
        &src,
        &PageRange::all(1),
        &ImportOptions::default(),
    )
    .expect("imports");

    let result = commit(&edit);
    let catalog = result.catalog().expect("a catalog");
    assert_eq!(
        catalog.name(names::TYPE),
        Some(&Name::from("Whatever")),
        "a wrong type is left alone"
    );
    assert_eq!(result.page_count(), 2);
}

// ---------------------------------------------------------------------------
// Viewer preferences
// ---------------------------------------------------------------------------

#[test]
fn viewer_preferences_are_copied_when_asked_for() {
    let src_bytes = b"%PDF-1.7\n\
1 0 obj\n<< /Type /Catalog /Pages 2 0 R /ViewerPreferences \
<< /HideToolbar true /Junk 9 0 R >> >>\nendobj\n\
2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n\
3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>\nendobj\n\
trailer\n<< /Root 1 0 R /Size 4 >>\n"
        .to_vec();
    let src = open(&src_bytes);
    let dest_bytes = destination();
    let dest = open(&dest_bytes);
    let mut edit = EditDoc::new(&dest);

    import_pages(
        &mut edit,
        &src,
        &PageRange::all(1),
        &ImportOptions {
            at: PageIndex::FIRST,
            viewer_preferences: true,
        },
    )
    .expect("imports");

    let result = commit(&edit);
    let prefs = result
        .catalog()
        .expect("a catalog")
        .dict(names::VIEWER_PREFERENCES, &result)
        .expect("preferences were copied");
    assert_eq!(prefs.bool(&Name::from("HideToolbar")), Some(true));
    assert!(
        !prefs.contains_key(&Name::from("Junk")),
        "a reference is filtered out — that is the circular-graph defence"
    );
}

#[test]
fn viewer_preferences_are_left_alone_when_not_asked_for() {
    let src = open(&source(1));
    let dest_bytes = destination();
    let dest = open(&dest_bytes);
    let mut edit = EditDoc::new(&dest);
    import_pages(
        &mut edit,
        &src,
        &PageRange::all(1),
        &ImportOptions::default(),
    )
    .expect("imports");

    let result = commit(&edit);
    assert!(
        result
            .catalog()
            .expect("a catalog")
            .raw(names::VIEWER_PREFERENCES)
            .is_none()
    );
}

// ---------------------------------------------------------------------------
// N-up
// ---------------------------------------------------------------------------

// ImportNPages (:108): the sheet counts, over a real document.
#[test]
fn n_up_produces_the_expected_sheet_counts() {
    for (x, y, pages, sheets) in [(2u32, 1u32, 5usize, 3u32), (5, 1, 5, 1), (3, 1, 5, 2)] {
        let src = open(&source(pages));
        let dest_bytes = destination();
        let dest = open(&dest_bytes);
        let mut edit = EditDoc::new(&dest);

        n_page_to_one(
            &mut edit,
            &src,
            &PageRange::all(u32::try_from(pages).expect("fits")),
            &NUpOptions {
                sheet: (612.0, 792.0),
                grid: (x, y),
            },
        )
        .expect("imposes");

        let result = commit(&edit);
        // The destination's own page is still there, plus the sheets.
        assert_eq!(
            result.page_count(),
            sheets + 1,
            "{x}x{y} over {pages} pages"
        );
    }
}

// BadNupParams (:129): a zero in the grid or the sheet is refused.
#[test]
fn n_up_refuses_a_zero_dimension() {
    let src = open(&source(2));
    let dest_bytes = destination();
    let dest = open(&dest_bytes);

    for options in [
        NUpOptions {
            sheet: (612.0, 792.0),
            grid: (0, 1),
        },
        NUpOptions {
            sheet: (612.0, 792.0),
            grid: (1, 0),
        },
        NUpOptions {
            sheet: (0.0, 792.0),
            grid: (1, 1),
        },
        NUpOptions {
            sheet: (612.0, 0.0),
            grid: (1, 1),
        },
    ] {
        let mut edit = EditDoc::new(&dest);
        assert!(
            matches!(
                n_page_to_one(&mut edit, &src, &PageRange::all(2), &options),
                Err(pdfrum_edit::Error::BadNupParams)
            ),
            "{options:?} must be refused"
        );
    }
}

#[test]
fn every_n_up_sheet_has_the_size_asked_for() {
    let src = open(&source(4));
    let dest_bytes = destination();
    let dest = open(&dest_bytes);
    let mut edit = EditDoc::new(&dest);

    n_page_to_one(
        &mut edit,
        &src,
        &PageRange::all(4),
        &NUpOptions {
            sheet: (792.0, 612.0),
            grid: (2, 1),
        },
    )
    .expect("imposes");

    let result = commit(&edit);
    // Skip the destination's own page, which keeps its own size.
    for i in 0..result.page_count() {
        let page = result.page(i).expect("a page");
        if page.dict.bool(&Name::from("Existing")) == Some(true) {
            continue;
        }
        let media = page.dict.array(names::MEDIA_BOX, &result).expect("a box");
        assert_eq!(
            (media.as_rect().width(), media.as_rect().height()),
            (792.0, 612.0),
            "sheet {i}"
        );
    }
}

// A source page reused on a *later* sheet must be registered in that
// sheet's own `/Resources /XObject`. The C++ reuses the name from a map it
// never clears while clearing the per-sheet registry, so the sub-page renders
// blank on every sheet after the first.
#[test]
fn a_page_reused_on_a_later_sheet_is_registered_on_that_sheet() {
    let src = open(&source(1));
    let dest_bytes = destination();
    let dest = open(&dest_bytes);
    let mut edit = EditDoc::new(&dest);

    // The same source page four times, one per sheet.
    n_page_to_one(
        &mut edit,
        &src,
        &PageRange::of([0, 0, 0, 0]),
        &NUpOptions {
            sheet: (612.0, 792.0),
            grid: (1, 1),
        },
    )
    .expect("imposes");

    let result = commit(&edit);
    let mut sheets = 0usize;
    for i in 0..result.page_count() {
        let page = result.page(i).expect("a page");
        if page.dict.bool(&Name::from("Existing")) == Some(true) {
            continue;
        }
        sheets += 1;

        let xobjects = page
            .dict
            .dict(names::RESOURCES, &result)
            .and_then(|r| r.dict(&Name::from("XObject"), &result))
            .unwrap_or_else(|| panic!("sheet {i} has no /XObject dictionary"));
        assert!(
            !xobjects.is_empty(),
            "sheet {i}'s /XObject dictionary is empty — the form is unreachable"
        );

        // Every name the content stream invokes must be in that dictionary.
        let contents = page
            .dict
            .stream(names::CONTENTS, &result)
            .expect("a content stream");
        let text = String::from_utf8_lossy(&pdfrum_parser::decoded_stream(
            &contents,
            &result,
            &pdfrum_common::Limits::default(),
            &mut pdfrum_common::Diagnostics::default(),
        ))
        .into_owned();
        for token in text.split_whitespace().collect::<Vec<_>>().windows(2) {
            let (Some(name), Some(op)) = (token.first(), token.get(1)) else {
                continue;
            };
            if *op == "Do"
                && let Some(bare) = name.strip_prefix('/')
            {
                assert!(
                    xobjects.contains_key(&Name::from(bare)),
                    "sheet {i} invokes /{bare} but does not name it"
                );
            }
        }
    }
    assert_eq!(sheets, 4, "one sheet per invocation");
}

// The same page used twice makes one form and two invocations, not two forms.
#[test]
fn a_page_used_twice_makes_one_form() {
    let src = open(&source(1));
    let dest_bytes = destination();
    let dest = open(&dest_bytes);
    let mut edit = EditDoc::new(&dest);

    n_page_to_one(
        &mut edit,
        &src,
        &PageRange::of([0, 0]),
        &NUpOptions {
            sheet: (612.0, 792.0),
            grid: (2, 1),
        },
    )
    .expect("imposes");

    let result = commit(&edit);
    let sheet = (0..result.page_count())
        .filter_map(|i| result.page(i).ok())
        .find(|p| p.dict.bool(&Name::from("Existing")) != Some(true))
        .expect("a sheet");

    let xobjects = sheet
        .dict
        .dict(names::RESOURCES, &result)
        .and_then(|r| r.dict(&Name::from("XObject"), &result))
        .expect("an /XObject dictionary");
    let targets: Vec<ObjRef> = xobjects.iter().filter_map(|(_, v)| v.as_ref_id()).collect();
    assert_eq!(targets.len(), 2, "two slots");
    assert_eq!(
        targets.first(),
        targets.get(1),
        "both slots name the same form"
    );
}

#[test]
fn an_n_up_form_is_a_form_xobject_carrying_only_resources() {
    let src = open(&source(1));
    let dest_bytes = destination();
    let dest = open(&dest_bytes);
    let mut edit = EditDoc::new(&dest);

    n_page_to_one(
        &mut edit,
        &src,
        &PageRange::all(1),
        &NUpOptions {
            sheet: (612.0, 792.0),
            grid: (1, 1),
        },
    )
    .expect("imposes");

    let result = commit(&edit);
    let sheet = (0..result.page_count())
        .filter_map(|i| result.page(i).ok())
        .find(|p| p.dict.bool(&Name::from("Existing")) != Some(true))
        .expect("a sheet");
    let form_ref = sheet
        .dict
        .dict(names::RESOURCES, &result)
        .and_then(|r| r.dict(&Name::from("XObject"), &result))
        .and_then(|x| x.iter().next().and_then(|(_, v)| v.as_ref_id()))
        .expect("a form reference");
    let form = result.fetch(form_ref).expect("resolves");
    let form = form.as_stream().expect("a stream");

    assert_eq!(
        form.dict.name(names::SUBTYPE),
        Some(&Name::from("Form")),
        "the object must be a form XObject"
    );
    assert_eq!(form.dict.direct_int(&Name::from("FormType")), Some(1));
    assert!(form.dict.raw(&Name::from("BBox")).is_some());
    assert!(form.dict.raw(&Name::from("Matrix")).is_some());
    assert!(form.dict.raw(names::RESOURCES).is_some());
    // Everything else about the source page is dropped.
    assert!(!form.dict.contains_key(names::ANNOTS));
    assert!(!form.dict.contains_key(names::CROP_BOX));
}

// ---------------------------------------------------------------------------
// The destination stays a valid document
// ---------------------------------------------------------------------------

#[test]
fn an_imported_document_is_one_another_reader_opens() {
    let src = open(&source(3));
    let dest_bytes = destination();
    let dest = open(&dest_bytes);
    let mut edit = EditDoc::new(&dest);
    import_pages(
        &mut edit,
        &src,
        &PageRange::all(3),
        &ImportOptions::default(),
    )
    .expect("imports");

    let options = SaveOptions {
        mode: SaveMode::Full,
        id_source: IdSource::Fixed([0x11; 16]),
        ..SaveOptions::default()
    };
    let mut out = Vec::new();
    save(&edit, &options, &mut out).expect("saves");

    // It opens, and every reference in it resolves.
    let result = open(&out);
    assert_eq!(result.page_count(), 4);
    for number in 1..=result.xref().last_object_number() {
        let Ok(object) = result.fetch(ObjRef::new(number, 0)) else {
            continue;
        };
        for target in references(&object) {
            assert!(
                result.fetch(target).is_ok(),
                "object {number} names {} unresolvably",
                target.num
            );
        }
    }
}

fn references(object: &Object) -> Vec<ObjRef> {
    let mut out = Vec::new();
    walk(object, &mut out, 0);
    out
}

fn walk(object: &Object, out: &mut Vec<ObjRef>, depth: u32) {
    if depth > 64 {
        return;
    }
    match object {
        Object::Ref(r) => out.push(*r),
        Object::Array(a) => a.iter().for_each(|v| walk(v, out, depth + 1)),
        Object::Dict(d) => d.iter().for_each(|(_, v)| walk(v, out, depth + 1)),
        Object::Stream(s) => s.dict.iter().for_each(|(_, v)| walk(v, out, depth + 1)),
        _ => {}
    }
}

// A destination that cannot be repaired is the one hard failure.
#[test]
fn a_destination_with_no_catalog_is_the_one_hard_failure() {
    // No `/Root` at all, and nothing the rebuild can find.
    let Ok(dest) = load(
        Arc::from(&b"%PDF-1.7\n1 0 obj\n<< /Type /Page >>\nendobj\ntrailer\n<< >>\n"[..]),
        &LoadOptions::default(),
    ) else {
        // Refusing to open is the reader's answer and is also correct.
        return;
    };
    let src = open(&source(1));
    let mut edit = EditDoc::new(&dest);
    assert!(matches!(
        import_pages(
            &mut edit,
            &src,
            &PageRange::all(1),
            &ImportOptions::default()
        ),
        Err(pdfrum_edit::Error::NoDestinationCatalog)
    ));
}