From 5628ad359d8f5bf9778f53edba9b9989b4b61d09 Mon Sep 17 00:00:00 2001 From: el-j Date: Sun, 15 Nov 2026 11:49:53 +0100 Subject: [PATCH 1/5] craft-image-codecs: Sun Raster image reader and writer Adds Format::SunRaster: 1-, 8- (gray or colour-mapped), 24- and 32-bit files, uncompressed or byte-encoded (RLE) on read, uncompressed on write. Closes #1560 --- crates/image-codecs/README.md | 1 + crates/image-codecs/src/codecs.rs | 1 + crates/image-codecs/src/codecs/sunraster.rs | 237 ++++++++++++++++++++ crates/image-codecs/src/format.rs | 12 +- crates/image-codecs/src/lib.rs | 4 +- crates/image-codecs/tests/it/detect_caps.rs | 14 ++ 6 files changed, 267 insertions(+), 2 deletions(-) create mode 100644 crates/image-codecs/src/codecs/sunraster.rs diff --git a/crates/image-codecs/README.md b/crates/image-codecs/README.md index 6e9e11617..f9f5f53e6 100644 --- a/crates/image-codecs/README.md +++ b/crates/image-codecs/README.md @@ -56,6 +56,7 @@ craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "< | Cineon | yes | yes | U16 (10-bit code values read and written exactly through U16) | Gray, RGB | no | no | no | no | no | no | no | built in | | DICOM | yes | **no** | U8, U16 | Gray, RGB | no | no | no | no | no | no | n/a | built in | | Amiga IFF (ILBM/PBM) | yes | yes (24-bit ILBM) | U8 | RGB, RGBA | yes (1-bit mask plane on write) | no | no | no | no | no | no | built in | +| Sun Raster (`.ras`) | yes (incl. RLE and colour maps) | yes (uncompressed) | U8 | Gray, Gray+A, RGB, RGBA | yes | no | no | no | no | no | no | built in | | AVIF | **no** | only with feature `avif` | U8 | RGB, RGBA | yes | no | no | no | no | no | yes | `image` + `ravif` | | HEIF/HEIC | with feature `heif` | **no** | U8, U16 (10/12-bit decodes to U16) | RGB, RGBA | yes (auxiliary alpha) | yes (`colr` prof) | yes | yes | no | no | n/a | `heic-rs` | diff --git a/crates/image-codecs/src/codecs.rs b/crates/image-codecs/src/codecs.rs index 0288ae22b..aecf95bbd 100644 --- a/crates/image-codecs/src/codecs.rs +++ b/crates/image-codecs/src/codecs.rs @@ -17,6 +17,7 @@ pub(crate) mod jxl; pub(crate) mod pcx; pub(crate) mod png; pub(crate) mod pnm; +pub(crate) mod sunraster; pub(crate) mod tga; pub(crate) mod tiff; pub(crate) mod tiff_exif; diff --git a/crates/image-codecs/src/codecs/sunraster.rs b/crates/image-codecs/src/codecs/sunraster.rs new file mode 100644 index 000000000..84d60f145 --- /dev/null +++ b/crates/image-codecs/src/codecs/sunraster.rs @@ -0,0 +1,237 @@ +//! Sun Raster files (`.ras`, `.sun`): 1-bit, 8-bit (gray or colour-mapped), 24-bit RGB and 32-bit +//! RGBA, uncompressed or byte-encoded (RLE) on read; uncompressed on write. +//! +//! Follows the published rasterfile format: a 32-byte big-endian header, an optional colour map, +//! then rows padded to an even number of bytes. In the "standard" type (1) 24- and 32-bit pixels +//! are stored blue-first; in the "RGB" type (3) red-first. Other types (TIFF, IFF, experimental) +//! are reported as unsupported. + +use crate::error::CodecError; +use crate::fidelity::Plan; +use crate::format::Format; +use crate::image::{ChannelLayout, Image, SampleType}; +use crate::options::Limits; + +const F: Format = Format::SunRaster; +const HEADER: usize = 32; +const MAGIC: u32 = 0x59a6_6a95; + +fn bad(reason: impl std::fmt::Display) -> CodecError { + CodecError::malformed(F, reason) +} + +fn be32(b: &[u8], i: usize) -> u32 { + u32::from_be_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]) +} + +/// Whether `b` starts with a Sun rasterfile header. +pub(crate) fn looks_like_sunraster(b: &[u8]) -> bool { + b.len() >= HEADER && be32(b, 0) == MAGIC && matches!(be32(b, 12), 1 | 8 | 24 | 32) +} + +/// Expand byte-encoded data (`0x80` escapes a run) until `want` bytes are produced. +fn unrle(src: &[u8], want: usize) -> Result, CodecError> { + let mut out = Vec::new(); + out.try_reserve_exact(want).map_err(|_| bad("pixel buffer is too large"))?; + let mut i = 0; + while out.len() < want { + let b = *src.get(i).ok_or_else(|| bad("truncated RLE data"))?; + i += 1; + if b != 0x80 { + out.push(b); + continue; + } + let n = *src.get(i).ok_or_else(|| bad("truncated RLE data"))?; + i += 1; + if n == 0 { + out.push(0x80); + continue; + } + let v = *src.get(i).ok_or_else(|| bad("truncated RLE data"))?; + i += 1; + let count = usize::from(n) + 1; + if count > want - out.len() { + return Err(bad("RLE run passes the end of the image")); + } + out.resize(out.len() + count, v); + } + Ok(out) +} + +pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result { + if !looks_like_sunraster(b) { + return Err(bad("invalid Sun raster header")); + } + let (w, h, depth, kind, map_type, map_len) = (be32(b, 4), be32(b, 8), be32(b, 12) as usize, be32(b, 20), be32(b, 24), be32(b, 28) as usize); + if !matches!(kind, 0..=3) { + return Err(CodecError::unsupported(F, format!("Sun raster type {kind} is not supported"))); + } + if map_type > 2 { + return Err(CodecError::unsupported(F, format!("Sun raster map type {map_type} is not supported"))); + } + let layout = match depth { + 1 | 8 if map_type != 1 => ChannelLayout::Gray, + 1 | 8 | 24 => ChannelLayout::Rgb, + _ => ChannelLayout::Rgba, + }; + limits.check(w, h, layout, SampleType::U8)?; + let (wu, hu) = (w as usize, h as usize); + let stride = wu.checked_mul(depth).and_then(|n| n.checked_add(15)).ok_or_else(|| bad("image size overflow"))? / 16 * 2; + let want = stride.checked_mul(hu).ok_or_else(|| bad("image size overflow"))?; + let data_at = HEADER.checked_add(map_len).ok_or_else(|| bad("colour map size overflow"))?; + let map = b.get(HEADER..data_at).ok_or_else(|| bad("truncated colour map"))?; + let rest = &b[data_at..]; + let raw; + let rows: &[u8] = if kind == 2 { + raw = unrle(rest, want)?; + &raw + } else { + rest.get(..want).ok_or_else(|| bad("the file is too short for the declared image"))? + }; + let channels = layout.channels(); + let mut out = Vec::new(); + out.try_reserve_exact(wu * hu * channels).map_err(|_| bad("pixel buffer is too large"))?; + let entries = map_len / 3; + for y in 0..hu { + let row = &rows[y * stride..(y + 1) * stride]; + for x in 0..wu { + match depth { + 1 => { + // A set bit is black. + let bit = (row[x / 8] >> (7 - x % 8)) & 1; + out.push(if bit == 1 { 0 } else { 255 }); + } + 8 if map_type == 1 => { + let i = usize::from(row[x]); + if i >= entries { + return Err(bad("pixel index is outside the colour map")); + } + out.extend_from_slice(&[map[i], map[entries + i], map[2 * entries + i]]); + } + 8 => out.push(row[x]), + 24 => { + let p = &row[3 * x..3 * x + 3]; + out.extend_from_slice(&if kind == 3 { [p[0], p[1], p[2]] } else { [p[2], p[1], p[0]] }); + } + _ => { + let p = &row[4 * x..4 * x + 4]; + out.extend_from_slice(&if kind == 3 { [p[1], p[2], p[3], p[0]] } else { [p[3], p[2], p[1], p[0]] }); + } + } + } + } + Image::from_u8(w, h, layout, out) +} + +/// Writes an uncompressed rasterfile: 8-bit gray, 24-bit RGB or 32-bit RGBA, in the RGB-ordered type. +pub(crate) fn encode(src: &Image, plan: Plan) -> Result, CodecError> { + let enc = |msg: String| CodecError::encode(F, msg); + let img = src.converted(plan.layout, plan.sample); + if img.sample_type() != SampleType::U8 { + return Err(enc(format!("Sun raster stores 8 bits per channel, not {:?}", img.sample_type()))); + } + let depth: usize = match img.layout() { + ChannelLayout::Gray => 8, + ChannelLayout::Rgb => 24, + ChannelLayout::Rgba => 32, + l => return Err(enc(format!("no Sun raster layout for {l:?}"))), + }; + let (w, h) = img.dimensions(); + let (wu, hu) = (w as usize, h as usize); + let bytes = depth / 8; + let stride = (wu * bytes).next_multiple_of(2); + let len = stride.checked_mul(hu).and_then(|n| u32::try_from(n).ok()).ok_or_else(|| enc("image too large".into()))?; + let data = img.data(); + if data.len() != wu * hu * bytes { + return Err(enc("the image has the wrong number of samples".into())); + } + let mut out = Vec::with_capacity(HEADER + len as usize); + for v in [MAGIC, w, h, depth as u32, len, 3, 0, 0] { + out.extend_from_slice(&v.to_be_bytes()); + } + for y in 0..hu { + let row = &data[y * wu * bytes..(y + 1) * wu * bytes]; + if depth == 32 { + // Stored alpha first. + for p in row.as_chunks::<4>().0 { + out.extend_from_slice(&[p[3], p[0], p[1], p[2]]); + } + } else { + out.extend_from_slice(row); + } + out.resize(HEADER + (y + 1) * stride, 0); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn pattern(w: u32, h: u32, layout: ChannelLayout) -> Image { + let n = w as usize * h as usize * layout.channels(); + Image::from_u8(w, h, layout, (0..n).map(|i| ((i * 13 + i / 3) % 253) as u8).collect()).unwrap() + } + + #[test] + fn round_trips_gray_rgb_and_rgba_with_odd_widths() { + for layout in [ChannelLayout::Gray, ChannelLayout::Rgb, ChannelLayout::Rgba] { + let img = pattern(13, 7, layout); + let bytes = encode(&img, Plan { layout, sample: SampleType::U8 }).unwrap(); + assert!(looks_like_sunraster(&bytes)); + let back = decode(&bytes, &Limits::default()).unwrap(); + assert_eq!((back.layout(), back.data()), (layout, img.data())); + } + } + + fn file(depth: u32, kind: u32, map: &[u8], map_type: u32, w: u32, h: u32, data: &[u8]) -> Vec { + let mut f = Vec::new(); + for v in [MAGIC, w, h, depth, data.len() as u32, kind, map_type, map.len() as u32] { + f.extend_from_slice(&v.to_be_bytes()); + } + f.extend_from_slice(map); + f.extend_from_slice(data); + f + } + + #[test] + fn standard_type_is_blue_first_and_rle_expands() { + let f = file(24, 1, &[], 0, 1, 1, &[1, 2, 3, 0]); + assert_eq!(decode(&f, &Limits::default()).unwrap().data(), &[3, 2, 1]); + // 0x80 0x00 is a literal 0x80; 0x80 n v is n + 1 copies of v. The 2x2 image has stride 2. + let f = file(8, 2, &[], 0, 2, 2, &[0x80, 0x00, 0x80, 0x00, 0x80, 0x01, 7]); + assert_eq!(decode(&f, &Limits::default()).unwrap().data(), &[0x80, 0x80, 7, 7]); + // A run that passes the end of the image is an error. + assert!(decode(&file(8, 2, &[], 0, 2, 2, &[0x80, 0x09, 7]), &Limits::default()).is_err()); + } + + #[test] + fn colour_mapped_and_one_bit_files() { + // Two entries: red plane, green plane, blue plane. + let map = [10, 20, 30, 40, 50, 60]; + let f = file(8, 1, &map, 1, 2, 1, &[0, 1]); + let img = decode(&f, &Limits::default()).unwrap(); + assert_eq!((img.layout(), img.data()), (ChannelLayout::Rgb, &[10, 30, 50, 20, 40, 60][..])); + let f = file(8, 1, &map, 1, 1, 1, &[5, 0]); + assert!(decode(&f, &Limits::default()).is_err()); + let f = file(1, 1, &[], 0, 3, 1, &[0b1010_0000, 0]); + assert_eq!(decode(&f, &Limits::default()).unwrap().data(), &[0, 255, 0]); + } + + #[test] + fn hostile_input_is_an_error_not_a_panic() { + let img = pattern(9, 5, ChannelLayout::Rgb); + let good = encode(&img, Plan { layout: ChannelLayout::Rgb, sample: SampleType::U8 }).unwrap(); + for len in 0..good.len() { + let _ = decode(&good[..len], &Limits::default()); + } + let mut huge = good.clone(); + huge[4..8].copy_from_slice(&u32::MAX.to_be_bytes()); + huge[8..12].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(decode(&huge, &Limits::default()).is_err()); + let mut bad_map = good; + bad_map[28..32].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(decode(&bad_map, &Limits::default()).is_err()); + assert!(matches!(decode(&file(24, 4, &[], 0, 1, 1, &[0; 4]), &Limits::default()), Err(CodecError::Unsupported { .. }))); + } +} diff --git a/crates/image-codecs/src/format.rs b/crates/image-codecs/src/format.rs index ecaf945cd..d4075cc8e 100644 --- a/crates/image-codecs/src/format.rs +++ b/crates/image-codecs/src/format.rs @@ -44,6 +44,8 @@ pub enum Format { Iff, /// JPEG 2000 (JP2 container or raw J2K codestream): read-only; see [`ASYMMETRIC_EXCEPTIONS`]. Jp2, + /// Sun Raster (`.ras`): 1-, 8-, 24- and 32-bit, uncompressed or RLE. + SunRaster, } /// What a format can hold **and** what this crate reads/writes for it. @@ -113,7 +115,7 @@ const TIFF_LAYOUTS: &[ChannelLayout] = &[L::Gray, L::GrayA, L::Rgb, L::Rgba, L:: impl Format { /// Every format known to the crate (enabled or not). - pub const ALL: [Format; 24] = [ + pub const ALL: [Format; 25] = [ Format::Png, Format::Jpeg, Format::Jp2, @@ -138,6 +140,7 @@ impl Format { Format::Cineon, Format::Dicom, Format::Iff, + Format::SunRaster, ]; pub fn caps(self) -> FormatCaps { @@ -176,6 +179,7 @@ impl Format { Format::Dicom => "DICOM", Format::Iff => "Amiga IFF", Format::Jp2 => "JPEG 2000", + Format::SunRaster => "Sun Raster", } } @@ -207,6 +211,7 @@ impl Format { Format::Dicom => &["dcm", "dicom", "dc3"], Format::Iff => &["iff", "lbm", "ilbm"], Format::Jp2 => &["jp2", "j2k", "j2c", "jpf", "jpx"], + Format::SunRaster => &["ras", "sun"], } } @@ -236,6 +241,7 @@ impl Format { Format::Dicom => "application/dicom", Format::Iff => "image/x-iff", Format::Jp2 => "image/jp2", + Format::SunRaster => "image/x-sun-raster", } } @@ -310,6 +316,7 @@ pub fn caps(format: Format) -> FormatCaps { Format::Cineon => FormatCaps { depths: &[S::U16], layouts: &[L::Gray, L::Rgb], alpha: false, ..base }, Format::Dicom => FormatCaps { read: true, write: false, depths: &[S::U8, S::U16], layouts: &[L::Gray, L::Rgb], alpha: false, ..base }, Format::Iff => FormatCaps { depths: &[S::U8], layouts: &[L::Rgb, L::Rgba], alpha: true, ..base }, + Format::SunRaster => FormatCaps { layouts: &[L::Gray, L::Rgb, L::Rgba], alpha: true, ..base }, Format::Jp2 => FormatCaps { read: true, write: false, layouts: &[L::Gray, L::GrayA, L::Rgb, L::Rgba, L::Cmyk, L::CmykA], icc: true, ..base }, } } @@ -388,6 +395,9 @@ pub fn detect(bytes: &[u8]) -> Option { if b.starts_with(b"/* XPM */") || b.starts_with(b"! XPM2\n") || b.starts_with(b"! XPM2\r\n") { return Some(Format::Xpm); } + if crate::codecs::sunraster::looks_like_sunraster(b) { + return Some(Format::SunRaster); + } if crate::codecs::pcx::looks_like_pcx(b) { return Some(Format::Pcx); } diff --git a/crates/image-codecs/src/lib.rs b/crates/image-codecs/src/lib.rs index 21130e392..ab235d2ab 100644 --- a/crates/image-codecs/src/lib.rs +++ b/crates/image-codecs/src/lib.rs @@ -62,7 +62,7 @@ pub use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_ pub use crate::source_settings::{WebpEncoding, jpeg_quality, webp_encoding}; pub use half::f16; -use crate::codecs::{dds, dicom, dpx, exr, fits, heif, iff, jp2, jpeg, jxl, pcx, png, pnm, tiff, via_image, webp, xpm}; +use crate::codecs::{dds, dicom, dpx, exr, fits, heif, iff, jp2, jpeg, jxl, pcx, png, pnm, sunraster, tiff, via_image, webp, xpm}; /// Detect the format and decode with default [`Limits`]. pub fn decode(bytes: &[u8]) -> Result { @@ -101,6 +101,7 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res Format::Cineon => dpx::decode_cineon(bytes, l), Format::Dicom => dicom::decode(bytes, l), Format::Iff => iff::decode(bytes, l), + Format::SunRaster => sunraster::decode(bytes, l), Format::OpenExr => exr::decode(bytes, l), Format::Heif => heif::decode(bytes, l, opts.keep_orientation), Format::Jp2 => jp2::decode(bytes, l), @@ -457,6 +458,7 @@ pub fn encode(image: &Image, format: Format, opts: &EncodeOptions) -> Result dpx::encode_cineon(image, plan), Format::Dicom => Err(CodecError::unsupported(format, "DICOM is import-only; save as TIFF or PNG instead")), Format::Iff => iff::encode(image, plan), + Format::SunRaster => sunraster::encode(image, plan), Format::OpenExr => exr::encode(image, plan, opts), Format::Heif => Err(CodecError::unsupported(format, "encoding is not available in this build")), Format::Jp2 => Err(CodecError::unsupported(format, "JPEG 2000 is import-only; save as PNG or TIFF instead")), diff --git a/crates/image-codecs/tests/it/detect_caps.rs b/crates/image-codecs/tests/it/detect_caps.rs index 640772c83..17fb20442 100644 --- a/crates/image-codecs/tests/it/detect_caps.rs +++ b/crates/image-codecs/tests/it/detect_caps.rs @@ -62,6 +62,7 @@ fn default_build_formats_all_symmetric() { Format::Dpx, Format::Cineon, Format::Iff, + Format::SunRaster, ]; for f in expected { assert!(caps(f).read && caps(f).write, "{f:?}"); @@ -218,6 +219,19 @@ fn detect_magic_iff() { assert_eq!(detect(b"FORM\0\0\0\x14AIFF"), None); assert!(decode_as(Format::Iff, b"FORM\0\0\0\x14ILBM").is_err()); } +#[test] +fn detect_magic_sun_raster() { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Image, encode}; + let img = Image::from_u8(5, 3, ChannelLayout::Rgb, (0..45).collect()).unwrap(); + let bytes = encode(&img, Format::SunRaster, &EncodeOptions::default()).unwrap(); + assert_eq!(detect(&bytes), Some(Format::SunRaster)); + assert_eq!(from_extension("scan.RAS"), Some(Format::SunRaster)); + assert_eq!(decode(&bytes).unwrap().data(), img.data()); + assert!(!ASYMMETRIC_EXCEPTIONS.iter().any(|(f, _)| *f == Format::SunRaster)); + assert_eq!(detect(&[0x59, 0xa6, 0x6a, 0x95]), None); + assert!(decode_as(Format::SunRaster, &[0x59, 0xa6, 0x6a, 0x95]).is_err()); +} + #[test] fn detect_magic_avif() { assert_eq!(detect(b"\0\0\0\x1cftypavif\0\0\0\0avifmif1miaf"), Some(Format::Avif)); From e9eaaf5641640b4e2735b0af79ef589c5a74a88a Mon Sep 17 00:00:00 2001 From: el-j Date: Sun, 15 Nov 2026 16:52:35 +0100 Subject: [PATCH 2/5] craft-image-codecs: Sun Raster 1-bit colour maps, opaque standard 32-bit pixels, fallible output buffer Addresses review findings: a 1-bit file with an RGB colour map reads as colour; the unused first byte of standard 32-bit pixels is no longer read as alpha; the writer's buffer is reserved with try_reserve_exact. README lists the native layouts correctly. --- crates/image-codecs/README.md | 2 +- crates/image-codecs/src/codecs/sunraster.rs | 52 +++++++++++++++++++-- 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/crates/image-codecs/README.md b/crates/image-codecs/README.md index f9f5f53e6..a37760d80 100644 --- a/crates/image-codecs/README.md +++ b/crates/image-codecs/README.md @@ -56,7 +56,7 @@ craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "< | Cineon | yes | yes | U16 (10-bit code values read and written exactly through U16) | Gray, RGB | no | no | no | no | no | no | no | built in | | DICOM | yes | **no** | U8, U16 | Gray, RGB | no | no | no | no | no | no | n/a | built in | | Amiga IFF (ILBM/PBM) | yes | yes (24-bit ILBM) | U8 | RGB, RGBA | yes (1-bit mask plane on write) | no | no | no | no | no | no | built in | -| Sun Raster (`.ras`) | yes (incl. RLE and colour maps) | yes (uncompressed) | U8 | Gray, Gray+A, RGB, RGBA | yes | no | no | no | no | no | no | built in | +| Sun Raster (`.ras`) | yes (incl. RLE and colour maps) | yes (uncompressed) | U8 | Gray, RGB, RGBA | yes | no | no | no | no | no | no | built in | | AVIF | **no** | only with feature `avif` | U8 | RGB, RGBA | yes | no | no | no | no | no | yes | `image` + `ravif` | | HEIF/HEIC | with feature `heif` | **no** | U8, U16 (10/12-bit decodes to U16) | RGB, RGBA | yes (auxiliary alpha) | yes (`colr` prof) | yes | yes | no | no | n/a | `heic-rs` | diff --git a/crates/image-codecs/src/codecs/sunraster.rs b/crates/image-codecs/src/codecs/sunraster.rs index 84d60f145..85c24acc5 100644 --- a/crates/image-codecs/src/codecs/sunraster.rs +++ b/crates/image-codecs/src/codecs/sunraster.rs @@ -97,9 +97,18 @@ pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result { for x in 0..wu { match depth { 1 => { - // A set bit is black. let bit = (row[x / 8] >> (7 - x % 8)) & 1; - out.push(if bit == 1 { 0 } else { 255 }); + if map_type == 1 { + // The bit is an index into the (two-entry or longer) colour map. + let i = usize::from(bit); + if i >= entries { + return Err(bad("pixel index is outside the colour map")); + } + out.extend_from_slice(&[map[i], map[entries + i], map[2 * entries + i]]); + } else { + // A set bit is black. + out.push(if bit == 1 { 0 } else { 255 }); + } } 8 if map_type == 1 => { let i = usize::from(row[x]); @@ -115,7 +124,8 @@ pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result { } _ => { let p = &row[4 * x..4 * x + 4]; - out.extend_from_slice(&if kind == 3 { [p[1], p[2], p[3], p[0]] } else { [p[3], p[2], p[1], p[0]] }); + // In the standard types the first byte (X in XBGR) is unused, not alpha. + out.extend_from_slice(&if kind == 3 { [p[1], p[2], p[3], p[0]] } else { [p[3], p[2], p[1], 255] }); } } } @@ -123,6 +133,13 @@ pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result { Image::from_u8(w, h, layout, out) } +/// A buffer of `cap` bytes, or an error instead of an abort when the allocation cannot be made. +fn reserve(cap: usize) -> std::result::Result, std::collections::TryReserveError> { + let mut v = Vec::new(); + v.try_reserve_exact(cap)?; + Ok(v) +} + /// Writes an uncompressed rasterfile: 8-bit gray, 24-bit RGB or 32-bit RGBA, in the RGB-ordered type. pub(crate) fn encode(src: &Image, plan: Plan) -> Result, CodecError> { let enc = |msg: String| CodecError::encode(F, msg); @@ -145,7 +162,8 @@ pub(crate) fn encode(src: &Image, plan: Plan) -> Result, CodecError> { if data.len() != wu * hu * bytes { return Err(enc("the image has the wrong number of samples".into())); } - let mut out = Vec::with_capacity(HEADER + len as usize); + let mut out = reserve(HEADER.checked_add(len as usize).ok_or_else(|| enc("image too large".into()))?) + .map_err(|_| enc("the image is too large to encode".into()))?; for v in [MAGIC, w, h, depth as u32, len, 3, 0, 0] { out.extend_from_slice(&v.to_be_bytes()); } @@ -218,6 +236,32 @@ mod tests { assert_eq!(decode(&f, &Limits::default()).unwrap().data(), &[0, 255, 0]); } + #[test] + fn one_bit_files_with_a_colour_map_read_as_colour() { + // Two entries: red plane, green plane, blue plane; bit 0 is entry 0. + let map = [10, 20, 30, 40, 50, 60]; + let f = file(1, 1, &map, 1, 3, 1, &[0b0100_0000, 0]); + let img = decode(&f, &Limits::default()).unwrap(); + assert_eq!((img.layout(), img.data()), (ChannelLayout::Rgb, &[10, 30, 50, 20, 40, 60, 10, 30, 50][..])); + // A one-entry map has no entry for a set bit. + assert!(decode(&file(1, 1, &[1, 2, 3], 1, 1, 1, &[0b1000_0000, 0]), &Limits::default()).is_err()); + } + + #[test] + fn the_unused_first_byte_of_standard_32_bit_pixels_is_not_alpha() { + let img = decode(&file(32, 1, &[], 0, 1, 1, &[0, 30, 20, 10]), &Limits::default()).unwrap(); + assert_eq!((img.layout(), img.data()), (ChannelLayout::Rgba, &[10, 20, 30, 255][..])); + // In the RGB-ordered type the first byte is the alpha the writer stores there. + let img = decode(&file(32, 3, &[], 0, 1, 1, &[7, 10, 20, 30]), &Limits::default()).unwrap(); + assert_eq!(img.data(), &[10, 20, 30, 7]); + } + + #[test] + fn an_output_buffer_too_large_to_allocate_is_an_error() { + assert!(reserve(usize::MAX).is_err()); + assert!(reserve(16).is_ok()); + } + #[test] fn hostile_input_is_an_error_not_a_panic() { let img = pattern(9, 5, ChannelLayout::Rgb); From d7696c4c767857d21e34e0718f33caff6df02665 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 17:32:45 +0000 Subject: [PATCH 3/5] Format Sun Raster feature gates --- crates/image-codecs/src/codecs.rs | 4 ++-- crates/image-codecs/src/format.rs | 8 +++++++- crates/image-codecs/src/lib.rs | 24 ++++++++++++++++-------- 3 files changed, 25 insertions(+), 11 deletions(-) diff --git a/crates/image-codecs/src/codecs.rs b/crates/image-codecs/src/codecs.rs index cc1b5a44e..81288cb4d 100644 --- a/crates/image-codecs/src/codecs.rs +++ b/crates/image-codecs/src/codecs.rs @@ -18,10 +18,10 @@ pub(crate) mod jxl; pub(crate) mod pcx; pub(crate) mod png; pub(crate) mod pnm; -#[cfg(feature = "sunraster")] -pub(crate) mod sunraster; #[cfg(feature = "sgi")] pub(crate) mod sgi; +#[cfg(feature = "sunraster")] +pub(crate) mod sunraster; pub(crate) mod tga; pub(crate) mod tiff; pub(crate) mod tiff_exif; diff --git a/crates/image-codecs/src/format.rs b/crates/image-codecs/src/format.rs index aab2292b0..f4f3c7186 100644 --- a/crates/image-codecs/src/format.rs +++ b/crates/image-codecs/src/format.rs @@ -328,7 +328,13 @@ pub fn caps(format: Format) -> FormatCaps { Format::Cineon => FormatCaps { depths: &[S::U16], layouts: &[L::Gray, L::Rgb], alpha: false, ..base }, Format::Dicom => FormatCaps { read: true, write: false, depths: &[S::U8, S::U16], layouts: &[L::Gray, L::Rgb], alpha: false, ..base }, Format::Iff => FormatCaps { depths: &[S::U8], layouts: &[L::Rgb, L::Rgba], alpha: true, ..base }, - Format::SunRaster => FormatCaps { read: cfg!(feature = "sunraster"), write: cfg!(feature = "sunraster"), layouts: &[L::Gray, L::Rgb, L::Rgba], alpha: true, ..base }, + Format::SunRaster => FormatCaps { + read: cfg!(feature = "sunraster"), + write: cfg!(feature = "sunraster"), + layouts: &[L::Gray, L::Rgb, L::Rgba], + alpha: true, + ..base + }, Format::Sgi => { FormatCaps { read: cfg!(feature = "sgi"), write: cfg!(feature = "sgi"), depths: &[S::U8, S::U16], layouts: RGB_GRAY, alpha: true, ..base } } diff --git a/crates/image-codecs/src/lib.rs b/crates/image-codecs/src/lib.rs index c86301520..e958bada6 100644 --- a/crates/image-codecs/src/lib.rs +++ b/crates/image-codecs/src/lib.rs @@ -64,10 +64,10 @@ pub use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_ pub use crate::source_settings::{WebpEncoding, jpeg_quality, webp_encoding}; pub use half::f16; -#[cfg(feature = "sunraster")] -use crate::codecs::sunraster; #[cfg(feature = "sgi")] use crate::codecs::sgi; +#[cfg(feature = "sunraster")] +use crate::codecs::sunraster; use crate::codecs::{dds, dicom, dpx, exr, fits, heif, iff, jp2, jpeg, jpegls, jxl, pcx, png, pnm, tiff, via_image, webp, xpm}; /// Detect the format and decode with default [`Limits`]. @@ -109,10 +109,14 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res Format::Iff => iff::decode(bytes, l), Format::SunRaster => { #[cfg(feature = "sunraster")] - { sunraster::decode(bytes, l) } + { + sunraster::decode(bytes, l) + } #[cfg(not(feature = "sunraster"))] - { Err(CodecError::unsupported(format, "Sun Raster support requires the sunraster feature")) } - }, + { + Err(CodecError::unsupported(format, "Sun Raster support requires the sunraster feature")) + } + } Format::Sgi => { #[cfg(feature = "sgi")] { @@ -482,10 +486,14 @@ pub fn encode(image: &Image, format: Format, opts: &EncodeOptions) -> Result iff::encode(image, plan), Format::SunRaster => { #[cfg(feature = "sunraster")] - { sunraster::encode(image, plan) } + { + sunraster::encode(image, plan) + } #[cfg(not(feature = "sunraster"))] - { Err(CodecError::unsupported(format, "Sun Raster support requires the sunraster feature")) } - }, + { + Err(CodecError::unsupported(format, "Sun Raster support requires the sunraster feature")) + } + } Format::Sgi => { #[cfg(feature = "sgi")] { From d2f95f488c25ef3d94746148ef63d9d190259ac4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 17:33:21 +0000 Subject: [PATCH 4/5] Include Sun Raster in coverage build --- .github/workflows/sonarcloud.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index 654fe4c02..f27878af5 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -23,5 +23,5 @@ jobs: # The codec and format code behind features that are off by default. Without these the # coverage build never compiles it, and new code there reads as untested. cargo-features: >- - craft-video/dnx,craft-video/vp8,craft-video/prores,craft-video/h264,craft-video/hevc,craft-video/vp9,craft-video/av1,craft-video/threads,craft-audio/decode,craft-audio/encode,craft-audio/peaks,craft-audio/rayon,craft-audio/serde,craft-media/matroska,craft-media/ogg,craft-media/bitstream,craft-media/serde,craft-mesh/stl,craft-mesh/obj,craft-mesh/ply,craft-mesh/gltf,craft-metafile/write + craft-video/dnx,craft-video/vp8,craft-video/prores,craft-video/h264,craft-video/hevc,craft-video/vp9,craft-video/av1,craft-video/threads,craft-audio/decode,craft-audio/encode,craft-audio/peaks,craft-audio/rayon,craft-audio/serde,craft-media/matroska,craft-media/ogg,craft-media/bitstream,craft-media/serde,craft-mesh/stl,craft-mesh/obj,craft-mesh/ply,craft-mesh/gltf,craft-metafile/write,craft-image-codecs/sunraster secrets: inherit From 048c93634a5183c070c349a5ccfe2d581cbc3ee6 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:15:55 +0100 Subject: [PATCH 5/5] image-codecs: probe PNG, JPEG and TIFF sizes from the header probe_size returned Unsupported for PNG, JPEG and TIFF, so callers sized those images with a full decode. Each now reads only its header with the checks decode runs: PNG's IHDR/fcTL, limits and plausibility; JPEG's first frame header and EXIF; TIFF's default page directory, camera-raw refusal and Orientation tag. The size is turned upright for 5-8, as decode returns it. --- crates/image-codecs/src/codecs/jpeg.rs | 9 ++++++ crates/image-codecs/src/codecs/png.rs | 20 +++++++++++++ crates/image-codecs/src/codecs/tiff.rs | 2 +- crates/image-codecs/src/codecs/tiff/decode.rs | 11 +++++++ crates/image-codecs/src/lib.rs | 15 +++++++--- crates/image-codecs/tests/it/limits.rs | 29 +++++++++++++++++++ crates/image-codecs/tests/it/orientation.rs | 20 +++++++++++-- crates/image-codecs/tests/it/tiff_pages.rs | 6 ++++ 8 files changed, 105 insertions(+), 7 deletions(-) diff --git a/crates/image-codecs/src/codecs/jpeg.rs b/crates/image-codecs/src/codecs/jpeg.rs index 15346ea56..1b92ea9d9 100644 --- a/crates/image-codecs/src/codecs/jpeg.rs +++ b/crates/image-codecs/src/codecs/jpeg.rs @@ -389,6 +389,15 @@ fn decode_craft_jpeg(bytes: &[u8], limits: &Limits, adobe_transform: Option, /// truncated or not, are far above this. const MAX_PIXELS_PER_BYTE: u64 = 2048; +/// The stored size and EXIF block [`decode`] would find, from the marker segments before the +/// first scan: the first frame header's size, checked against `limits`, and the APP1 EXIF block. +pub(crate) fn probe(bytes: &[u8], limits: &Limits) -> Result<(u32, u32, Option>), CodecError> { + let meta = scan_metadata(bytes); + let (w, h, _) = meta.frame.ok_or_else(|| err("no frame header before the image data"))?; + limits.check_size(w, h)?; + Ok((w, h, meta.exif)) +} + pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result { let (end, scan_bytes) = data_end(bytes); if end == DataEnd::Empty { diff --git a/crates/image-codecs/src/codecs/png.rs b/crates/image-codecs/src/codecs/png.rs index 9965dfc30..a244a1aae 100644 --- a/crates/image-codecs/src/codecs/png.rs +++ b/crates/image-codecs/src/codecs/png.rs @@ -27,6 +27,26 @@ pub(crate) fn dpi_of_ppm(ppm: u32) -> f32 { } /// Decodes a whole PNG, by driving a [`PngDecodeRows`] to its end. +/// The stored size and EXIF block [`decode`] would find, from the chunks before the image data: +/// the same header checks (limits, a file too small for its image) and the same frame (an fcTL +/// before the IDAT overrides the header's size), without inflating any pixels or text. +pub(crate) fn probe(bytes: &[u8], limits: &Limits) -> Result<(u32, u32, Option>), CodecError> { + let mut decoder = png::Decoder::new_with_limits(Cursor::new(bytes), png::Limits { bytes: limits.alloc_usize() }); + decoder.set_ignore_text_chunk(true); + { + let info = decoder.read_header_info().map_err(map_png_err)?; + let (w, h) = info.size(); + limits.check_size(w, h)?; + let stored = u64::from(w).saturating_mul(u64::from(h)).saturating_mul(info.bits_per_pixel() as u64).div_ceil(8); + Limits::check_plausible(stored, bytes.len(), 1100)?; + } + let reader = decoder.read_info().map_err(map_png_err)?; + let info = reader.info(); + let (w, h) = info.frame_control.map_or_else(|| info.size(), |f| (f.width, f.height)); + limits.check_size(w, h)?; + Ok((w, h, info.exif_metadata.as_ref().map(|c| c.to_vec()))) +} + pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result { PngDecodeRows::new(bytes, limits)?.step(&mut || true)?.ok_or_else(|| err("the decoder stopped before the image ended")) } diff --git a/crates/image-codecs/src/codecs/tiff.rs b/crates/image-codecs/src/codecs/tiff.rs index c74ab4436..fa279d9f0 100644 --- a/crates/image-codecs/src/codecs/tiff.rs +++ b/crates/image-codecs/src/codecs/tiff.rs @@ -171,7 +171,7 @@ mod tags; mod ycbcr; pub use decode::TiffBands; -pub(crate) use decode::{decode, decode_page, has_unretained_samples, orientation}; +pub(crate) use decode::{decode, decode_page, has_unretained_samples, orientation, probe}; pub(crate) use encode::encode; #[cfg(test)] use encode::{Extras, try_with_capacity}; diff --git a/crates/image-codecs/src/codecs/tiff/decode.rs b/crates/image-codecs/src/codecs/tiff/decode.rs index 97efdd979..a9caa98ee 100644 --- a/crates/image-codecs/src/codecs/tiff/decode.rs +++ b/crates/image-codecs/src/codecs/tiff/decode.rs @@ -13,6 +13,17 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result decode_page(bytes, None, limits) } +/// The stored size and Orientation (1–8) of the page [`decode`] opens, from its directory alone: +/// the same page choice and refusals (camera raw, no directory), checked against `limits`, +/// without reading any strips or tiles. +pub(crate) fn probe(bytes: &[u8], limits: &Limits) -> Result<(u32, u32, u16), CodecError> { + let (file, dir, _) = open_page(bytes, None)?; + let side = |tag: u16| file.tag_uint(&dir, tag).and_then(|v| u32::try_from(v).ok()).unwrap_or(0); + let (w, h) = (side(ifd::TAG_WIDTH), side(ifd::TAG_HEIGHT)); + limits.check_size(w, h)?; + Ok((w, h, ifd::orientation_of(&file, &dir))) +} + /// Decodes page `page` of [`ifd::tiff_info`]'s list (`None`: the default page). The image /// carries the page's metadata, a [`DecodeWarning::MorePages`] when the file holds more /// full-resolution pages, and a [`DecodeWarning::Truncated`] when image data is cut off. diff --git a/crates/image-codecs/src/lib.rs b/crates/image-codecs/src/lib.rs index 361285b2a..78df75333 100644 --- a/crates/image-codecs/src/lib.rs +++ b/crates/image-codecs/src/lib.rs @@ -199,10 +199,11 @@ pub fn decode_png_rows>( } /// The upright pixel size [`decode`] would return, read from the file's header without decoding -/// pixels, for WebP, OpenEXR (flat) and the GIF/BMP/TGA/ICO/QOI/HDR family. It runs the same -/// header reads and size checks as the decoder (default [`Limits`]) and swaps the size for an -/// EXIF orientation of 5–8, so wherever [`decode`] succeeds the two agree. Other formats (and -/// deep EXR or AVIF) return [`CodecError::Unsupported`]: decode those to learn their size. +/// pixels, for PNG, JPEG, TIFF (the page [`decode`] opens), WebP, OpenEXR (flat) and the +/// GIF/BMP/TGA/ICO/QOI/HDR family. It runs the same header reads and size checks as the decoder +/// (default [`Limits`]) and swaps the size for an orientation of 5–8 (EXIF, or the TIFF page's +/// own tag), so wherever [`decode`] succeeds the two agree. Other formats (and deep EXR or AVIF) +/// return [`CodecError::Unsupported`]: decode those to learn their size. pub fn probe_size(bytes: &[u8]) -> Result<(u32, u32), CodecError> { let format = detect(bytes).ok_or(CodecError::UnknownFormat)?; if !caps(format).read { @@ -210,6 +211,12 @@ pub fn probe_size(bytes: &[u8]) -> Result<(u32, u32), CodecError> { } let l = &Limits::default(); let (w, h, exif) = match format { + Format::Png => png::probe(bytes, l)?, + Format::Jpeg => jpeg::probe(bytes, l)?, + Format::Tiff => { + let (w, h, o) = tiff::probe(bytes, l)?; + return Ok(if (5..=8).contains(&o) { (h, w) } else { (w, h) }); + } Format::WebP => webp::probe(bytes, l)?, Format::OpenExr => exr::probe(bytes, l).map(|(w, h)| (w, h, None))?, Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => via_image::probe(format, bytes, l)?, diff --git a/crates/image-codecs/tests/it/limits.rs b/crates/image-codecs/tests/it/limits.rs index e590aa568..49561e7a8 100644 --- a/crates/image-codecs/tests/it/limits.rs +++ b/crates/image-codecs/tests/it/limits.rs @@ -671,3 +671,32 @@ fn highly_compressible_jpeg_and_gif_still_decode() { assert_eq!(decode(&b).unwrap().width(), 3000, "{f:?}"); } } + +/// `probe_size` refuses the headers `decode` refuses, from the header alone: a size past the +/// limits, and one at the limit that a tiny file cannot hold. +#[test] +fn probe_size_refuses_png_bomb_headers() { + for side in [100_000u32, 32768] { + let mut ihdr = Vec::new(); + ihdr.extend_from_slice(&side.to_be_bytes()); + ihdr.extend_from_slice(&side.to_be_bytes()); + ihdr.extend_from_slice(&[16, 6, 0, 0, 0]); + let mut b = b"\x89PNG\r\n\x1a\n".to_vec(); + b.extend(png_chunk(b"IHDR", &ihdr)); + b.extend(png_chunk(b"IDAT", &[0x78, 0x9C, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01])); + b.extend(png_chunk(b"IEND", &[])); + assert!(matches!(probe_size(&b), Err(CodecError::LimitExceeded(_))), "{side}"); + } +} + +/// A JPEG header declaring a size past the default limits is refused by `probe_size` as by +/// `decode`, without reading the scan. +#[test] +fn probe_size_refuses_an_oversized_jpeg_header() { + let mut jpeg = encoded(Format::Jpeg); + assert_eq!(probe_size(&jpeg).unwrap(), (64, 48)); + let sof = jpeg.windows(2).position(|w| matches!(w, [0xFF, 0xC0..=0xC2])).unwrap(); + jpeg[sof + 5..sof + 9].copy_from_slice(&[0xFF, 0xFF, 0xFF, 0xFF]); + assert!(decode(&jpeg).is_err()); + assert!(matches!(probe_size(&jpeg), Err(CodecError::LimitExceeded(_))), "{:?}", probe_size(&jpeg)); +} diff --git a/crates/image-codecs/tests/it/orientation.rs b/crates/image-codecs/tests/it/orientation.rs index d5d3ad90e..4eaf188a8 100644 --- a/crates/image-codecs/tests/it/orientation.rs +++ b/crates/image-codecs/tests/it/orientation.rs @@ -202,6 +202,7 @@ fn png_opens_upright_for_every_orientation() { let file = png_with_exif(&png, &exif(u32::from(o), o % 2 == 0, false)); let img = decode(&file).unwrap(); assert_eq!(img.dimensions(), (w as u32, h as u32), "o={o}"); + assert_eq!(probe_size(&file).unwrap(), img.dimensions(), "the header probe turns upright too, o={o}"); assert_eq!(img.data(), &up[..], "o={o}"); assert_eq!(exif_orientation(img.meta.exif.as_deref().unwrap()), 1, "o={o}: metadata says upright"); // Decoded in steps and finished by `finish_png_decode`, it is the same image. @@ -309,8 +310,10 @@ fn tiff_opens_upright_for_every_orientation() { let up = exact_scene(w, h); for o in 1..=8u16 { let (s, sw, sh) = stored(&up, w, h, o); - let img = decode(&tiff_with_orientation(&s, sw as u32, sh as u32, o)).unwrap(); + let file = tiff_with_orientation(&s, sw as u32, sh as u32, o); + let img = decode(&file).unwrap(); assert_eq!(img.dimensions(), (w as u32, h as u32), "o={o}"); + assert_eq!(probe_size(&file).unwrap(), img.dimensions(), "the header probe turns upright too, o={o}"); assert_eq!(img.data(), &up[..], "o={o}"); } } @@ -358,6 +361,7 @@ fn jpeg_opens_upright_for_every_orientation() { let file = jpeg_with_exif(&jpeg, &exif(u32::from(o), o > 4, o == 7)); let img = decode(&file).unwrap(); assert_blocks(&img, &up, w, h, &format!("o={o}")); + assert_eq!(probe_size(&file).unwrap(), img.dimensions(), "the header probe turns upright too, o={o}"); assert_eq!(exif_orientation(img.meta.exif.as_deref().unwrap()), 1); } } @@ -659,7 +663,19 @@ fn long_orientation_reads_and_rewrites_in_both_byte_orders() { #[test] fn probe_size_matches_decode() { let img = synth(7, 5, ChannelLayout::Rgb, SampleType::U8, 3, 0.0); - let probed = [Format::WebP, Format::Gif, Format::Bmp, Format::Tga, Format::Qoi, Format::Hdr, Format::Ico, Format::OpenExr]; + let probed = [ + Format::Png, + Format::Jpeg, + Format::Tiff, + Format::WebP, + Format::Gif, + Format::Bmp, + Format::Tga, + Format::Qoi, + Format::Hdr, + Format::Ico, + Format::OpenExr, + ]; assert!(probed.iter().all(|f| rw_formats().contains(f))); for format in rw_formats() { let bytes = encode(&img, format, &EncodeOptions::default()).unwrap(); diff --git a/crates/image-codecs/tests/it/tiff_pages.rs b/crates/image-codecs/tests/it/tiff_pages.rs index b94509598..7501be936 100644 --- a/crates/image-codecs/tests/it/tiff_pages.rs +++ b/crates/image-codecs/tests/it/tiff_pages.rs @@ -539,6 +539,7 @@ fn every_ifd_and_subifd_is_listed_and_decodable() { // Like Photoshop: the first full-resolution page opens; the thumbnail is skipped. let img = decode_ok(&b.bytes); assert_eq!((img.dimensions(), img.data()[0]), ((9, 7), 2)); + assert_eq!(probe_size(&b.bytes).unwrap(), (9, 7), "the header probe sizes the page decode opens"); assert_eq!(img.warnings, [DecodeWarning::MorePages { total: Some(2) }]); // Every directory decodes on request. for (i, (w, level)) in [(4, 1u8), (9, 2), (3, 5), (2, 6), (9, 3), (5, 4)].into_iter().enumerate() { @@ -554,6 +555,7 @@ fn a_file_of_only_thumbnails_still_opens() { let b = build(true, false, &[gray_page(4, 3, 7, Some(1))], &[0]); assert_eq!(tiff_info(&b.bytes).unwrap().default_page(), Some(0)); assert_eq!(decode_ok(&b.bytes).data()[0], 7); + assert_eq!(probe_size(&b.bytes).unwrap(), (4, 3)); } #[test] @@ -698,6 +700,9 @@ fn hostile_sizes_and_counts_are_refused_without_allocating() { patch_value(&mut b, little, big, 0, 256, 0, wv); patch_value(&mut b, little, big, 0, 257, 0, hv); assert!(decode(&b.bytes).is_err(), "{wv}x{hv}"); + if wv > 300_000 || hv > 300_000 { + assert!(matches!(probe_size(&b.bytes), Err(CodecError::LimitExceeded(_))), "{wv}x{hv}: probe"); + } assert!(decode_with(&b.bytes, &DecodeOptions { limits: Limits::none(), ..Default::default() }).is_err(), "{wv}x{hv} without limits"); } // A strip-offset count far past the end of the file. @@ -805,6 +810,7 @@ fn poke(bytes: &[u8]) { let _ = decode_with(bytes, &DecodeOptions { limits: Limits { max_alloc: 16 << 20, ..Limits::default() }, ..Default::default() }); let _ = exif_orientation(bytes); let _ = tiff_orientation(bytes); + let _ = probe_size(bytes); if let Ok(info) = tiff_info(bytes) { for i in 0..info.pages.len().min(8) { let _ = decode_tiff_page(bytes, i, &DecodeOptions::default());