rusty_pdf_core 0.2.1

Pure-Rust PDF reader core: objects, classic and stream cross-reference tables, object streams, incremental updates, broken-xref repair, RC4 and AES-128/256 decryption, stream filters, page tree, content streams, editing and save. Hostile input errors or stays bounded. No C, no unsafe.
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
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
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
//! Image XObjects and inline images to samples.
//!
//! Everything here is bounded by the image's own declared size: the pixel
//! count is checked against [`ImageOptions::max_pixels`] before anything is
//! allocated, and decompression stops at the number of bytes those
//! dimensions justify.
//!
//! The result is samples in the image's own colour space. Colour management
//! (ICC, tint transforms) belongs to the renderer; [`Image::to_rgb8`] and
//! [`Image::to_gray8`] are the plain device conversions, which is what OCR
//! and thumbnails need.

use crate::document::Document;
use crate::error::{Error, Result};
use crate::filters::{self, Cap};
use crate::object::{Dictionary, Object, Stream};

/// Bounds and policy for decoding one image.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ImageOptions {
    /// Largest image decoded, in pixels. Default 100,000,000: a 600 ppi
    /// tabloid page with room to spare.
    pub max_pixels: usize,
    /// What to do when the data holds fewer samples than the dimensions
    /// need: `false` (the default) is an error; `true` fills the missing
    /// samples with zero, as viewers do.
    pub pad_short_data: bool,
}

impl Default for ImageOptions {
    fn default() -> Self {
        Self { max_pixels: 100_000_000, pad_short_data: false }
    }
}

impl ImageOptions {
    /// Default options with `max_pixels`.
    #[must_use]
    pub fn with_max_pixels(max_pixels: usize) -> Self {
        Self { max_pixels, ..Self::default() }
    }
}

/// What an image's samples mean.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ColorSpace {
    /// One component, 0 black to 255 white (DeviceGray, CalGray, a
    /// one-component ICC profile).
    Gray,
    /// Three components (DeviceRGB, CalRGB, a three-component ICC profile).
    Rgb,
    /// Four components, 0 no ink to 255 full ink (DeviceCMYK, a
    /// four-component ICC profile).
    Cmyk,
    /// One component: an index into `palette`, which holds one entry of
    /// `base` per index.
    Indexed {
        /// The colour space of the palette entries.
        base: Box<ColorSpace>,
        /// `base.components()` bytes per entry.
        palette: Vec<u8>,
    },
    /// A space this crate does not convert: Lab, Separation, DeviceN.
    Other {
        /// The colour-space family name.
        name: Vec<u8>,
        /// Components per sample.
        components: usize,
    },
}

impl ColorSpace {
    /// Components per sample.
    #[must_use]
    pub fn components(&self) -> usize {
        match self {
            Self::Gray | Self::Indexed { .. } => 1,
            Self::Rgb => 3,
            Self::Cmyk => 4,
            Self::Other { components, .. } => *components,
        }
    }
}

/// A decoded image.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Image {
    /// Width in pixels.
    pub width: u32,
    /// Height in pixels.
    pub height: u32,
    /// What the samples mean.
    pub color_space: ColorSpace,
    /// A stencil mask (`/ImageMask true`): one component, and the page is
    /// painted with the current colour **where the sample is 0**.
    pub stencil: bool,
    /// `width * height * color_space.components()` bytes, rows top to
    /// bottom, 8 bits per component whatever the file used, `/Decode`
    /// applied. For [`ColorSpace::Indexed`] the bytes are palette indexes.
    pub samples: Vec<u8>,
    /// An alpha channel carried inside the image data (JPEG 2000 with
    /// `/SMaskInData`), `width * height` bytes.
    pub alpha: Option<Vec<u8>>,
}

/// An image from [`Document::decode_image_lenient`], with what was decoded
/// around to produce it.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LenientImage {
    /// The image. Where damage was concealed, those samples are a stand-in
    /// (zero, or a codec's neutral value), not the picture.
    pub image: Image,
    /// One line per concealment, in the order found: data that ended early
    /// or could not be read, and what stands in for it. Empty when the
    /// image decoded whole, exactly as the strict decode would.
    pub concealed: Vec<String>,
    /// One line per kind of damage that was decoded through rather than
    /// filled: every pixel comes from the data, but the data was damaged, so
    /// some may be wrong (a JPEG with out-of-range coefficients, or one whose
    /// missing Huffman table was replaced by the standard one). The strict
    /// decode accepts these images too; this says what to distrust.
    pub damaged: Vec<String>,
}

impl LenientImage {
    /// Whether the image decoded whole, with nothing concealed. Damage
    /// decoded through ([`damaged`](Self::damaged)) does not count.
    #[must_use]
    pub fn is_complete(&self) -> bool {
        self.concealed.is_empty()
    }
}

/// What a lenient decode found: the lists behind [`LenientImage`].
#[derive(Default)]
struct Report {
    concealed: Vec<String>,
    damaged: Vec<String>,
}

fn image_error<T>(m: impl Into<String>) -> Result<T> {
    Err(Error::Image(m.into()))
}

fn cmyk_to_rgb(c: u8, m: u8, y: u8, k: u8) -> [u8; 3] {
    let k = 255 - u16::from(k);
    // (255 - x) * k / 255 is at most 255.
    [c, m, y].map(|v| ((255 - u16::from(v)) * k / 255) as u8)
}

fn luma(r: u8, g: u8, b: u8) -> u8 {
    // Rec. 601 weights in 1/256ths; the sum is at most 255 * 256.
    ((u32::from(r) * 77 + u32::from(g) * 150 + u32::from(b) * 29) >> 8) as u8
}

