caj2pdf-core 0.8.1

Platform-neutral CAJ-family conversion core
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
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
// SPDX-License-Identifier: MIT

use super::*;
use crate::ErrorKind;
use crate::pdf::{MAX_CLASSIC_PDF_BYTES, PdfIndex, PdfRange};
use crate::test_support::{CancelAfter, NEVER};
use std::io;
use std::io::Write;

/// A source whose bytes are all `0x5A`, optionally claiming to have read
/// one byte more than the caller requested.
struct FilledSource {
    size: u64,
    over_report: bool,
}

impl FilledSource {
    fn new(size: u64) -> Self {
        Self {
            size,
            over_report: false,
        }
    }
}

impl RangedSource for FilledSource {
    fn size(&self) -> u64 {
        self.size
    }

    fn read_at(&mut self, offset: u64, destination: &mut [u8]) -> Result<usize> {
        let available = self.size.saturating_sub(offset);
        let copied = destination.len().min(available as usize);
        destination[..copied].fill(0x5a);
        Ok(copied + usize::from(self.over_report))
    }
}

#[derive(Default)]
struct VecSink {
    bytes: Vec<u8>,
    writes: usize,
    fail_at_write: Option<usize>,
}

impl Write for VecSink {
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
        self.writes += 1;
        if self.fail_at_write == Some(self.writes) {
            return Err(io::Error::other("injected sink failure"));
        }
        self.bytes.extend_from_slice(bytes);
        Ok(bytes.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

fn page() -> PageSpec {
    PageSpec {
        width_points: 100.0,
        height_points: 50.0,
    }
}

fn gray_pixels(pixel_width: u32) -> ImageSpec {
    ImageSpec {
        pixel_width,
        pixel_height: 1,
        encoding: ImageEncoding::Gray8,
    }
}

fn bookmark(depth: u32, title: &str) -> Bookmark {
    Bookmark {
        depth,
        title: title.into(),
        page_index: 0,
    }
}

fn index_pdf(bytes: Vec<u8>) -> Result<PdfIndex> {
    let length = bytes.len() as u64;
    let mut source = crate::native::SeekableSource::new(io::Cursor::new(bytes))?;
    PdfIndex::open(
        &mut source,
        PdfRange { offset: 0, length },
        &Limits::default(),
        &NEVER,
    )
}

#[test]
fn info_dictionary_holds_only_present_values_as_utf16_text() {
    let write = |info: &[(&'static str, Option<&str>)]| {
        let limits = Limits::default();
        let mut sink = VecSink::default();
        let mut source = FilledSource::new(1);
        let result = (|| {
            let mut document = PdfDocument::new(&mut sink, &limits, &NEVER)?;
            document.add_image_page(&mut source, 0, 1, page(), gray_pixels(1))?;
            document.finish_with_info(info)
        })();
        (result, sink.bytes)
    };
    let (_, plain) = write(&[]);
    let (_, absent) = write(&[("Subject", None)]);
    assert_eq!(absent, plain);
    let (report, pdf) = write(&[
        ("Subject", Some("A\u{4e2d}")),
        ("Empty", None),
        ("X_1", Some("")),
    ]);
    let text = String::from_utf8_lossy(&pdf).into_owned();
    assert!(
        text.contains("<< /Subject <FEFF00414E2D> /X_1 <FEFF> >>"),
        "{text}"
    );
    assert!(text.contains(" /Info "), "{text}");
    assert_eq!(report.unwrap().output_bytes_written, pdf.len() as u64);
    assert_eq!(index_pdf(pdf).unwrap().pages().len(), 1);
    for key in ["", "Sub ject", "/Subject"] {
        let (error, pdf) = write(&[(key, Some("x"))]);
        assert!(matches!(
            error,
            Err(Error {
                kind: ErrorKind::Malformed,
                reason: "PDF Info key must be a plain ASCII name",
                ..
            })
        ));
        assert!(!String::from_utf8_lossy(&pdf).contains("trailer"));
    }
}

#[test]
fn decimal_matrices_preserve_small_values_and_signed_bounds_without_exponents() {
    let values = [
        f64::from_bits(1),
        -f64::from_bits(1),
        f64::MIN_POSITIVE,
        -(MAX_PDF_INTEGER as f64),
        MAX_PDF_INTEGER as f64,
        -0.0,
    ];
    let text = decimals(&values).unwrap();
    assert!(
        text.bytes()
            .all(|b| b.is_ascii_digit() || b"-. ".contains(&b))
    );
    let words: Vec<_> = text.split_ascii_whitespace().collect();
    assert_eq!(words.len(), 6);
    for (word, value) in words.iter().zip(values) {
        assert_eq!(word.parse::<f64>().unwrap(), value);
    }
    assert_eq!(words[5], "0");
    let small = decimals(&[1.0e-20; 6]).unwrap();
    assert!(small.contains("0.00000000000000000001"));
    let worst = decimals(&[-f64::from_bits(1); 6]).unwrap();
    assert_eq!(worst.split_ascii_whitespace().count(), 6);
}

#[test]
fn decimal_matrices_reject_nonfinite_and_out_of_profile_components() {
    for bad in [
        f64::NAN,
        f64::INFINITY,
        f64::NEG_INFINITY,
        MAX_PDF_INTEGER as f64 + 1.0,
        -(MAX_PDF_INTEGER as f64 + 1.0),
    ] {
        // Invalid late components must be rejected as well as the first one.
        for index in [0, 5] {
            let mut values = [1.0; 6];
            values[index] = bad;
            assert!(matches!(
                decimals(&values),
                Err(Error {
                    kind: ErrorKind::Malformed,
                    ..
                })
            ));
        }
    }
    // Singular matrices are deliberately allowed, with no rounding or epsilon
    // determinant rule. PDF consumers decide their visibility.
    assert_eq!(decimals(&[0.0; 6]).unwrap(), "0 0 0 0 0 0");
}

#[test]
fn affine_preflight_at_leaf_rollover_preserves_existing_pages_and_object_ids() {
    // 256 placed pages reserve 774 objects. Their successor needs a new leaf
    // plus three page objects, exceeding this 777-offset allocation ceiling.
    let limits = Limits {
        io_chunk_bytes: 8,
        max_allocation_bytes: 777 * 8,
        ..Limits::default()
    };
    let mut sink = VecSink::default();
    let mut source = FilledSource::new(1);
    let report = (|| {
        let mut document = PdfDocument::new(&mut sink, &limits, &NEVER)?;
        let image = document.add_image(&mut source, 0, 1, gray_pixels(1))?;
        let placement = ImagePlacement {
            image,
            transform: [100.0, 0.0, 0.0, -50.0, 0.25, 50.125],
        };
        for index in 0..256 {
            assert_eq!(document.add_placed_page(page(), &[placement])?, index);
        }
        let before = document.writer.position();
        let mut invalid = placement;
        invalid.transform[5] = f64::INFINITY;
        assert!(matches!(
            document.add_placed_page(page(), &[placement, invalid]),
            Err(Error {
                kind: ErrorKind::Malformed,
                ..
            })
        ));
        assert_eq!(document.writer.position(), before);
        assert!(matches!(
            document.add_placed_page(page(), &[placement]),
            Err(Error {
                kind: ErrorKind::LimitExceeded {
                    resource: "allocation bytes",
                    limit: 6216,
                    attempted: 6224,
                    ..
                },
                ..
            })
        ));
        assert_eq!(document.writer.position(), before);
        document.finish()
    })()
    .unwrap();
    assert_eq!(report.pages_converted, 256);
    assert_eq!(report.input_bytes_read, 1);
    assert_eq!(report.output_bytes_written, sink.bytes.len() as u64);
    index_pdf(sink.bytes).expect("refused rollover leaves a valid completed page tree");
}

fn write_sample<W: Write, C: Cancellation>(
    sink: &mut W,
    limits: &Limits,
    cancellation: &C,
) -> Result<ConversionReport> {
    let mut source = FilledSource::new(3);
    let mut document = PdfDocument::new(sink, limits, cancellation)?;
    for _ in 0..2 {
        document.add_image_page(&mut source, 0, 3, page(), gray_pixels(3))?;
    }
    document.add_bookmark(bookmark(0, "Root"))?;
    document.add_bookmark(bookmark(1, "Child"))?;
    document.add_bookmark(bookmark(0, "Next"))?;
    document.finish()
}

#[test]
fn image_source_that_over_reports_is_rejected() {
    let mut source = FilledSource {
        over_report: true,
        ..FilledSource::new(4)
    };
    let mut sink = VecSink::default();
    let limits = Limits::default();
    let error = (|| {
        let mut document = PdfDocument::new(&mut sink, &limits, &NEVER)?;
        document.add_image_page(&mut source, 0, 4, page(), gray_pixels(4))
    })()
    .unwrap_err();
    assert!(matches!(
        error,
        Error {
            kind: ErrorKind::Malformed,
            reason: "image source reported more bytes than requested",
            ..
        }
    ));
}

#[test]
fn jpeg_stream_longer_than_a_pdf_integer_is_rejected_before_reading() {
    let length = MAX_PDF_INTEGER + 1;
    let mut source = FilledSource::new(length);
    let mut sink = VecSink::default();
    let limits = Limits::default();
    let (error, header_bytes) = (|| {
        let mut document = PdfDocument::new(&mut sink, &limits, &NEVER)?;
        let header_bytes = document.writer.position();
        let image = ImageSpec {
            pixel_width: 10,
            pixel_height: 10,
            encoding: ImageEncoding::JpegRgb8,
        };
        let error = document
            .add_image_page(&mut source, 0, length, page(), image)
            .unwrap_err();
        assert_eq!(document.input_bytes_read, 0);
        Ok::<_, Error>((error, header_bytes))
    })()
    .unwrap();
    assert!(matches!(
        error,
        Error { kind: ErrorKind::LimitExceeded { resource: "PDF image stream bytes", limit: MAX_PDF_INTEGER, attempted, .. }, .. } if attempted == length
    ));
    assert_eq!(sink.bytes.len() as u64, header_bytes);
}

#[test]
fn page_tree_capacity_is_checked_before_any_page_output() {
    let mut source = FilledSource::new(1);
    let mut sink = VecSink::default();
    let limits = Limits {
        max_pages: u32::MAX,
        ..Limits::default()
    };
    let error = (|| {
        let mut document = PdfDocument::new(&mut sink, &limits, &NEVER)?;
        document.pages_written = MAX_TREE_PAGES as u32;
        document.add_image_page(&mut source, 0, 1, page(), gray_pixels(1))
    })()
    .unwrap_err();
    assert!(matches!(
        error,
        Error { kind: ErrorKind::LimitExceeded { resource: "PDF page-tree capacity", limit: MAX_TREE_PAGES, attempted, .. }, .. } if attempted == MAX_TREE_PAGES + 1
    ));
}

/// Counts output bytes and keeps only page-tree node objects, so a very
/// large document can be checked without retaining or rescanning it.
#[derive(Default)]
struct PageTreeSink {
    written: u64,
    object: Vec<u8>,
    page_nodes: Vec<Vec<u8>>,
}

impl Write for PageTreeSink {
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
        // Page-tree nodes are small; larger runs (the xref table) are
        // never page-tree objects and need not be retained.
        if self.object.len() > 64 * 1024 {
            self.object.clear();
        }
        self.written += bytes.len() as u64;
        self.object.extend_from_slice(bytes);
        if self.object.ends_with(b"\nendobj\n") {
            let body = self
                .object
                .iter()
                .position(|byte| *byte == b'\n')
                .map_or(&[][..], |header| &self.object[header + 1..]);
            if body.starts_with(b"<< /Type /Pages ") {
                self.page_nodes.push(body.to_vec());
            }
            self.object.clear();
        }
        Ok(bytes.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

/// A one-pixel image that many pages can share, which keeps documents with
/// full page-tree nodes cheap to build.
fn shared_image<W: Write>(document: &mut PdfDocument<'_, W, CancelAfter>) -> Result<ImageObject> {
    let mut writer = document.begin_bilevel_image(BilevelImageSpec {
        pixel_width: 1,
        pixel_height: 1,
        row_stride: 1,
    })?;
    writer.write_all(&[0])?;
    writer.finish()
}

#[test]
fn full_middle_node_starts_a_second_root_kid() -> Result<()> {
    const PER_MIDDLE: usize = PAGE_TREE_FANOUT * PAGE_TREE_FANOUT;
    const PAGES: u32 = PER_MIDDLE as u32 + 1;
    let mut sink = PageTreeSink::default();
    let limits = Limits::default();
    let report = (|| {
        let mut document = PdfDocument::new(&mut sink, &limits, &NEVER)?;
        let image = shared_image(&mut document)?;
        for expected in 0..PAGES {
            let index = document.add_page(page(), &[image])?;
            assert_eq!(index, expected);
        }
        assert_eq!(document.root_children.len(), 1);
        document.finish()
    })()?;
    assert_eq!(report.pages_converted, PAGES);
    assert_eq!(report.output_bytes_written, sink.written);
    // 257 leaves, two middle nodes, and the root.
    assert_eq!(sink.page_nodes.len(), 257 + 2 + 1);
    let root_prefix = format!("<< /Type /Pages /Count {PAGES} /Kids [");
    let roots: Vec<_> = sink
        .page_nodes
        .iter()
        .filter(|node| node.starts_with(root_prefix.as_bytes()))
        .collect();
    assert_eq!(roots.len(), 1);
    let root_kids = roots[0]
        .windows(b" 0 R".len())
        .filter(|window| *window == b" 0 R")
        .count();
    assert_eq!(root_kids, 2);
    let full_middle = format!("/Count {PER_MIDDLE} /Kids [");
    let full_middles = sink
        .page_nodes
        .iter()
        .filter(|node| {
            node.windows(full_middle.len())
                .any(|window| window == full_middle.as_bytes())
        })
        .count();
    assert_eq!(full_middles, 1);
    Ok(())
}

#[test]
fn page_nodes_lost_to_failed_writes_make_finish_fail() -> Result<()> {
    const PER_MIDDLE: usize = PAGE_TREE_FANOUT * PAGE_TREE_FANOUT;
    let mut sink = PageTreeSink::default();
    let limits = Limits::default();
    let (leaf_failure, middle_failure, finish) = (|| {
        let mut document = PdfDocument::new(&mut sink, &limits, &NEVER)?;
        let image = shared_image(&mut document)?;
        for _ in 0..PER_MIDDLE {
            document.add_page(page(), &[image])?;
        }
        // Writing a closed node would pass the classic xref limit, which
        // fails before the sink sees a byte and leaves the writer usable.
        let position = document.writer.position();
        document.writer.set_position_for_test(MAX_CLASSIC_PDF_BYTES);
        // The full leaf is detached before its write fails, and on the
        // next page the full middle node is.
        let leaf_failure = document.add_page(page(), &[image]);
        let middle_failure = document.add_page(page(), &[image]);
        document.writer.set_position_for_test(position);
        Ok::<_, Error>((leaf_failure, middle_failure, document.finish()))
    })()?;
    for failure in [leaf_failure.map(|_| ()), middle_failure.map(|_| ())] {
        assert!(matches!(
            failure,
            Err(Error {
                kind: ErrorKind::LimitExceeded {
                    resource: "classic PDF file bytes",
                    ..
                },
                ..
            })
        ));
    }
    // Neither lost node is written, so no PDF with dangling kids completes.
    assert!(matches!(
        finish,
        Err(Error {
            kind: ErrorKind::Malformed,
            reason: "a reserved PDF object has not been written",
            ..
        })
    ));
    Ok(())
}

#[test]
fn outline_titles_are_chunked_and_empty_titles_stay_well_formed() -> Result<()> {
    let long_title = "\u{4E2D}".repeat(3000);
    let mut source = FilledSource::new(1);
    let mut sink = VecSink::default();
    let limits = Limits::default();
    let report = (|| {
        let mut document = PdfDocument::new(&mut sink, &limits, &NEVER)?;
        document.add_image_page(&mut source, 0, 1, page(), gray_pixels(1))?;
        document.add_bookmark(bookmark(0, &long_title))?;
        BookmarkVisitor::visit(&mut document, bookmark(1, ""))?;
        document.finish()
    })()?;
    assert_eq!(report.bookmarks_written, 2);
    let text = String::from_utf8_lossy(&sink.bytes);
    assert!(text.contains(&format!("/Title <FEFF{}>", "4E2D".repeat(3000))));
    assert!(text.contains("/Title <FEFF> /Parent"));
    assert!(text.contains(" /Count 1 >>"));
    let index = index_pdf(sink.bytes)?;
    assert!(index.has_outlines());
    Ok(())
}

#[test]
fn every_sink_failure_point_returns_the_io_error() {
    let limits = Limits::default();
    let mut clean = VecSink::default();
    write_sample(&mut clean, &limits, &NEVER).unwrap();
    assert!(clean.writes > 20);
    for fail_at in 1..=clean.writes {
        let mut sink = VecSink {
            fail_at_write: Some(fail_at),
            ..VecSink::default()
        };
        let result = write_sample(&mut sink, &limits, &NEVER);
        assert!(
            matches!(&result, Err(Error { kind: ErrorKind::Io(error), .. }) if error.to_string() == "injected sink failure"),
            "write {fail_at}: {result:?}"
        );
        assert_eq!(sink.writes, fail_at);
        assert!(clean.bytes.starts_with(&sink.bytes));
    }
}

#[test]
fn cancellation_at_every_checkpoint_never_reports_success() {
    let limits = Limits::default();
    let mut allowed = 0;
    loop {
        let mut sink = VecSink::default();
        let cancellation = CancelAfter::new(allowed);
        let report = match write_sample(&mut sink, &limits, &cancellation) {
            Err(Error {
                kind: ErrorKind::Cancelled,
                ..
            }) => {
                allowed += 1;
                continue;
            }
            result => result.expect("only cancellation may stop the run"),
        };
        assert!(allowed >= 20, "only {allowed} cancellation checks");
        assert_eq!(report.output_bytes_written, sink.bytes.len() as u64);
        break;
    }
}

#[test]
fn reserve_bounded_enforces_item_and_byte_ceilings() {
    let limits = Limits {
        io_chunk_bytes: 16,
        max_allocation_bytes: 64,
        ..Limits::default()
    };
    let mut values: Vec<u64> = Vec::new();
    for _ in 0..3 {
        reserve_bounded(&mut values, 3, &limits, "test items").unwrap();
        values.push(0);
    }
    assert!(matches!(
        reserve_bounded(&mut values, 3, &limits, "test items"),
        Err(Error {
            kind: ErrorKind::LimitExceeded {
                resource: "test items",
                limit: 3,
                attempted: 4,
                ..
            },
            ..
        })
    ));

    let mut wide: Vec<[u8; 40]> = vec![[0; 40]];
    assert!(matches!(
        reserve_bounded(&mut wide, 10, &limits, "wide items"),
        Err(Error {
            kind: ErrorKind::LimitExceeded {
                resource: "allocation bytes",
                limit: 64,
                attempted: 80,
                ..
            },
            ..
        })
    ));
    assert_eq!(wide.len(), 1);
}

#[test]
fn a_refused_bookmark_leaves_earlier_outline_items_writable() {
    // Walk the allocation ceiling across every refusal point of a nested
    // outline. Whenever a bookmark is refused, the items accepted before it
    // must still finish as a valid outline tree.
    let titles = [(0, "A"), (1, "B"), (2, "C"), (1, "D"), (0, "E"), (1, "F")];
    let mut refusals_checked = 0;
    for max_allocation_bytes in (64..4096).step_by(8) {
        let limits = Limits {
            io_chunk_bytes: 16,
            max_allocation_bytes,
            ..Limits::default()
        };
        let mut source = FilledSource::new(1);
        let mut sink = VecSink::default();
        let result = (|| {
            let mut document = PdfDocument::new(&mut sink, &limits, &NEVER)?;
            document.add_image_page(&mut source, 0, 1, page(), gray_pixels(1))?;
            let mut accepted = 0;
            for (depth, title) in titles {
                if document.add_bookmark(bookmark(depth, title)).is_err() {
                    break;
                }
                accepted += 1;
            }
            Ok::<_, Error>((accepted, document.finish()))
        })();
        let Ok((accepted, Ok(report))) = result else {
            continue;
        };
        if (1..titles.len()).contains(&accepted) {
            assert_eq!(report.bookmarks_written, accepted as u32);
            assert!(index_pdf(sink.bytes).unwrap().has_outlines());
            refusals_checked += 1;
        }
    }
    assert!(refusals_checked > 0);
}

#[test]
fn a_bookmark_that_fails_while_closing_items_stops_the_outline() -> Result<()> {
    let limits = Limits::default();
    let mut source = FilledSource::new(1);
    let mut sink = VecSink::default();
    let (failed, retry, finish) = (|| {
        let mut document = PdfDocument::new(&mut sink, &limits, &NEVER)?;
        document.add_image_page(&mut source, 0, 1, page(), gray_pixels(1))?;
        document.add_bookmark(bookmark(0, "A"))?;
        document.add_bookmark(bookmark(1, "B"))?;
        // Writing the closed items would pass the classic xref limit, which
        // fails before the sink sees a byte and so leaves the writer usable.
        let position = document.writer.position();
        document.writer.set_position_for_test(MAX_CLASSIC_PDF_BYTES);
        let failed = document.add_bookmark(bookmark(0, "C"));
        document.writer.set_position_for_test(position);
        let retry = document.add_bookmark(bookmark(0, "D"));
        Ok::<_, Error>((failed, retry, document.finish()))
    })()?;
    assert!(matches!(
        failed,
        Err(Error {
            kind: ErrorKind::LimitExceeded {
                resource: "classic PDF file bytes",
                ..
            },
            ..
        })
    ));
    for result in [retry, finish.map(|_| ())] {
        assert!(matches!(
            result,
            Err(Error {
                kind: ErrorKind::Malformed,
                reason: "PDF outline cannot continue after a failed bookmark operation",
                ..
            })
        ));
    }
    assert!(!sink.bytes.ends_with(b"%%EOF\n"));
    Ok(())
}

#[test]
fn bilevel_compressor_reservation_is_checked_before_opening_an_image() {
    let limits = Limits {
        io_chunk_bytes: 8,
        max_allocation_bytes: DEFLATE_RESERVATION_BYTES - 1,
        ..Limits::default()
    };
    let mut sink = VecSink::default();
    {
        let mut document = PdfDocument::new(&mut sink, &limits, &NEVER).unwrap();
        let before = document.writer.position();
        let result = document.begin_bilevel_image(BilevelImageSpec {
            pixel_width: 8,
            pixel_height: 1,
            row_stride: 1,
        });
        assert!(matches!(
            result,
            Err(Error {
                kind: ErrorKind::LimitExceeded {
                    resource: "allocation bytes",
                    attempted: DEFLATE_RESERVATION_BYTES,
                    ..
                },
                ..
            })
        ));
        assert_eq!(document.writer.position(), before);
        assert!(document.writer.ensure_idle().is_ok());
    };
}

#[test]
fn bilevel_compression_is_independent_of_row_and_output_chunk_boundaries() {
    let (visible, stride, height) = (8193, 8196, 7);
    let mut raw = vec![0; stride * height];
    let mut random = 0x12345678_u32;
    for byte in &mut raw {
        random ^= random << 13;
        random ^= random >> 17;
        random ^= random << 5;
        *byte = random as u8;
    }
    let expected: Vec<_> = raw
        .chunks(stride)
        .flat_map(|row| row[..visible].iter().copied())
        .collect();
    let mut reference = None;
    for (chunk, split) in [(1, 1), (7, 13), (16 * 1024, raw.len())] {
        let limits = Limits {
            io_chunk_bytes: chunk,
            ..Limits::default()
        };
        let mut sink = VecSink::default();
        {
            let mut document = PdfDocument::new(&mut sink, &limits, &NEVER).unwrap();
            let mut image = document
                .begin_bilevel_image(BilevelImageSpec {
                    pixel_width: 65537,
                    pixel_height: height as u32,
                    row_stride: stride,
                })
                .unwrap();
            assert!(image.zlib.encoded.len() <= DEFLATE_CHUNK_BYTES);
            for bytes in raw.chunks(split) {
                image.write_all(bytes).unwrap();
            }
            assert_eq!(image.zlib.encoder.total_in(), expected.len() as u64);
            let object = image.finish().unwrap();
            document.add_page(page(), &[object]).unwrap();
            document.finish().unwrap();
        };
        assert_eq!(
            crate::test_support::bilevel_pixels(&sink.bytes).as_slice(),
            std::slice::from_ref(&expected)
        );
        if let Some(bytes) = &reference {
            assert_eq!(&sink.bytes, bytes);
        } else {
            reference = Some(sink.bytes);
        }
    }
}

#[test]
fn bilevel_compression_failure_poisons_the_image_and_leaves_the_stream_open() {
    for mode in 0..2 {
        let limits = Limits::default();
        let mut sink = VecSink::default();
        {
            let mut document = PdfDocument::new(&mut sink, &limits, &NEVER).unwrap();
            let mut image = document
                .begin_bilevel_image(BilevelImageSpec {
                    pixel_width: 8,
                    pixel_height: 1,
                    row_stride: 1,
                })
                .unwrap();
            if mode == 0 {
                // A broken compressor/output-buffer contract must not spin.
                image.zlib.encoded.clear();
            } else {
                // Simulate a backend entering finalization before row submission.
                assert_eq!(
                    image
                        .zlib
                        .encoder
                        .compress(&[], &mut image.zlib.encoded[..1], FlushCompress::Finish)
                        .unwrap(),
                    Status::Ok
                );
            }
            let error = Error::from(image.write(&[0x80]).unwrap_err());
            let expected = if mode == 0 {
                "zlib compression made no progress"
            } else {
                "zlib compression failed"
            };
            assert!(
                matches!(error, Error { kind: ErrorKind::Malformed, reason, .. } if reason == expected)
            );
            assert!(image.failed);
            assert!(matches!(
                image.write(&[0x80]).map_err(Error::from),
                Err(Error {
                    kind: ErrorKind::Malformed,
                    reason: "bilevel image cannot continue after compression or output failure",
                    ..
                })
            ));
            assert!(image.finish().is_err());
            assert!(document.finish().is_err());
        };
    }
}

#[test]
fn bilevel_finish_observes_output_limits() {
    let limits = Limits {
        max_output_bytes: 4096,
        ..Limits::default()
    };
    let mut sink = VecSink::default();
    {
        let mut document = PdfDocument::new(&mut sink, &limits, &NEVER).unwrap();
        let mut image = document
            .begin_bilevel_image(BilevelImageSpec {
                pixel_width: 8,
                pixel_height: 1,
                row_stride: 1,
            })
            .unwrap();
        image.write_all(&[0]).unwrap();
        // The final zlib bytes must pass through the PDF output limit.
        image
            .document
            .writer
            .set_position_for_test(limits.max_output_bytes);
        assert!(matches!(
            image.finish(),
            Err(Error {
                kind: ErrorKind::LimitExceeded {
                    resource: "output bytes",
                    ..
                },
                ..
            })
        ));
        assert!(document.finish().is_err());
    };
}

#[test]
fn bilevel_finish_observes_cancellation_while_draining() {
    for allowed in 0.. {
        let limits = Limits {
            io_chunk_bytes: 1,
            ..Limits::default()
        };
        let mut sink = VecSink::default();
        let cancellation = CancelAfter::new(allowed);
        let result = (|| {
            let mut document = PdfDocument::new(&mut sink, &limits, &cancellation)?;
            let mut image = document.begin_bilevel_image(BilevelImageSpec {
                pixel_width: 8,
                pixel_height: 1,
                row_stride: 1,
            })?;
            image.write_all(&[0])?;
            Ok::<_, Error>(image.finish())
        })();
        match result {
            Ok(Err(Error {
                kind: ErrorKind::Cancelled,
                ..
            })) => return,
            Err(Error {
                kind: ErrorKind::Cancelled,
                ..
            }) => {}
            other => panic!("expected a cancellation checkpoint during finish: {other:?}"),
        }
    }
}