pdf2 1.7.0

A PDF 2.0 (ISO 32000-2) reader, writer and text extractor.
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
//! Editing an opened document: the overlay (M2), and the save once it lands.
//!
//! The base document is never modified, which is the property the whole model
//! rests on (ADR 0006): a reader that keeps the `Document` sees the file as it
//! was, and only the overlay knows about the edit.

use pdf2::{Document, Error, MutableDocument, Object, ObjectId};

const TEXT: &[u8] = include_bytes!("fixtures/text.pdf");

fn opened() -> Document {
    Document::open(TEXT).expect("text.pdf opens")
}

/// The catalog's id, from the trailer's `/Root`.
fn catalog_id(document: &Document) -> ObjectId {
    match document.trailer().get(b"Root") {
        Some(Object::Reference(id)) => *id,
        other => panic!("trailer /Root is {other:?}"),
    }
}

#[test]
fn a_replaced_object_reads_back_new_from_the_overlay_and_old_from_the_base() {
    let base = opened();
    let id = catalog_id(&base);
    let original = base.get_object(id).expect("the catalog reads");
    let mut edit = MutableDocument::new(base);

    let mut replaced = pdf2::Dictionary::new();
    replaced.insert("Type", Object::Name(b"Catalog".to_vec()));
    replaced.insert("AnEdit", Object::Integer(42));
    edit.set_object(id, Object::Dictionary(replaced));

    assert_eq!(
        edit.get_object(id).expect("the overlay answers"),
        Object::Dictionary({
            let mut dict = pdf2::Dictionary::new();
            dict.insert("Type", Object::Name(b"Catalog".to_vec()));
            dict.insert("AnEdit", Object::Integer(42));
            dict
        }),
        "the overlay returns what was set"
    );
    assert_eq!(
        edit.base().get_object(id).expect("the base still answers"),
        original,
        "the base document is untouched"
    );
    assert_eq!(edit.changes().len(), 1, "one change is recorded");
}

#[test]
fn a_deleted_object_is_absent_from_the_overlay_and_still_there_in_the_base() {
    let base = opened();
    let id = catalog_id(&base);
    let original = base.get_object(id).expect("the catalog reads");
    let mut edit = MutableDocument::new(base);

    edit.delete_object(id);

    assert!(
        edit.get_object(id).is_err(),
        "a deleted object reads as absent"
    );
    assert!(
        edit.base().get_object(id).is_ok(),
        "the base still has it: the deletion is an overlay fact, not a byte edit"
    );
    assert_eq!(
        edit.deleted().iter().copied().collect::<Vec<_>>(),
        vec![id.number]
    );

    // Deleting what the overlay added leaves no trace at all: there is no `f` row
    // to write for an object the file never had.
    let added = edit.add_object(Object::Integer(7));
    edit.delete_object(added);
    assert!(!edit.changes().contains_key(&added));
    assert!(!edit.deleted().contains(&added.number));
    assert_eq!(edit.base().get_object(id).unwrap(), original);
}

#[test]
fn added_objects_take_numbers_from_size_and_never_reuse_them() {
    let base = opened();
    let size = match base.trailer().get(b"Size") {
        Some(Object::Integer(size)) => *size as u32,
        other => panic!("trailer /Size is {other:?}"),
    };
    let mut edit = MutableDocument::new(base);
    assert_eq!(edit.next_object(), size.max(edit.next_object()));

    let first = edit.add_object(Object::Integer(1));
    let second = edit.add_object(Object::Integer(2));
    assert_eq!(
        first.number, size,
        "the first added number is the base's /Size"
    );
    assert_eq!(second.number, size + 1, "numbers increase by one");
    assert_eq!(edit.get_object(first).unwrap(), Object::Integer(1));
    assert_eq!(edit.get_object(second).unwrap(), Object::Integer(2));
}