impl Image {
    /// The image as 8-bit RGB, by the device conversions (CMYK without a
    /// profile, palette looked up). Fails for [`ColorSpace::Other`].
    pub fn to_rgb8(&self) -> Result<Vec<u8>> {
        convert_rgb(&self.color_space, &self.samples)
    }

    /// The image as 8-bit gray. Fails for [`ColorSpace::Other`].
    pub fn to_gray8(&self) -> Result<Vec<u8>> {
        if self.color_space == ColorSpace::Gray {
            return Ok(self.samples.clone());
        }
        let rgb = self.to_rgb8()?;
        Ok(rgb.as_chunks::<3>().0.iter().map(|p| luma(p[0], p[1], p[2])).collect())
    }
}

fn convert_rgb(space: &ColorSpace, samples: &[u8]) -> Result<Vec<u8>> {
    match space {
        ColorSpace::Gray => Ok(samples.iter().flat_map(|g| [*g; 3]).collect()),
        ColorSpace::Rgb => Ok(samples.to_vec()),
        ColorSpace::Cmyk => Ok(samples
            .as_chunks::<4>().0.iter()
            .flat_map(|p| cmyk_to_rgb(p[0], p[1], p[2], p[3]))
            .collect()),
        ColorSpace::Indexed { base, palette } => {
            let n = base.components();
            let mut entries = Vec::with_capacity(samples.len() * n);
            for index in samples {
                let at = usize::from(*index) * n;
                match palette.get(at..at + n) {
                    Some(entry) => entries.extend_from_slice(entry),
                    // An index past the palette paints the first entry's
                    // black; viewers differ, none fail.
                    None => entries.extend(std::iter::repeat_n(0, n)),
                }
            }
            convert_rgb(base, &entries)
        }
        ColorSpace::Other { name, .. } => image_error(format!(
            "colour space {} needs a colour-managed conversion",
            String::from_utf8_lossy(name)
        )),
    }
}

/// A dictionary entry by its full name or its inline-image abbreviation.
fn entry<'a>(doc: &'a Document, dict: &'a Dictionary, long: &[u8], short: &[u8]) -> Result<&'a Object> {
    match doc.lookup(dict, long)? {
        Object::Null => doc.lookup(dict, short),
        o => Ok(o),
    }
}

fn dimension(doc: &Document, dict: &Dictionary, long: &'static [u8], short: &[u8]) -> Result<usize> {
    let name = String::from_utf8_lossy(long);
    let v = entry(doc, dict, long, short)?
        .as_i64()
        .map_err(|_| Error::Image(format!("missing /{name}")))?;
    usize::try_from(v)
        .ok()
        .filter(|v| *v > 0)
        .ok_or_else(|| Error::Image(format!("/{name} {v} is not a positive size")))
}

/// Resolve a colour-space object. `resources` supplies named colour spaces,
/// which inline images may use.
fn color_space(doc: &Document, object: &Object, resources: Option<&Dictionary>, depth: u8) -> Result<ColorSpace> {
    if depth > 4 {
        return image_error("colour spaces nested too deeply");
    }
    let object = doc.resolve(object)?;
    let by_name = |name: &[u8]| -> Result<ColorSpace> {
        match name {
            b"DeviceGray" | b"G" | b"CalGray" => Ok(ColorSpace::Gray),
            b"DeviceRGB" | b"RGB" | b"CalRGB" => Ok(ColorSpace::Rgb),
            b"DeviceCMYK" | b"CMYK" => Ok(ColorSpace::Cmyk),
            other => {
                let named = resources
                    .and_then(|r| doc.lookup_dict(r, b"ColorSpace"))
                    .and_then(|spaces| spaces.get(other));
                match named {
                    Some(o) => color_space(doc, o, None, depth + 1),
                    None => image_error(format!("unknown colour space {}", String::from_utf8_lossy(other))),
                }
            }
        }
    };
    let items = match object {
        Object::Name(n) => return by_name(n),
        Object::Array(a) => a,
        _ => return image_error("unrecognised colour space"),
    };
    let family = match items.first().map(|o| doc.resolve(o)).transpose()? {
        Some(Object::Name(n)) => n.as_slice(),
        _ => return image_error("unrecognised colour space"),
    };
    let arg = |i: usize| -> Result<&Object> {
        match items.get(i) {
            Some(o) => doc.resolve(o),
            None => image_error("colour space array is too short"),
        }
    };
    match family {
        b"ICCBased" => {
            // `/N` feeds the row-size arithmetic: only the sizes a profile
            // can have are accepted.
            let n = arg(1)?.as_dict().ok().and_then(|d| doc.lookup(d, b"N").ok()).and_then(|o| o.as_i64().ok());
            match n {
                Some(1) => Ok(ColorSpace::Gray),
                Some(3) | None => Ok(ColorSpace::Rgb),
                Some(4) => Ok(ColorSpace::Cmyk),
                Some(other) => image_error(format!("ICC colour space with {other} components")),
            }
        }
        b"Indexed" | b"I" => {
            let base = color_space(doc, arg(1)?, resources, depth + 1)?;
            if matches!(base, ColorSpace::Indexed { .. }) {
                return image_error("an Indexed colour space cannot be based on another");
            }
            let hival = arg(2)?.as_i64().ok().and_then(|v| usize::try_from(v).ok()).unwrap_or(255).min(255);
            let wanted = (hival + 1) * base.components();
            let mut palette = match arg(3)? {
                Object::String(s, _) => s.clone(),
                Object::Stream(s) => doc.decode_partial(s, Cap::clip(wanted))?.data.into_owned(),
                _ => return image_error("Indexed colour space has no lookup table"),
            };
            palette.truncate(wanted);
            Ok(ColorSpace::Indexed { base: Box::new(base), palette })
        }
        b"Separation" => Ok(ColorSpace::Other { name: family.to_vec(), components: 1 }),
        b"DeviceN" => {
            let n = arg(1)?.as_array().map(<[Object]>::len).unwrap_or(0);
            if (1..=32).contains(&n) {
                Ok(ColorSpace::Other { name: family.to_vec(), components: n })
            } else {
                image_error("DeviceN colour space with an unusable component count")
            }
        }
        b"Lab" => Ok(ColorSpace::Other { name: family.to_vec(), components: 3 }),
        b"Pattern" => image_error("an image cannot use a Pattern colour space"),
        other => by_name(other),
    }
}

/// Spread packed samples of `bits` each into one byte per sample.
/// `scale` stretches the value range to 0..=255 (not for palette indexes).
fn unpack(raw: &[u8], width: usize, height: usize, components: usize, bits: usize, scale: bool) -> Vec<u8> {
    let per_row = width * components;
    let row_bytes = (per_row * bits).div_ceil(8);
    let mut out = Vec::with_capacity(per_row * height);
    for row in raw.chunks(row_bytes).take(height) {
        match bits {
            8 => out.extend_from_slice(&row[..per_row.min(row.len())]),
            16 => out.extend(row.as_chunks::<2>().0.iter().take(per_row).map(|p| p[0])),
            1 => {
                // A whole input byte at a time: one table row of 8 samples.
                let table = if scale { &EXPAND_1BIT_SCALED } else { &EXPAND_1BIT_RAW };
                let full = per_row / 8;
                for &b in row.iter().take(full) {
                    out.extend_from_slice(&table[usize::from(b)]);
                }
                let rest = per_row % 8;
                if rest > 0 {
                    if let Some(&b) = row.get(full) {
                        out.extend_from_slice(&table[usize::from(b)][..rest]);
                    }
                }
            }
            _ => {
                let max = (1u16 << bits) - 1;
                for s in 0..per_row {
                    let bit = s * bits;
                    let Some(byte) = row.get(bit / 8) else { break };
                    let v = u16::from(byte >> (8 - bits - bit % 8)) & max;
                    // v <= max, so v * 255 / max <= 255.
                    out.push(if scale { (v * 255 / max) as u8 } else { v as u8 });
                }
            }
        }
        // A short final row is padded by the caller's length check.
    }
    out
}

/// The 8 samples of one byte of 1-bit data, most significant bit first,
/// with a set bit as `one`.
const fn expand_1bit(one: u8) -> [[u8; 8]; 256] {
    let mut table = [[0u8; 8]; 256];
    let mut b = 0;
    while b < 256 {
        let mut i = 0;
        while i < 8 {
            if (b >> (7 - i)) & 1 == 1 {
                table[b][i] = one;
            }
            i += 1;
        }
        b += 1;
    }
    table
}

/// 1-bit samples stretched to 0 / 255.
static EXPAND_1BIT_SCALED: [[u8; 8]; 256] = expand_1bit(255);
/// 1-bit samples kept as 0 / 1 (palette indexes).
static EXPAND_1BIT_RAW: [[u8; 8]; 256] = expand_1bit(1);

/// Apply a `/Decode` array to 8-bit samples.
fn apply_decode(samples: &mut [u8], decode: &[f64], components: usize) {
    if decode.len() < components * 2 {
        return;
    }
    let maps: Vec<Option<[u8; 256]>> = (0..components)
        .map(|c| {
            let (lo, hi) = (decode[c * 2], decode[c * 2 + 1]);
            // The default range needs no work.
            if (lo, hi) == (0.0, 1.0) || !lo.is_finite() || !hi.is_finite() {
                return None;
            }
            let mut table = [0u8; 256];
            for (v, slot) in table.iter_mut().enumerate() {
                // v is 0..=255.
                #[allow(clippy::cast_precision_loss)]
                let x = lo + (v as f64 / 255.0) * (hi - lo);
                // Clamped to 0..=255 before the cast.
                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                {
                    *slot = (x.clamp(0.0, 1.0) * 255.0).round() as u8;
                }
            }
            Some(table)
        })
        .collect();
    if maps.iter().all(Option::is_none) {
        return;
    }
    for pixel in samples.chunks_exact_mut(components) {
        for (sample, map) in pixel.iter_mut().zip(&maps) {
            if let Some(table) = map {
                *sample = table[usize::from(*sample)];
            }
        }
    }
}

impl Document {
    /// Decode an image XObject to samples.
    ///
    /// Handles raw, Flate, LZW and run-length samples at 1, 2, 4, 8 or 16
    /// bits, and the image codecs enabled by crate features: JPEG (`dct`),
    /// JPEG 2000 (`jpx`), JBIG2 (`jbig2`) and CCITT fax (`ccitt`).
    pub fn decode_image(&self, stream: &Stream, options: &ImageOptions) -> Result<Image> {
        self.decode_image_with(stream, None, options)
    }

    /// [`decode_image`](Self::decode_image) for an inline image, whose
    /// colour space may be a name defined in the page's `resources`.
    pub fn decode_image_with(
        &self,
        stream: &Stream,
        resources: Option<&Dictionary>,
        options: &ImageOptions,
    ) -> Result<Image> {
        self.decode_image_inner(stream, resources, options, None)
    }