#[test]
fn an_added_page_appears_in_the_overlay_and_not_in_the_base() {
    let base = opened();
    let before = base.page_count().expect("text.pdf has pages");
    let base_first = base.page(0).expect("the first page reads");
    let mut edit = MutableDocument::new(base);

    let page = edit
        .add_page(b"BT /F1 24 Tf 72 720 Td (a page added by an edit) Tj ET")
        .expect("the page is added");

    assert_eq!(
        edit.page_count().expect("the overlay counts"),
        before + 1,
        "the page count grows in the overlay"
    );
    assert_eq!(
        edit.base().page_count().expect("the base counts"),
        before,
        "the base document still reports the old count"
    );
    let added = edit.page(before).expect("the added page is last");
    assert_eq!(
        added.id,
        Some(page),
        "the added page has the id handed back"
    );
    assert_eq!(
        added.media_box, base_first.media_box,
        "the new page inherits the document's box rather than the default"
    );
    assert_eq!(added.contents.len(), 1, "the page has its content stream");
}

#[test]
fn adding_past_the_page_ceiling_is_refused_before_anything_changes() {
    let base = opened();
    let pages = base.page_count().expect("text.pdf has pages");
    let mut edit = MutableDocument::new(base);
    edit.base().set_page_limit(pages);
    let next_before = edit.next_object();

    let error = edit
        .add_page(b"BT (over the ceiling) Tj ET")
        .expect_err("the ceiling fires");
    match error {
        Error::TooMany { what, limit } => {
            assert_eq!(what, "the page tree");
            assert_eq!(limit, pages);
        }
        other => panic!("expected Error::TooMany, got {other:?}"),
    }
    assert_eq!(edit.page_count().unwrap(), pages, "no page was added");
    assert!(edit.changes().is_empty(), "nothing was written");
    assert_eq!(edit.next_object(), next_before, "no number was consumed");
}

#[test]
fn a_saved_edit_starts_with_the_base_and_reopens_with_the_page() {
    let base = opened();
    let pages_before = base.page_count().expect("text.pdf has pages");
    let first_page_before = base
        .extract_text(&base.page(0).expect("the first page reads"))
        .expect("the first page's text extracts");
    let mut edit = MutableDocument::new(base);
    edit.add_page(b"BT /F1 18 Tf 72 720 Td (a page added by an edit) Tj ET")
        .expect("the page is added");

    let saved = edit.save_incremental().expect("the edit saves");

    assert!(
        saved.starts_with(TEXT),
        "the saved bytes start with the base bytes: {} appended",
        saved.len() - TEXT.len()
    );
    let reopened = Document::open(&saved[..]).expect("the saved file opens");
    assert_eq!(
        reopened.page_count().expect("the saved file counts"),
        pages_before + 1,
        "one page more than the base"
    );
    assert_eq!(
        reopened
            .extract_text(&reopened.page(0).expect("the first page reads"))
            .expect("the first page's text extracts"),
        first_page_before,
        "the first page still extracts what it did"
    );
    let added = reopened.page(pages_before).expect("the added page is last");
    assert_eq!(
        reopened
            .extract_text(&added)
            .expect("the added page's text extracts"),
        "a page added by an edit",
        "the added page's own text extracts"
    );
}