    /// Decode an image, concealing damage instead of failing, and say what
    /// was concealed.
    ///
    /// Where the strict [`decode_image_with`](Self::decode_image_with)
    /// fails on damaged image data, this decodes what is there and lists the
    /// rest in [`LenientImage::concealed`]:
    /// - encoded data that ends early or turns to garbage part-way
    ///   (a truncated Flate layer, for one);
    /// - JPEG data cut short or damaged, filled or decoded out of step by
    ///   `rusty_jpeg`;
    /// - damaged or cut-off CCITT fax rows, repaired by `rusty_tiff` under the
    ///   filter's `EndOfLine` / `EndOfBlock` / `DamagedRowsBeforeError` rules;
    /// - JPEG 2000 tiles, tile-parts, packets or code-blocks that are missing
    ///   or unreadable, decoded around by `rusty_jpx`;
    /// - samples short of the image's size, filled with zero.
    ///
    /// An image the strict decode accepts comes back identical, with nothing
    /// concealed. Damage that leaves nothing to show (no header, the wrong
    /// size, an unsupported format) is still an error.
    pub fn decode_image_lenient(
        &self,
        stream: &Stream,
        resources: Option<&Dictionary>,
        options: &ImageOptions,
    ) -> Result<LenientImage> {
        let mut report = Report::default();
        let image = self.decode_image_inner(stream, resources, options, Some(&mut report))?;
        Ok(LenientImage { image, concealed: report.concealed, damaged: report.damaged })
    }

    /// The decode behind both entry points. `conceal` is `None` for the
    /// strict decode; with a report, damage is concealed and recorded in it.
    fn decode_image_inner(
        &self,
        stream: &Stream,
        resources: Option<&Dictionary>,
        options: &ImageOptions,
        mut conceal: Option<&mut Report>,
    ) -> Result<Image> {
        let dict = &stream.dict;
        let width = dimension(self, dict, b"Width", b"W")?;
        let height = dimension(self, dict, b"Height", b"H")?;
        let pixels = width
            .checked_mul(height)
            .filter(|p| *p <= options.max_pixels)
            .ok_or(Error::Limit { what: "image pixels", limit: options.max_pixels as u64 })?;
        let (Ok(w32), Ok(h32)) = (u32::try_from(width), u32::try_from(height)) else {
            return image_error("image dimensions out of range");
        };
        let stencil = entry(self, dict, b"ImageMask", b"IM")?.as_bool().unwrap_or(false);
        let declared_space = match entry(self, dict, b"ColorSpace", b"CS")? {
            _ if stencil => Some(ColorSpace::Gray),
            Object::Null => None,
            o => Some(color_space(self, o, resources, 0)?),
        };
        let decode: Vec<f64> = match entry(self, dict, b"Decode", b"D")? {
            Object::Array(a) => a.iter().filter_map(|o| self.resolve(o).ok()?.as_f64().ok()).collect(),
            _ => Vec::new(),
        };

        // Encoded image data cannot be justified exactly from the
        // dimensions. Eight bytes per pixel is beyond what any codec here
        // produces for an image worth decoding.
        let encoded_cap = pixels.saturating_mul(8).saturating_add(1 << 20).min(self.limits.max_stream_bytes);
        let has_codec = self.filter_chain(dict)?.iter().any(|(name, _)| filters::is_image_filter(name));

        let (space, mut samples, alpha) = if has_codec {
            let partial = self.decode_partial(stream, Cap::strict(encoded_cap))?;
            let Some((codec, parms)) = partial.image else {
                return image_error("image codec is not the last filter");
            };
            if !partial.complete {
                match conceal.as_deref_mut() {
                    Some(r) => r.concealed.push("the filters before the image codec stopped early: the codec gets the data decoded up to that point".into()),
                    None => return image_error("encoded image data is damaged"),
                }
            }
            let geometry = Geometry { width, height, pixels };
            match filters::canonical_name(codec) {
                b"DCTDecode" => {
                    self.decode_dct(&partial.data, parms.as_deref(), declared_space, geometry, conceal.as_deref_mut())?
                }
                b"JPXDecode" => {
                    self.decode_jpx(&partial.data, dict, declared_space, geometry, conceal.as_deref_mut())?
                }
                bilevel => {
                    let packed = if bilevel == b"CCITTFaxDecode" {
                        decode_ccitt(&partial.data, parms.as_deref(), geometry, conceal.as_deref_mut())?
                    } else {
                        self.decode_jbig2(&partial.data, parms.as_deref(), geometry)?
                    };
                    let space = declared_space.unwrap_or(ColorSpace::Gray);
                    if space.components() != 1 {
                        return image_error("a bi-level image needs a one-component colour space");
                    }
                    let scale = !matches!(space, ColorSpace::Indexed { .. });
                    (space, unpack(&packed, width, height, 1, 1, scale), None)
                }
            }
        } else {
            let Some(space) = declared_space else {
                return image_error("missing /ColorSpace");
            };
            let bits = if stencil {
                1
            } else {
                match entry(self, dict, b"BitsPerComponent", b"BPC")?.as_i64() {
                    Ok(b @ (1 | 2 | 4 | 8 | 16)) => usize::try_from(b).unwrap_or(8),
                    Ok(other) => return image_error(format!("{other} bits per component is not supported")),
                    Err(_) => return image_error("missing /BitsPerComponent"),
                }
            };
            let components = space.components();
            let expected = width
                .checked_mul(components)
                .and_then(|v| v.checked_mul(bits))
                .map(|row_bits| row_bits.div_ceil(8))
                .and_then(|row| row.checked_mul(height))
                .ok_or_else(|| Error::Image("image size overflows".into()))?;
            let partial = self.decode_partial(stream, Cap::clip(expected))?;
            if partial.data.len() < expected && !options.pad_short_data {
                let message = format!("{} bytes of samples, {expected} needed", partial.data.len());
                match conceal.as_deref_mut() {
                    Some(r) => r.concealed.push(format!("{message}: the rest are zero")),
                    None => return image_error(message),
                }
            }
            let samples = if bits == 8 {
                // 8-bit rows are already one byte per sample with no row
                // padding: the decoded buffer IS the samples, no copy.
                let mut data = partial.data.into_owned();
                data.truncate(expected);
                data
            } else {
                let scale = !matches!(space, ColorSpace::Indexed { .. });
                unpack(&partial.data, width, height, components, bits, scale)
            };
            (space, samples, None)
        };

        let components = space.components();
        let wanted = pixels
            .checked_mul(components)
            .ok_or_else(|| Error::Image("image size overflows".into()))?;
        if samples.len() < wanted && !options.pad_short_data {
            let message = format!("{} samples decoded, {wanted} needed", samples.len());
            match conceal {
                // The raw path already recorded its shortfall above.
                Some(_) if !has_codec => {}
                Some(r) => r.concealed.push(format!("{message}: the rest are zero")),
                None => return image_error(message),
            }
        }
        samples.resize(wanted, 0);
        if !matches!(space, ColorSpace::Indexed { .. }) {
            apply_decode(&mut samples, &decode, components);
        }
        Ok(Image { width: w32, height: h32, color_space: space, stencil, samples, alpha })
    }