#[test]
fn a_deleted_object_is_a_free_row_and_the_saved_file_still_opens() {
    // A base with an object nothing references: deleting a live one would leave
    // the page pointing at a free entry, which is a broken document, not a test.
    // The builder gives a file whose spare object can go without touching the
    // page's text.
    let mut builder = Document::new();
    builder.add_page(
        pdf2::Rect::new(0.0, 0.0, 612.0, 792.0),
        "BT /F1 18 Tf 72 700 Td (a page worth keeping) Tj ET",
    );
    let spare = builder.add_object(Object::Integer(1234));
    let base_bytes = builder.save().expect("the base saves");
    let base = Document::open(&base_bytes[..]).expect("the base opens");
    assert!(base.contains_object(spare), "the spare object is live");
    let text_before = base
        .extract_text(&base.page(0).expect("the page reads"))
        .expect("the page's text extracts");

    let mut edit = MutableDocument::new(base);
    edit.delete_object(ObjectId::new(spare, 0));
    assert!(
        edit.get_object(ObjectId::new(spare, 0)).is_err(),
        "deleted in the overlay"
    );

    let saved = edit.save_incremental().expect("the edit saves");
    assert!(
        saved.starts_with(&base_bytes[..]),
        "the saved bytes start with the base bytes"
    );
    let section = String::from_utf8_lossy(&saved[base_bytes.len()..]).to_string();
    assert!(
        section.contains("0000000000 00001 f"),
        "the deletion is a free row in the appended section:\n{section}"
    );

    let reopened = Document::open(&saved[..]).expect("the saved file opens");
    assert!(
        !reopened.contains_object(spare),
        "the deleted number is free in the saved file"
    );
    assert_eq!(
        reopened
            .extract_text(&reopened.page(0).expect("the page reads"))
            .expect("the page's text still extracts"),
        text_before,
        "the page is untouched by the deletion"
    );
}

#[test]
fn a_saved_edit_can_be_opened_edited_and_saved_again() {
    // A second update over the first: the appended section has to be readable as
    // a base, with its own `/Prev` chain, or editing is a one-shot operation.
    let first = {
        let mut edit = MutableDocument::new(opened());
        edit.add_page(b"BT /F1 18 Tf 72 700 Td (first edit) Tj ET")
            .expect("the first page is added");
        edit.save_incremental().expect("the first edit saves")
    };
    let second = {
        let base = Document::open(&first[..]).expect("the first save opens");
        let mut edit = MutableDocument::new(base);
        edit.add_page(b"BT /F1 18 Tf 72 600 Td (second edit) Tj ET")
            .expect("the second page is added");
        edit.save_incremental().expect("the second edit saves")
    };

    assert!(
        second.starts_with(&first[..]),
        "each save appends to what it opened"
    );
    let reopened = Document::open(&second[..]).expect("the second save opens");
    assert_eq!(
        reopened.page_count().expect("the second save counts"),
        3,
        "one page from the base and one from each edit"
    );
    let texts: Vec<String> = (0..3)
        .map(|index| {
            reopened
                .extract_text(&reopened.page(index).expect("the page reads"))
                .expect("the page's text extracts")
        })
        .collect();
    assert!(
        texts[1].contains("first edit"),
        "the first edit is intact: {texts:?}"
    );
    assert!(
        texts[2].contains("second edit"),
        "the second edit is there: {texts:?}"
    );
}

/// The offset the newest `startxref` names, read from the raw bytes.
fn last_startxref(bytes: &[u8]) -> i64 {
    let at = bytes
        .windows(b"startxref".len())
        .rposition(|window| window == b"startxref")
        .expect("a startxref");
    let rest = &bytes[at + b"startxref".len()..];
    let start = rest
        .iter()
        .position(|byte| byte.is_ascii_digit())
        .expect("a startxref offset");
    let end = start
        + rest[start..]
            .iter()
            .position(|byte| !byte.is_ascii_digit())
            .expect("the end of the offset");
    core::str::from_utf8(&rest[start..end])
        .expect("ASCII digits")
        .parse()
        .expect("a number")
}