    #[cfg(feature = "dct")]
    fn decode_dct(
        &self,
        data: &[u8],
        parms: Option<&Dictionary>,
        declared: Option<ColorSpace>,
        g: Geometry,
        mut conceal: Option<&mut Report>,
    ) -> Result<Decoded> {
        use rusty_jpeg::decode::WarningClass;
        use rusty_jpeg::{ColorTransform, Decoder, PixelFormat};
        let fail = |e: &dyn std::fmt::Display| Error::Image(format!("JPEG: {e}"));
        let mut decoder = Decoder::new(data);
        // rusty_jpeg recovers damaged data and classes each repair. Its own
        // strict mode refuses every repair, a missing end marker or stray
        // padding bytes included, which would refuse images whose every pixel
        // decoded. So it always recovers here, and the class decides:
        // `Concealed` (pixels are a stand-in) is refused by the strict decode
        // and listed by the lenient one; `Damaged` (decoded through bad data)
        // is accepted and listed as damage; `Harmless` is neither.
        decoder.set_max_decoding_buffer_size(g.pixels.saturating_mul(8).saturating_add(1 << 16));
        decoder.read_info().map_err(|e| fail(&e))?;
        let header = decoder.frame_header().ok_or_else(|| Error::Image("JPEG has no frame".into()))?;
        if (usize::from(header.width), usize::from(header.height)) != (g.width, g.height) {
            return image_error("JPEG dimensions disagree with /Width and /Height");
        }
        // `/ColorTransform` overrides what the file's markers say.
        let transform = parms.and_then(|p| p.get_i64(b"ColorTransform"));
        match (header.components, transform) {
            (3, Some(0)) => decoder.set_color_transform(ColorTransform::None),
            (3, Some(_)) => decoder.set_color_transform(ColorTransform::YCbCr),
            (4, Some(0)) => decoder.set_color_transform(ColorTransform::CMYK),
            (4, Some(_)) => decoder.set_color_transform(ColorTransform::YCCK),
            _ => {}
        }
        let mut pixels = decoder.decode().map_err(|e| fail(&e))?;
        for w in decoder.warnings() {
            match (w.class(), conceal.as_deref_mut()) {
                (WarningClass::Harmless, _) => {}
                (WarningClass::Damaged, Some(r)) => r.damaged.push(jpeg_concealment(w)),
                (WarningClass::Damaged, None) => {}
                (_, Some(r)) => r.concealed.push(jpeg_concealment(w)),
                // `Concealed`, or a class added later: some pixels are not
                // from the data.
                (_, None) => return image_error(format!("damaged image data ({})", jpeg_concealment(w))),
            }
        }
        let info = decoder.info().ok_or_else(|| Error::Image("JPEG pixel format is not supported".into()))?;
        let space = match info.pixel_format {
            PixelFormat::L8 => ColorSpace::Gray,
            PixelFormat::L16 => {
                // Big-endian 16-bit samples: keep the high byte.
                pixels = pixels.as_chunks::<2>().0.iter().map(|p| p[0]).collect();
                ColorSpace::Gray
            }
            PixelFormat::RGB24 => ColorSpace::Rgb,
            PixelFormat::CMYK32 => {
                // The decoder returns 255 minus the stored value for
                // four-component files. The filter's output is the stored
                // value; a file that stores inverted inks says so with
                // `/Decode [1 0 1 0 1 0 1 0]`.
                for v in &mut pixels {
                    *v = 255 - *v;
                }
                ColorSpace::Cmyk
            }
        };
        let space = match declared {
            Some(d) if d.components() == space.components() => d,
            Some(_) => return image_error("JPEG component count disagrees with /ColorSpace"),
            None => space,
        };
        Ok((space, pixels, None))
    }

    #[cfg(feature = "jpx")]
    fn decode_jpx(
        &self,
        data: &[u8],
        dict: &Dictionary,
        declared: Option<ColorSpace>,
        g: Geometry,
        conceal: Option<&mut Report>,
    ) -> Result<Decoded> {
        let fail = |e: &dyn std::fmt::Display| Error::Image(format!("JPEG 2000: {e}"));
        // A palette inside the JPEG 2000 data is expanded, unless the PDF
        // declares an /Indexed space: then the samples are indexes into the
        // PDF's own palette, which takes precedence (ISO 32000-1, 7.4.9).
        let indexed = matches!(declared, Some(ColorSpace::Indexed { .. }));
        let mut options = rusty_jpx::DecodeOptions::new()
            .with_apply_palette(!indexed)
            .with_allow_truncated(conceal.is_some());
        // Up to four colour channels and one of opacity.
        options.limits.max_samples = (g.pixels as u64).saturating_mul(5);
        let image = rusty_jpx::decode_jpx_with(data, &options).map_err(|e| fail(&e))?;
        if let Some(r) = conceal {
            r.concealed.extend(image.concealed.iter().map(jpx_concealment));
        }
        if (image.width as usize, image.height as usize) != (g.width, g.height) {
            return image_error("JPEG 2000 dimensions disagree with /Width and /Height");
        }
        // One component as 8-bit samples at full size. Palette indexes are
        // kept as they are; everything else is stretched to 0..=255.
        let plane = |index: usize, scale: bool| -> Result<Vec<u8>> {
            let c = &image.components[index];
            let data = image
                .upsampled(index)
                .ok_or_else(|| Error::Image("JPEG 2000 component has no samples".into()))?;
            Ok(data.iter().map(|v| jpx_sample(*v, c.bits, c.signed, scale)).collect())
        };
        let color: Vec<usize> = (0..image.components.len())
            .filter(|i| image.components[*i].role == rusty_jpx::ChannelRole::Color)
            .collect();
        let color = if color.is_empty() { (0..image.components.len()).collect() } else { color };
        let space = match (declared, color.len()) {
            (Some(d), n) if d.components() <= n => d,
            (Some(_), _) => return image_error("JPEG 2000 has fewer components than /ColorSpace needs"),
            (None, 1) => ColorSpace::Gray,
            (None, 3) => ColorSpace::Rgb,
            (None, 4) => ColorSpace::Cmyk,
            (None, n) => return image_error(format!("JPEG 2000 with {n} colour components and no /ColorSpace")),
        };
        let n = space.components();
        let scale = !matches!(space, ColorSpace::Indexed { .. });
        // Each component straight into its interleaved slots: one buffer,
        // no per-plane staging.
        let mut samples = vec![0u8; g.pixels * n];
        for (k, index) in color.iter().take(n).enumerate() {
            let c = &image.components[*index];
            let data = image
                .upsampled(*index)
                .ok_or_else(|| Error::Image("JPEG 2000 component has no samples".into()))?;
            for (slot, v) in samples.iter_mut().skip(k).step_by(n).zip(data.iter()) {
                *slot = jpx_sample(*v, c.bits, c.signed, scale);
            }
        }
        let wants_alpha = self.lookup(dict, b"SMaskInData")?.as_i64().unwrap_or(0) != 0;
        let alpha = if wants_alpha {
            let opacity = (0..image.components.len()).find(|i| {
                matches!(
                    image.components[*i].role,
                    rusty_jpx::ChannelRole::Opacity | rusty_jpx::ChannelRole::PremultipliedOpacity
                )
            });
            opacity.map(|i| plane(i, true)).transpose()?
        } else {
            None
        };
        Ok((space, samples, alpha))
    }

    #[cfg(feature = "jbig2")]
    fn decode_jbig2(&self, data: &[u8], parms: Option<&Dictionary>, g: Geometry) -> Result<Vec<u8>> {
        let globals = match parms.and_then(|p| p.get(b"JBIG2Globals")) {
            Some(o) => match self.resolve(o)? {
                Object::Stream(s) => Some(self.decode_stream(s, self.limits.max_stream_bytes.min(64 << 20))?),
                _ => None,
            },
            None => None,
        };
        // rusty_jbig2 counts a bitmap's pixels with its rows rounded up to
        // whole bytes, so the page's own budget is rounded the same way.
        // Symbols and regions are never larger than the page they build.
        let page_pixels = (g.width.div_ceil(8) as u64 * 8).saturating_mul(g.height as u64);
        let limits = rusty_jbig2::Limits::default().with_max_pixels(page_pixels.max(1 << 16));
        let options = rusty_jbig2::DecodeOptions::new().with_limits(limits);
        let bitmap = rusty_jbig2::decode_jbig2_with(data, globals.as_deref(), &options)
            .map_err(|e| Error::Image(format!("JBIG2: {e}")))?;
        if (bitmap.width as usize, bitmap.height as usize) != (g.width, g.height) {
            return image_error("JBIG2 dimensions disagree with /Width and /Height");
        }
        Ok(bitmap.into_pdf_samples())
    }

    #[cfg(not(feature = "dct"))]
    fn decode_dct(
        &self,
        _: &[u8],
        _: Option<&Dictionary>,
        _: Option<ColorSpace>,
        _: Geometry,
        _: Option<&mut Report>,
    ) -> Result<Decoded> {
        Err(Error::UnsupportedFilter("DCTDecode (the `dct` feature is off)".into()))
    }

    #[cfg(not(feature = "jpx"))]
    fn decode_jpx(
        &self,
        _: &[u8],
        _: &Dictionary,
        _: Option<ColorSpace>,
        _: Geometry,
        _: Option<&mut Report>,
    ) -> Result<Decoded> {
        Err(Error::UnsupportedFilter("JPXDecode (the `jpx` feature is off)".into()))
    }

    #[cfg(not(feature = "jbig2"))]
    fn decode_jbig2(&self, _: &[u8], _: Option<&Dictionary>, _: Geometry) -> Result<Vec<u8>> {
        Err(Error::UnsupportedFilter("JBIG2Decode (the `jbig2` feature is off)".into()))
    }
}

/// One line for a repair `rusty_jpeg` reported while recovering.
#[cfg(feature = "dct")]
fn jpeg_concealment(w: &rusty_jpeg::decode::Warning) -> String {
    use rusty_jpeg::decode::Warning as W;
    let what = match w {
        W::Truncated => "the data ends before the end-of-image marker: what was not reached is grey",
        W::SegmentEndedEarly => "a scan segment ran out of data: the rest of it is grey (or earlier scans' values)",
        W::BadHuffmanCode => "a bad Huffman code: decoding continued out of step until the next restart marker",
        W::RestartMarkerMismatch => "a restart marker was out of sequence: decoding resynchronised",
        W::ExtraneousBytes => "stray bytes between segments were skipped",
        W::MissingScan => "a component has no scan data: its plane is mid-grey",
        W::BadArithmeticCode => "a bad arithmetic code: the rest of that segment is not decoded",
        W::InvalidScanParameters => "a sequential scan had invalid SOS parameters: decoded as if they were valid",
        W::UnknownMarker => "an unknown marker segment (most likely a damaged byte) was skipped",
        W::InvalidCoefficient => "the coded data holds values no valid stream can: decoded as read",
        W::DefaultHuffmanTable => "a Huffman table was missing: the standard Annex K table stands in",
        W::MissingEoi => "only the end-of-image marker is missing: every pixel decoded",
        // `Warning` is non-exhaustive: a new kind is still reported.
        other => return format!("JPEG damage repaired ({other:?})"),
    };
    format!("JPEG: {what}")
}