#[test]
fn the_appended_trailer_names_the_previous_section_and_keeps_the_first_identifier() {
    const TWIN: &[u8] = include_bytes!("fixtures/plain-twin.pdf");
    let base = Document::open(TWIN).expect("plain-twin.pdf opens");
    let base_ids = match base.trailer().get(b"ID") {
        Some(Object::Array(ids)) => ids.clone(),
        other => panic!("the base /ID is {other:?}"),
    };
    assert_eq!(base_ids.len(), 2, "the base has two identifier strings");
    let mut edit = MutableDocument::new(base);
    edit.add_page(b"BT /F1 18 Tf 72 700 Td (added) Tj ET")
        .expect("the page is added");
    let expected_size = edit.next_object();

    let saved = edit.save_incremental().expect("the edit saves");

    // `/Prev` is the base's last `startxref`, read from the bytes rather than
    // remembered: that is the number a reader follows into the previous section.
    let appended = &saved[TWIN.len()..];
    let section = String::from_utf8_lossy(appended).to_string();
    assert!(
        section.contains(&format!("/Prev {}", last_startxref(TWIN))),
        "the trailer names the base's last section:\n{section}"
    );

    let reopened = Document::open(&saved[..]).expect("the saved file opens");
    let trailer = reopened.trailer();
    assert_eq!(
        trailer.get(b"Prev"),
        Some(&Object::Integer(last_startxref(TWIN))),
        "the newest trailer's /Prev is the base's startxref"
    );
    assert_eq!(
        trailer.get(b"Size"),
        Some(&Object::Integer(i64::from(expected_size))),
        "the newest trailer's /Size covers the highest number written"
    );

    // `14.4`: the first string is permanent — an encrypted file's key derives
    // from it — and the second is the one an update replaces.
    let ids = match trailer.get(b"ID") {
        Some(Object::Array(ids)) => ids.clone(),
        other => panic!("the saved /ID is {other:?}"),
    };
    assert_eq!(ids.len(), 2, "still two identifier strings");
    assert_eq!(ids[0], base_ids[0], "the first string is byte-identical");
    assert_ne!(ids[1], base_ids[1], "the second string changed");
}

#[test]
fn a_base_without_an_identifier_gets_no_identifier_from_the_update() {
    let base = opened();
    assert!(
        base.trailer().get(b"ID").is_none(),
        "text.pdf carries no /ID"
    );
    let mut edit = MutableDocument::new(base);
    edit.add_page(b"BT /F1 18 Tf 72 700 Td (added) Tj ET")
        .expect("the page is added");
    let saved = edit.save_incremental().expect("the edit saves");

    let section = String::from_utf8_lossy(&saved[TEXT.len()..]).to_string();
    assert!(
        !section.contains("/ID"),
        "an update invents no identifier:\n{section}"
    );
    let reopened = Document::open(&saved[..]).expect("the saved file opens");
    assert!(
        reopened.trailer().get(b"ID").is_none(),
        "the saved file has no /ID either"
    );
}

#[test]
fn a_save_past_the_object_ceiling_returns_too_many_and_produces_no_bytes() {
    let base = opened();
    let pages = base.page_count().expect("text.pdf has pages");
    let mut edit = MutableDocument::new(base);
    // Three pages is six objects: a page and its content stream each, plus the
    // rewritten page tree. A ceiling of two is below that and above nothing.
    edit.base().set_object_limit(2);
    for index in 0..3 {
        edit.add_page(format!("BT /F1 18 Tf 72 700 Td (page {index}) Tj ET"))
            .expect("the page is added in memory");
    }
    assert!(
        edit.changes().len() > 2,
        "the overlay holds more than the ceiling: {}",
        edit.changes().len()
    );

    let error = edit
        .save_incremental()
        .expect_err("the ceiling fires before any bytes");
    match error {
        Error::TooMany { what, limit } => {
            assert_eq!(what, "the number of objects an update writes");
            assert_eq!(limit, 2);
        }
        other => panic!("expected Error::TooMany, got {other:?}"),
    }
    assert_eq!(
        edit.page_count().expect("the overlay still counts"),
        pages + 3,
        "nothing was lost: the ceiling stopped the save, not the edit"
    );
}

/// Open an encrypted fixture with its user password.
fn opened_encrypted(bytes: &[u8]) -> Document {
    Document::open_with_password(bytes, b"user").expect("the fixture opens with its user password")
}