/// One line for a concealment `rusty_jpx` reported.
#[cfg(feature = "jpx")]
fn jpx_concealment(c: &rusty_jpx::Concealment) -> String {
    use rusty_jpx::ConcealmentKind as K;
    let what = match c.kind {
        K::TileMissing => "has no data: it is the DC level (mid-grey)".to_string(),
        K::TilePartSkipped(why) => format!("lost a tile-part ({why}): it was skipped"),
        K::PacketsMissing(why) => format!("stops early ({why}): the missing coding passes are zero"),
        K::CodeBlocksCut => "has code-blocks cut short: decoded as far as they go".to_string(),
        K::TileUnreadable(why) => format!("is unreadable ({why}): it is the DC level (mid-grey)"),
        // `ConcealmentKind` is non-exhaustive: a new kind is still reported.
        other => format!("was concealed ({other:?})"),
    };
    match c.tile {
        Some(t) => format!("JPEG 2000 tile {t} {what}"),
        None => format!("JPEG 2000 data {what}"),
    }
}

/// One JPEG 2000 sample as a byte: stretched from its bit depth to
/// 0..=255, or, for a palette index (`scale == false`), kept as the index.
#[cfg_attr(not(feature = "jpx"), allow(dead_code))]
fn jpx_sample(v: i32, bits: u8, signed: bool, scale: bool) -> u8 {
    let bits = u32::from(bits.clamp(1, 31));
    let offset = if signed { 1i64 << (bits - 1) } else { 0 };
    let max = (1i64 << bits) - 1;
    let v = (i64::from(v) + offset).clamp(0, max);
    if scale {
        // v <= max, so the quotient is at most 255.
        (v * 255 / max) as u8
    } else {
        u8::try_from(v).unwrap_or(u8::MAX)
    }
}

/// Colour space, samples, alpha.
type Decoded = (ColorSpace, Vec<u8>, Option<Vec<u8>>);

/// What an image codec's output must match. Read only by the codecs, so a
/// build with every codec feature off never reads it.
#[derive(Debug, Clone, Copy)]
#[cfg_attr(not(any(feature = "dct", feature = "jpx", feature = "jbig2", feature = "ccitt")), allow(dead_code))]
struct Geometry {
    width: usize,
    height: usize,
    /// Read by the JPEG and JPEG 2000 decoders only.
    #[cfg_attr(not(any(feature = "dct", feature = "jpx")), allow(dead_code))]
    pixels: usize,
}

/// Widest CCITT row accepted: far past a 600 ppi tabloid page. `/Columns`
/// sizes the decoder's line buffers, so it must be a plausible row width,
/// not whatever the file says.
const MAX_CCITT_COLUMNS: usize = 100_000;

/// CCITT fax data to packed 1-bit rows of `width` pixels, as the filter
/// outputs them (0 is black unless `/BlackIs1`).
///
/// With a report (the lenient decode), damaged data is decoded as libtiff
/// decodes it and each stand-in row is recorded; without one it is an error.
#[cfg(feature = "ccitt")]
fn decode_ccitt(data: &[u8], parms: Option<&Dictionary>, g: Geometry, conceal: Option<&mut Report>) -> Result<Vec<u8>> {
    use rusty_tiff::ccitt::{self, Coding, FilterOptions, Options, Recovery, WarningKind};
    let int = |key: &[u8]| parms.and_then(|p| p.get_i64(key));
    let flag = |key: &[u8]| parms.and_then(|p| p.get_bool(key)).unwrap_or(false);
    let k = int(b"K").unwrap_or(0);
    let columns = match int(b"Columns") {
        None => 1728,
        Some(c) => usize::try_from(c)
            .ok()
            .filter(|c| (1..=MAX_CCITT_COLUMNS).contains(c))
            .ok_or_else(|| Error::Image(format!("CCITT /Columns {c} out of range")))?,
    };
    let coding = match k {
        k if k < 0 => Coding::Group4,
        0 => Coding::Group3_1D,
        _ => Coding::Group3_2D,
    };
    let (Ok(columns32), Ok(rows32)) = (u32::try_from(columns), u32::try_from(g.height)) else {
        return image_error("CCITT dimensions out of range");
    };
    let stride = columns.div_ceil(8);
    let mut options = Options::new(coding, columns32).with_rows(rows32);
    options.encoded_byte_align = flag(b"EncodedByteAlign");
    options.black_is_1 = flag(b"BlackIs1");
    options.max_output_bytes = stride.saturating_mul(g.height).saturating_add(stride);
    let fail = |e: ccitt::CcittError| Error::Image(format!("CCITT: {e}"));
    let rows = match conceal {
        None => ccitt::decode(data, &options).map_err(fail)?,
        Some(report) => {
            // The PDF filter's own rules (`EndOfLine`, `EndOfBlock`,
            // `DamagedRowsBeforeError`), not `decode_with`'s TIFF ones: those
            // re-decode an intact `/EndOfBlock false` stream as libtiff would
            // and report every row damaged.
            let mut filter = FilterOptions::new(options.clone())
                .with_end_of_line(flag(b"EndOfLine"))
                .with_end_of_block(parms.and_then(|p| p.get_bool(b"EndOfBlock")).unwrap_or(true))
                .with_damaged_rows_before_error(
                    int(b"DamagedRowsBeforeError").and_then(|n| u32::try_from(n).ok()).unwrap_or(0),
                )
                .with_recovery(Recovery::Lenient);
            if let Ok(k) = u32::try_from(k) {
                filter.options.k = k;
            }
            let decoding = ccitt::decode_filter(data, &filter).map_err(fail)?;
            for w in &decoding.warnings {
                let line = match w.kind {
                    // Every row decoded; only the EOL framing was missing.
                    WarningKind::MissingEndOfLine => continue,
                    WarningKind::Truncated => {
                        format!("CCITT fax data stops in row {} ({}): the rest is white", w.row, w.message)
                    }
                    WarningKind::ConcealedRow => format!(
                        "CCITT fax row {} is damaged ({}): repaired, and 2-D rows after it up to the next 1-D row may be wrong",
                        w.row, w.message
                    ),
                    // `WarningKind` is non-exhaustive: a new kind is still reported.
                    _ => format!("CCITT fax row {}: {}", w.row, w.message),
                };
                report.concealed.push(line);
            }
            decoding.data
        }
    };
    let out_stride = g.width.div_ceil(8);
    if stride == out_stride {
        return Ok(rows);
    }
    // `/Columns` differs from `/Width`: each row is cut or padded with white.
    let white = if options.black_is_1 { 0x00 } else { 0xFF };
    let mut out = Vec::with_capacity(out_stride * g.height);
    for row in rows.chunks(stride).take(g.height) {
        let keep = row.len().min(out_stride);
        out.extend_from_slice(&row[..keep]);
        out.extend(std::iter::repeat_n(white, out_stride - keep));
    }
    Ok(out)
}