/// Add a page, save, and reopen with the same password: the appended objects
/// have to decrypt with the key the base's encryption dictates.
fn encrypted_round_trip(bytes: &[u8], expected: &str) {
    let base = opened_encrypted(bytes);
    let pages = base.page_count().expect("the base has pages");
    let first_page_before = base
        .extract_text(&base.page(0).expect("the first page reads"))
        .expect("the first page's text extracts");
    let mut edit = MutableDocument::new(base);
    edit.add_page(format!("BT /F1 18 Tf 72 700 Td ({expected}) Tj ET"))
        .expect("the page is added");
    let saved = edit.save_incremental().expect("the edit saves");

    assert!(
        saved.starts_with(bytes),
        "the saved bytes start with the base bytes"
    );
    let appended = String::from_utf8_lossy(&saved[bytes.len()..]).to_string();
    assert!(
        !appended.contains(expected),
        "the appended page's text is not in the clear:\n{appended}"
    );

    let reopened = opened_encrypted(&saved[..]);
    assert_eq!(
        reopened.page_count().expect("the saved file counts"),
        pages + 1,
        "the page is there after reopening"
    );
    assert_eq!(
        reopened
            .extract_text(&reopened.page(0).expect("the first page reads"))
            .expect("the first page's text extracts"),
        first_page_before,
        "the base pages still decrypt to what they did"
    );
    assert_eq!(
        reopened
            .extract_text(&reopened.page(pages).expect("the added page is last"))
            .expect("the added page's text extracts"),
        expected,
        "the appended page decrypts to its own text"
    );
}

#[test]
fn an_r4_aes_base_round_trips_through_the_save() {
    const ENCRYPTED: &[u8] = include_bytes!("fixtures/encrypted-r4-aes.pdf");
    encrypted_round_trip(ENCRYPTED, "added to an rc4 and aes revision 4 file");
}

#[test]
fn an_r4_rc4_base_round_trips_through_the_save() {
    const ENCRYPTED: &[u8] = include_bytes!("fixtures/encrypted-r4-rc4.pdf");
    encrypted_round_trip(ENCRYPTED, "added to a revision 4 rc4 file");
}

#[test]
fn an_r6_aes256_base_round_trips_through_the_save() {
    const ENCRYPTED: &[u8] = include_bytes!("fixtures/encrypted-r6.pdf");
    encrypted_round_trip(ENCRYPTED, "added to a revision 6 file");
}

// ---------------------------------------------------------------- external reader

/// Where a test writes its scratch files, under the target directory.
fn scratch(name: &str) -> std::path::PathBuf {
    let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")).join(name);
    // Empty, so a previous run's renders cannot be mistaken for this one's.
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).expect("the scratch directory");
    dir
}

/// Whether a program is on `PATH`, so the external check can skip rather than
/// fail on a machine that has no PDF engines installed.
fn on_path(program: &str) -> bool {
    std::process::Command::new(program)
        .arg("-v")
        .output()
        .is_ok()
}

/// The darkest sample in a binary PNM (`P5` gray or `P6` colour), after its
/// header — 255 means the page is blank, anything lower means ink.
fn darkest_in_pnm(bytes: &[u8]) -> u8 {
    let mut fields = 0;
    let mut index = 0;
    while fields < 4 && index < bytes.len() {
        while index < bytes.len() && bytes[index].is_ascii_whitespace() {
            index += 1;
        }
        if index < bytes.len() && bytes[index] == b'#' {
            while index < bytes.len() && bytes[index] != b'\n' {
                index += 1;
            }
            continue;
        }
        while index < bytes.len() && !bytes[index].is_ascii_whitespace() {
            index += 1;
        }
        fields += 1;
    }
    index += 1;
    bytes[index.min(bytes.len())..]
        .iter()
        .copied()
        .min()
        .unwrap_or(255)
}