#[cfg(not(feature = "ccitt"))]
fn decode_ccitt(_: &[u8], _: Option<&Dictionary>, _: Geometry, _: Option<&mut Report>) -> Result<Vec<u8>> {
    let _ = MAX_CCITT_COLUMNS;
    Err(Error::UnsupportedFilter("CCITTFaxDecode (the `ccitt` feature is off)".into()))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unpack_scales_small_samples() {
        // 2 bits per sample: 0, 1, 2, 3 -> 0, 85, 170, 255.
        assert_eq!(unpack(&[0b0001_1011], 4, 1, 1, 2, true), [0, 85, 170, 255]);
        assert_eq!(unpack(&[0b0001_1011], 4, 1, 1, 2, false), [0, 1, 2, 3]);
        assert_eq!(unpack(&[0b1010_0000], 3, 1, 1, 1, true), [255, 0, 255]);
        assert_eq!(unpack(&[0x12, 0x34, 0xAB, 0xCD], 2, 1, 1, 16, true), [0x12, 0xAB]);
        // Rows are byte aligned.
        assert_eq!(unpack(&[0b1000_0000, 0b0100_0000], 2, 2, 1, 1, true), [255, 0, 0, 255]);
        // The 1-bit table path against a bit-by-bit oracle: widths that are
        // and are not whole bytes, both scalings, and short final rows.
        let data: Vec<u8> = (0..97u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 24) as u8).collect();
        for width in [1usize, 7, 8, 9, 15, 16, 17, 33] {
            for scale in [true, false] {
                let height = 5;
                let row_bytes = width.div_ceil(8);
                for take in [row_bytes * height, row_bytes * height - 1, row_bytes * 2 + 1] {
                    let input = &data[..take.min(data.len())];
                    let mut oracle = Vec::new();
                    for row in input.chunks(row_bytes).take(height) {
                        for x in 0..width {
                            let Some(byte) = row.get(x / 8) else { break };
                            let bit = (byte >> (7 - x % 8)) & 1;
                            oracle.push(if scale { bit * 255 } else { bit });
                        }
                    }
                    assert_eq!(unpack(input, width, height, 1, 1, scale), oracle, "width {width} scale {scale} take {take}");
                }
            }
        }
    }

    #[test]
    fn jpx_samples_keep_palette_indexes() {
        // A 4-bit index stays an index; a 4-bit level is stretched.
        assert_eq!(jpx_sample(3, 4, false, false), 3);
        assert_eq!(jpx_sample(3, 4, false, true), 51);
        assert_eq!(jpx_sample(15, 4, false, true), 255);
        // Signed samples are offset to unsigned first.
        assert_eq!(jpx_sample(-128, 8, true, true), 0);
        assert_eq!(jpx_sample(127, 8, true, true), 255);
        // An index past 255 cannot be represented and saturates.
        assert_eq!(jpx_sample(4000, 12, false, false), 255);
    }

    #[test]
    fn decode_arrays() {
        let mut s = [0, 100, 255];
        apply_decode(&mut s, &[1.0, 0.0], 1);
        assert_eq!(s, [255, 155, 0]);
        let mut s = [10, 20, 30];
        apply_decode(&mut s, &[0.0, 1.0, 1.0, 0.0, 0.0, 1.0], 3);
        assert_eq!(s, [10, 235, 30]);
    }

    #[test]
    fn device_conversions() {
        assert_eq!(cmyk_to_rgb(0, 0, 0, 0), [255, 255, 255]);
        assert_eq!(cmyk_to_rgb(0, 0, 0, 255), [0, 0, 0]);
        assert_eq!(cmyk_to_rgb(255, 0, 0, 0), [0, 255, 255]);
        assert_eq!(luma(255, 255, 255), 255);
        assert_eq!(luma(0, 0, 0), 0);
        let indexed = ColorSpace::Indexed { base: Box::new(ColorSpace::Rgb), palette: vec![1, 2, 3, 4, 5, 6] };
        assert_eq!(convert_rgb(&indexed, &[1, 0, 9]).unwrap(), [4, 5, 6, 1, 2, 3, 0, 0, 0]);
    }
}