/// Run one external renderer over `path`'s page `page` and return the bytes it
/// wrote, discovering the file by prefix rather than guessing how the tool pads
/// page numbers.
fn render(tool: &str, path: &std::path::Path, page: usize, directory: &std::path::Path) -> Vec<u8> {
    let prefix = directory.join(tool);
    let run = match tool {
        "pdftoppm" => std::process::Command::new("pdftoppm")
            .args([
                "-r",
                "72",
                "-f",
                &page.to_string(),
                "-l",
                &page.to_string(),
                "-gray",
            ])
            .arg(path)
            .arg(&prefix)
            .output(),
        _ => std::process::Command::new("mutool")
            .args(["draw", "-r", "72", "-o"])
            .arg(directory.join("mutool.pnm"))
            .arg(path)
            .arg(page.to_string())
            .output(),
    }
    .expect("the tool runs");
    assert!(
        run.status.success(),
        "{tool} rejected the saved file: status {:?}\nstdout: {}\nstderr: {}",
        run.status.code(),
        String::from_utf8_lossy(&run.stdout),
        String::from_utf8_lossy(&run.stderr),
    );

    let mut written: Vec<std::path::PathBuf> = std::fs::read_dir(directory)
        .expect("the scratch directory lists")
        .filter_map(|entry| entry.ok())
        .map(|entry| entry.path())
        .filter(|candidate| {
            candidate
                .file_name()
                .and_then(|name| name.to_str())
                .is_some_and(|name| name.starts_with(tool) && !name.ends_with(".pdf"))
        })
        .collect();
    written.sort();
    let file = written
        .first()
        .unwrap_or_else(|| panic!("{tool} wrote no output into {}", directory.display()));
    std::fs::read(file).expect("the rendered file reads")
}

#[test]
fn poppler_and_mupdf_render_the_saved_file() {
    let tools: Vec<&str> = ["pdftoppm", "mutool"]
        .into_iter()
        .filter(|tool| on_path(tool))
        .collect();
    if tools.is_empty() {
        println!(
            "skipped: neither pdftoppm nor mutool is on PATH (the oracle job has both; \
             finding (8) in the plan says a developer machine has neither)"
        );
        return;
    }

    let base = opened();
    let pages = base.page_count().expect("text.pdf has pages");
    let mut edit = MutableDocument::new(base);
    edit.add_page(b"BT /F1 24 Tf 72 700 Td (added, and visible) Tj ET")
        .expect("the page is added");
    let saved = edit.save_incremental().expect("the edit saves");
    let directory = scratch("external-reader");
    let path = directory.join("edited.pdf");
    std::fs::write(&path, &saved).expect("the saved file is written");

    // The page the edit added, rendered by a program that has never seen this
    // crate: an appended section a third-party reader rejects is not a save.
    for tool in &tools {
        let darkest = darkest_in_pnm(&render(tool, &path, pages + 1, &directory));
        println!(
            "{tool} rendered page {} of the saved file: darkest {darkest} of 255, {} bytes appended",
            pages + 1,
            saved.len() - TEXT.len()
        );
        assert!(
            darkest < 250,
            "{tool} rendered a blank page for the added page: darkest {darkest} of 255"
        );
    }
}

#[test]
fn the_pnm_reader_finds_ink_and_clears_blank_pages() {
    // The external check's own oracle: the header parse is what decides "blank",
    // so it is tested without an engine — a blank gray page and an inked one.
    let blank = b"P5\n4 2\n255\n\xff\xff\xff\xff\xff\xff\xff\xff".to_vec();
    assert_eq!(darkest_in_pnm(&blank), 255, "a blank page has no ink");
    let inked = b"P5\n4 2\n255\n\xff\xff\xff\xff\x00\xff\xff\xff".to_vec();
    assert_eq!(darkest_in_pnm(&inked), 0, "one black pixel is ink");
    let comment = b"P6\n# written by a tool\n2 1\n255\n\x10\x20\x30\x40\x50\x60".to_vec();
    assert_eq!(
        darkest_in_pnm(&comment),
        0x10,
        "a comment line is skipped, and colour is read the same way"
    );
}