Merge branch 'simplify/u20' into simplify/w1b
Browse files at this commit23 changed files +79 -1279
- Cargo.lock +0 -45
- crates/ec-image/Cargo.toml +0 -1
- crates/ec-image/examples/bench.rs +0 -73
- crates/ec-image/fuzz/Cargo.toml +0 -56
- crates/ec-image/fuzz/fuzz_targets/bmp.rs +0 -17
- crates/ec-image/fuzz/fuzz_targets/decode_with_limits.rs +0 -17
- crates/ec-image/fuzz/fuzz_targets/gif.rs +0 -18
- crates/ec-image/fuzz/fuzz_targets/info.rs +0 -8
- crates/ec-image/fuzz/fuzz_targets/jpeg.rs +0 -18
- crates/ec-image/fuzz/fuzz_targets/png.rs +0 -17
- crates/ec-image/fuzz/fuzz_targets/tiff.rs +0 -17
- crates/ec-image/fuzz/fuzz_targets/webp.rs +0 -18
- crates/ec-image/fuzz/seed.sh +13 -40
- crates/ec-image/src/lib.rs +27 -65
- crates/ec-image/tests/fuzz.rs +0 -774
- crates/ec-image/tests/it/differential.rs +12 -1
- crates/ec-inflate/examples/bench.rs +0 -69
- crates/ec-inflate/fuzz/fuzz_targets/inflate_diff.rs +3 -2
- crates/ec-inflate/fuzz/fuzz_targets/inflate_raw.rs +2 -2
- crates/ec-inflate/src/bits.rs +2 -2
- crates/ec-inflate/src/deflate.rs +6 -1
- crates/ec-inflate/src/lib.rs +8 -17
- crates/ec-inflate/tests/inflate.rs +6 -1
Cargo.lockmodified+0 -45
| @@ -591,7 +591,6 @@ dependencies = [ | |||
| 591 | "ec-inflate", | 591 | "ec-inflate", |
| 592 | "ec-testkit", | 592 | "ec-testkit", |
| 593 | "image", | 593 | "image", |
| 594 | - "tracking-allocator", | ||
| 595 | ] | 594 | ] |
| 596 | 595 | ||
| 597 | [[package]] | 596 | [[package]] |
| @@ -1326,12 +1325,6 @@ version = "0.1.1" | |||
| 1326 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1325 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1327 | checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" | 1326 | checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" |
| 1328 | 1327 | ||
| 1329 | -[[package]] | ||
| 1330 | -name = "pin-project-lite" | ||
| 1331 | -version = "0.2.17" | ||
| 1332 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1333 | -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" | ||
| 1334 | - | ||
| 1335 | [[package]] | 1328 | [[package]] |
| 1336 | name = "pkg-config" | 1329 | name = "pkg-config" |
| 1337 | version = "0.3.34" | 1330 | version = "0.3.34" |
| @@ -1794,44 +1787,6 @@ dependencies = [ | |||
| 1794 | "zune-jpeg", | 1787 | "zune-jpeg", |
| 1795 | ] | 1788 | ] |
| 1796 | 1789 | ||
| 1797 | -[[package]] | ||
| 1798 | -name = "tracing" | ||
| 1799 | -version = "0.1.44" | ||
| 1800 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1801 | -checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" | ||
| 1802 | -dependencies = [ | ||
| 1803 | - "pin-project-lite", | ||
| 1804 | - "tracing-core", | ||
| 1805 | -] | ||
| 1806 | - | ||
| 1807 | -[[package]] | ||
| 1808 | -name = "tracing-core" | ||
| 1809 | -version = "0.1.36" | ||
| 1810 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1811 | -checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" | ||
| 1812 | -dependencies = [ | ||
| 1813 | - "once_cell", | ||
| 1814 | -] | ||
| 1815 | - | ||
| 1816 | -[[package]] | ||
| 1817 | -name = "tracing-subscriber" | ||
| 1818 | -version = "0.3.23" | ||
| 1819 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1820 | -checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" | ||
| 1821 | -dependencies = [ | ||
| 1822 | - "tracing-core", | ||
| 1823 | -] | ||
| 1824 | - | ||
| 1825 | -[[package]] | ||
| 1826 | -name = "tracking-allocator" | ||
| 1827 | -version = "0.4.0" | ||
| 1828 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1829 | -checksum = "1b61e0cb3385e17df7db29c565b40fd0350dfe8a076c7eea83d416e30cfd0581" | ||
| 1830 | -dependencies = [ | ||
| 1831 | - "tracing", | ||
| 1832 | - "tracing-subscriber", | ||
| 1833 | -] | ||
| 1834 | - | ||
| 1835 | [[package]] | 1790 | [[package]] |
| 1836 | name = "transpose" | 1791 | name = "transpose" |
| 1837 | version = "0.2.3" | 1792 | version = "0.2.3" |
crates/ec-image/Cargo.tomlmodified+0 -1
| @@ -16,4 +16,3 @@ ec-testkit.workspace = true | |||
| 16 | # bytes both ways and compares pixels. Running it is the point; nothing is | 16 | # bytes both ways and compares pixels. Running it is the point; nothing is |
| 17 | # copied from it. | 17 | # copied from it. |
| 18 | image = "0.25.10" | 18 | image = "0.25.10" |
| 19 | -tracking-allocator = "0.4.0" | ||
crates/ec-image/examples/bench.rsdeleted+0 -73
| @@ -1,73 +0,0 @@ | |||
| 1 | -//! bench: still-image decode and PNG encode rows for lanes/bench.md ("lane benchrest"). | ||
| 2 | -//! | ||
| 3 | -//! usage: | ||
| 4 | -//! bench png-dec <in.png> <out.rgb> [reps] | ||
| 5 | -//! bench jpeg-dec <in.jpg> <out.rgb> [reps] | ||
| 6 | -//! bench png-enc <in.rgba> <width> <height> <out.png> [reps] | ||
| 7 | -//! | ||
| 8 | -//! `png-dec` and `jpeg-dec` decode the file with `ec_image::decode`, `reps` times (default 5), and | ||
| 9 | -//! keep the best wall time. After timing, the last decode is converted with `to_rgb8` and written to | ||
| 10 | -//! `<out.rgb>` (untimed) so the pixels can be compared with ffmpeg's `-f rawvideo -pix_fmt rgb24`. | ||
| 11 | -//! `png-enc` encodes raw RGBA8 with `ec_image::png_encode::encode_rgba8`, best of `reps`, and writes | ||
| 12 | -//! the last PNG to `<out.png>`. | ||
| 13 | -use std::hint::black_box; | ||
| 14 | -use std::time::Instant; | ||
| 15 | - | ||
| 16 | -fn main() { | ||
| 17 | - let args: Vec<String> = std::env::args().collect(); | ||
| 18 | - match args.get(1).map(String::as_str) { | ||
| 19 | - Some("png-dec" | "jpeg-dec") if args.len() >= 4 => { | ||
| 20 | - let reps: usize = args.get(4).map_or(5, |s| s.parse().expect("reps")); | ||
| 21 | - assert!(reps >= 1, "reps must be at least 1"); | ||
| 22 | - let data = std::fs::read(&args[2]).expect("read input"); | ||
| 23 | - let mut best = f64::MAX; | ||
| 24 | - let mut last = None; | ||
| 25 | - for _ in 0..reps { | ||
| 26 | - let t = Instant::now(); | ||
| 27 | - let img = ec_image::decode(black_box(&data)).expect("decode"); | ||
| 28 | - best = best.min(t.elapsed().as_secs_f64()); | ||
| 29 | - last = Some(img); | ||
| 30 | - } | ||
| 31 | - let img = last.expect("at least one rep"); | ||
| 32 | - let (w, h) = img.dimensions(); | ||
| 33 | - let rgb = img.to_rgb8(); | ||
| 34 | - std::fs::write(&args[3], &rgb).expect("write output"); | ||
| 35 | - let mpix = f64::from(w) * f64::from(h) / 1e6; | ||
| 36 | - println!( | ||
| 37 | - "width={w} height={h} channels={} best_decode_s={best:.4} mpix_per_s={:.2} mb_per_s={:.2} out_bytes={} reps={reps}", | ||
| 38 | - img.pixels.channels(), | ||
| 39 | - mpix / best, | ||
| 40 | - rgb.len() as f64 / best / 1e6, | ||
| 41 | - rgb.len() | ||
| 42 | - ); | ||
| 43 | - } | ||
| 44 | - Some("png-enc") if args.len() >= 6 => { | ||
| 45 | - let reps: usize = args.get(6).map_or(5, |s| s.parse().expect("reps")); | ||
| 46 | - assert!(reps >= 1, "reps must be at least 1"); | ||
| 47 | - let w: u32 = args[3].parse().expect("width"); | ||
| 48 | - let h: u32 = args[4].parse().expect("height"); | ||
| 49 | - let raw = std::fs::read(&args[2]).expect("read input"); | ||
| 50 | - let mut best = f64::MAX; | ||
| 51 | - let mut out = Vec::new(); | ||
| 52 | - for _ in 0..reps { | ||
| 53 | - let t = Instant::now(); | ||
| 54 | - out = ec_image::png_encode::encode_rgba8(w, h, black_box(&raw)).expect("encode"); | ||
| 55 | - best = best.min(t.elapsed().as_secs_f64()); | ||
| 56 | - } | ||
| 57 | - std::fs::write(&args[5], &out).expect("write output"); | ||
| 58 | - let mpix = f64::from(w) * f64::from(h) / 1e6; | ||
| 59 | - println!( | ||
| 60 | - "width={w} height={h} best_encode_s={best:.4} mpix_per_s={:.2} mb_per_s={:.2} out_bytes={} reps={reps}", | ||
| 61 | - mpix / best, | ||
| 62 | - raw.len() as f64 / best / 1e6, | ||
| 63 | - out.len() | ||
| 64 | - ); | ||
| 65 | - } | ||
| 66 | - _ => { | ||
| 67 | - eprintln!( | ||
| 68 | - "usage: bench png-dec <in.png> <out.rgb> [reps]\n bench jpeg-dec <in.jpg> <out.rgb> [reps]\n bench png-enc <in.rgba> <width> <height> <out.png> [reps]" | ||
| 69 | - ); | ||
| 70 | - std::process::exit(2); | ||
| 71 | - } | ||
| 72 | - } | ||
| 73 | -} | ||
crates/ec-image/fuzz/Cargo.tomlmodified+0 -56
| @@ -24,20 +24,6 @@ test = false | |||
| 24 | doc = false | 24 | doc = false |
| 25 | bench = false | 25 | bench = false |
| 26 | 26 | ||
| 27 | -[[bin]] | ||
| 28 | -name = "decode_with_limits" | ||
| 29 | -path = "fuzz_targets/decode_with_limits.rs" | ||
| 30 | -test = false | ||
| 31 | -doc = false | ||
| 32 | -bench = false | ||
| 33 | - | ||
| 34 | -[[bin]] | ||
| 35 | -name = "info" | ||
| 36 | -path = "fuzz_targets/info.rs" | ||
| 37 | -test = false | ||
| 38 | -doc = false | ||
| 39 | -bench = false | ||
| 40 | - | ||
| 41 | [[bin]] | 27 | [[bin]] |
| 42 | name = "decode_animation" | 28 | name = "decode_animation" |
| 43 | path = "fuzz_targets/decode_animation.rs" | 29 | path = "fuzz_targets/decode_animation.rs" |
| @@ -45,48 +31,6 @@ test = false | |||
| 45 | doc = false | 31 | doc = false |
| 46 | bench = false | 32 | bench = false |
| 47 | 33 | ||
| 48 | -[[bin]] | ||
| 49 | -name = "bmp" | ||
| 50 | -path = "fuzz_targets/bmp.rs" | ||
| 51 | -test = false | ||
| 52 | -doc = false | ||
| 53 | -bench = false | ||
| 54 | - | ||
| 55 | -[[bin]] | ||
| 56 | -name = "gif" | ||
| 57 | -path = "fuzz_targets/gif.rs" | ||
| 58 | -test = false | ||
| 59 | -doc = false | ||
| 60 | -bench = false | ||
| 61 | - | ||
| 62 | -[[bin]] | ||
| 63 | -name = "jpeg" | ||
| 64 | -path = "fuzz_targets/jpeg.rs" | ||
| 65 | -test = false | ||
| 66 | -doc = false | ||
| 67 | -bench = false | ||
| 68 | - | ||
| 69 | -[[bin]] | ||
| 70 | -name = "png" | ||
| 71 | -path = "fuzz_targets/png.rs" | ||
| 72 | -test = false | ||
| 73 | -doc = false | ||
| 74 | -bench = false | ||
| 75 | - | ||
| 76 | -[[bin]] | ||
| 77 | -name = "tiff" | ||
| 78 | -path = "fuzz_targets/tiff.rs" | ||
| 79 | -test = false | ||
| 80 | -doc = false | ||
| 81 | -bench = false | ||
| 82 | - | ||
| 83 | -[[bin]] | ||
| 84 | -name = "webp" | ||
| 85 | -path = "fuzz_targets/webp.rs" | ||
| 86 | -test = false | ||
| 87 | -doc = false | ||
| 88 | -bench = false | ||
| 89 | - | ||
| 90 | [[bin]] | 34 | [[bin]] |
| 91 | name = "probe" | 35 | name = "probe" |
| 92 | path = "fuzz_targets/probe.rs" | 36 | path = "fuzz_targets/probe.rs" |
crates/ec-image/fuzz/fuzz_targets/bmp.rsdeleted+0 -17
| @@ -1,17 +0,0 @@ | |||
| 1 | -#![no_main] | ||
| 2 | - | ||
| 3 | -use ec_image::Limits; | ||
| 4 | -use libfuzzer_sys::fuzz_target; | ||
| 5 | - | ||
| 6 | -// The bmp module's own entry points, called directly so the format signature check in the | ||
| 7 | -// dispatcher does not filter the input first. Header parse, then a decode under small limits. | ||
| 8 | -const LIMITS: Limits = Limits { | ||
| 9 | - max_pixels: 4096 * 4096, | ||
| 10 | - max_alloc: 1 << 26, | ||
| 11 | - max_total_alloc: 1 << 27, | ||
| 12 | -}; | ||
| 13 | - | ||
| 14 | -fuzz_target!(|data: &[u8]| { | ||
| 15 | - let _ = ec_image::bmp::info(data); | ||
| 16 | - let _ = ec_image::bmp::decode(data, LIMITS); | ||
| 17 | -}); | ||
crates/ec-image/fuzz/fuzz_targets/decode_with_limits.rsdeleted+0 -17
| @@ -1,17 +0,0 @@ | |||
| 1 | -#![no_main] | ||
| 2 | - | ||
| 3 | -use ec_image::Limits; | ||
| 4 | -use libfuzzer_sys::fuzz_target; | ||
| 5 | - | ||
| 6 | -// Small limits: 4096x4096 pixels, 64 MiB per buffer, 128 MiB across one call. Under these a | ||
| 7 | -// hostile header is refused before it sizes anything, and every path that multiplies a count by | ||
| 8 | -// a size still gets exercised against a real budget. | ||
| 9 | -const LIMITS: Limits = Limits { | ||
| 10 | - max_pixels: 4096 * 4096, | ||
| 11 | - max_alloc: 1 << 26, | ||
| 12 | - max_total_alloc: 1 << 27, | ||
| 13 | -}; | ||
| 14 | - | ||
| 15 | -fuzz_target!(|data: &[u8]| { | ||
| 16 | - let _ = ec_image::decode_with_limits(data, LIMITS); | ||
| 17 | -}); | ||
crates/ec-image/fuzz/fuzz_targets/gif.rsdeleted+0 -18
| @@ -1,18 +0,0 @@ | |||
| 1 | -#![no_main] | ||
| 2 | - | ||
| 3 | -use ec_image::Limits; | ||
| 4 | -use libfuzzer_sys::fuzz_target; | ||
| 5 | - | ||
| 6 | -// The gif module's own entry points, called directly so the format signature check in the | ||
| 7 | -// dispatcher does not filter the input first. Header parse, then a decode under small limits. | ||
| 8 | -const LIMITS: Limits = Limits { | ||
| 9 | - max_pixels: 4096 * 4096, | ||
| 10 | - max_alloc: 1 << 26, | ||
| 11 | - max_total_alloc: 1 << 27, | ||
| 12 | -}; | ||
| 13 | - | ||
| 14 | -fuzz_target!(|data: &[u8]| { | ||
| 15 | - let _ = ec_image::gif::info(data); | ||
| 16 | - let _ = ec_image::gif::decode(data, LIMITS); | ||
| 17 | - let _ = ec_image::gif::decode_animation(data, LIMITS); | ||
| 18 | -}); | ||
crates/ec-image/fuzz/fuzz_targets/info.rsdeleted+0 -8
| @@ -1,8 +0,0 @@ | |||
| 1 | -#![no_main] | ||
| 2 | - | ||
| 3 | -use libfuzzer_sys::fuzz_target; | ||
| 4 | - | ||
| 5 | -// Header-only parse: dimensions and format details without decoding any pixels. | ||
| 6 | -fuzz_target!(|data: &[u8]| { | ||
| 7 | - let _ = ec_image::info(data); | ||
| 8 | -}); | ||
crates/ec-image/fuzz/fuzz_targets/jpeg.rsdeleted+0 -18
| @@ -1,18 +0,0 @@ | |||
| 1 | -#![no_main] | ||
| 2 | - | ||
| 3 | -use ec_image::Limits; | ||
| 4 | -use libfuzzer_sys::fuzz_target; | ||
| 5 | - | ||
| 6 | -// The jpeg module's own entry points, called directly so the format signature check in the | ||
| 7 | -// dispatcher does not filter the input first. Header parse, then a decode under small limits. | ||
| 8 | -const LIMITS: Limits = Limits { | ||
| 9 | - max_pixels: 4096 * 4096, | ||
| 10 | - max_alloc: 1 << 26, | ||
| 11 | - max_total_alloc: 1 << 27, | ||
| 12 | -}; | ||
| 13 | - | ||
| 14 | -fuzz_target!(|data: &[u8]| { | ||
| 15 | - let _ = ec_image::jpeg::info(data); | ||
| 16 | - let _ = ec_image::jpeg::decode(data, LIMITS); | ||
| 17 | - let _ = ec_image::jpeg::decode_yuv(data, LIMITS); | ||
| 18 | -}); | ||
crates/ec-image/fuzz/fuzz_targets/png.rsdeleted+0 -17
| @@ -1,17 +0,0 @@ | |||
| 1 | -#![no_main] | ||
| 2 | - | ||
| 3 | -use ec_image::Limits; | ||
| 4 | -use libfuzzer_sys::fuzz_target; | ||
| 5 | - | ||
| 6 | -// The png module's own entry points, called directly so the format signature check in the | ||
| 7 | -// dispatcher does not filter the input first. Header parse, then a decode under small limits. | ||
| 8 | -const LIMITS: Limits = Limits { | ||
| 9 | - max_pixels: 4096 * 4096, | ||
| 10 | - max_alloc: 1 << 26, | ||
| 11 | - max_total_alloc: 1 << 27, | ||
| 12 | -}; | ||
| 13 | - | ||
| 14 | -fuzz_target!(|data: &[u8]| { | ||
| 15 | - let _ = ec_image::png::info(data); | ||
| 16 | - let _ = ec_image::png::decode(data, LIMITS); | ||
| 17 | -}); | ||
crates/ec-image/fuzz/fuzz_targets/tiff.rsdeleted+0 -17
| @@ -1,17 +0,0 @@ | |||
| 1 | -#![no_main] | ||
| 2 | - | ||
| 3 | -use ec_image::Limits; | ||
| 4 | -use libfuzzer_sys::fuzz_target; | ||
| 5 | - | ||
| 6 | -// The tiff module's own entry points, called directly so the format signature check in the | ||
| 7 | -// dispatcher does not filter the input first. Header parse, then a decode under small limits. | ||
| 8 | -const LIMITS: Limits = Limits { | ||
| 9 | - max_pixels: 4096 * 4096, | ||
| 10 | - max_alloc: 1 << 26, | ||
| 11 | - max_total_alloc: 1 << 27, | ||
| 12 | -}; | ||
| 13 | - | ||
| 14 | -fuzz_target!(|data: &[u8]| { | ||
| 15 | - let _ = ec_image::tiff::info(data); | ||
| 16 | - let _ = ec_image::tiff::decode(data, LIMITS); | ||
| 17 | -}); | ||
crates/ec-image/fuzz/fuzz_targets/webp.rsdeleted+0 -18
| @@ -1,18 +0,0 @@ | |||
| 1 | -#![no_main] | ||
| 2 | - | ||
| 3 | -use ec_image::Limits; | ||
| 4 | -use libfuzzer_sys::fuzz_target; | ||
| 5 | - | ||
| 6 | -// The webp module's own entry points, called directly so the format signature check in the | ||
| 7 | -// dispatcher does not filter the input first. Header parse, then a decode under small limits. | ||
| 8 | -const LIMITS: Limits = Limits { | ||
| 9 | - max_pixels: 4096 * 4096, | ||
| 10 | - max_alloc: 1 << 26, | ||
| 11 | - max_total_alloc: 1 << 27, | ||
| 12 | -}; | ||
| 13 | - | ||
| 14 | -fuzz_target!(|data: &[u8]| { | ||
| 15 | - let _ = ec_image::webp::info(data); | ||
| 16 | - let _ = ec_image::webp::decode(data, LIMITS); | ||
| 17 | - let _ = ec_image::webp::decode_frames(data, LIMITS); | ||
| 18 | -}); | ||
crates/ec-image/fuzz/seed.shmodified+13 -40
| @@ -1,11 +1,7 @@ | |||
| 1 | #!/usr/bin/env bash | 1 | #!/usr/bin/env bash |
| 2 | # seed.sh: fill fuzz/corpus/<target>/ from the repo's still-image fixtures. | 2 | # seed.sh: fill fuzz/corpus/<target>/ from the repo's still-image fixtures. |
| 3 | # | 3 | # |
| 4 | -# Every file under tests/data/stills (PNG, JPEG, WebP, GIF, BMP, TIFF) seeds the whole-file targets: | 4 | +# Every file under tests/data/stills seeds each whole-file target: decode, decode_animation, probe. |
| 5 | -# decode, decode_with_limits, info, probe, decode_animation. Each format target gets only the files of its | ||
| 6 | -# own format, so its corpus starts on the right signature. The VP8 frames under fixtures/vp8 are | ||
| 7 | -# VP8 bitstreams, not stills, and are not used here. | ||
| 8 | -# | ||
| 9 | # Corpus lives under fuzz/corpus, which is git-ignored. | 5 | # Corpus lives under fuzz/corpus, which is git-ignored. |
| 10 | set -euo pipefail | 6 | set -euo pipefail |
| 11 | 7 | ||
| @@ -14,39 +10,16 @@ STILLS="$FUZZ_DIR/../tests/data/stills" | |||
| 14 | [ -d "$STILLS" ] || { echo "seed.sh: $STILLS missing" >&2; exit 2; } | 10 | [ -d "$STILLS" ] || { echo "seed.sh: $STILLS missing" >&2; exit 2; } |
| 15 | 11 | ||
| 16 | CORPUS="$FUZZ_DIR/corpus" | 12 | CORPUS="$FUZZ_DIR/corpus" |
| 17 | -mkdir -p "$CORPUS"/{decode,decode_with_limits,info,probe,decode_animation,bmp,gif,jpeg,png,tiff,webp} | 13 | +TARGETS=(decode decode_animation probe) |
| 18 | - | 14 | +mkdir -p "${TARGETS[@]/#/$CORPUS/}" |
| 19 | -python3 -I - "$STILLS" "$CORPUS" <<'PY' | ||
| 20 | -import glob, os, sys | ||
| 21 | - | ||
| 22 | -stills, corpus = sys.argv[1], sys.argv[2] | ||
| 23 | -by_format = { | ||
| 24 | - "png": (".png",), "jpeg": (".jpg", ".jpeg"), "webp": (".webp",), | ||
| 25 | - "gif": (".gif",), "bmp": (".bmp",), "tiff": (".tif", ".tiff"), | ||
| 26 | -} | ||
| 27 | -all_files = sorted(p for p in glob.glob(os.path.join(stills, "*")) if os.path.isfile(p)) | ||
| 28 | -if not all_files: | ||
| 29 | - sys.exit("seed.sh: no still-image fixtures found") | ||
| 30 | - | ||
| 31 | -def write(target, name, data): | ||
| 32 | - with open(os.path.join(corpus, target, name), "wb") as f: | ||
| 33 | - f.write(data) | ||
| 34 | - | ||
| 35 | -count = {} | ||
| 36 | -def bump(t): | ||
| 37 | - count[t] = count.get(t, 0) + 1 | ||
| 38 | 15 | ||
| 39 | -for path in all_files: | 16 | +n=0 |
| 40 | - name = os.path.basename(path) | 17 | +for path in "$STILLS"/*; do |
| 41 | - ext = os.path.splitext(name)[1].lower() | 18 | + [ -f "$path" ] || continue |
| 42 | - data = open(path, "rb").read() | 19 | + for t in "${TARGETS[@]}"; do |
| 43 | - for t in ("decode", "decode_with_limits", "info", "probe", "decode_animation"): | 20 | + cp "$path" "$CORPUS/$t/$(basename "$path")" |
| 44 | - write(t, name, data) | 21 | + n=$((n + 1)) |
| 45 | - bump(t) | 22 | + done |
| 46 | - for fmt, exts in by_format.items(): | 23 | +done |
| 47 | - if ext in exts: | 24 | +[ "$n" -gt 0 ] || { echo "seed.sh: no still-image fixtures found" >&2; exit 2; } |
| 48 | - write(fmt, name, data) | 25 | +echo "seeded $n files under $CORPUS" |
| 49 | - bump(fmt) | ||
| 50 | -for t in ("decode", "decode_with_limits", "info", "decode_animation", "bmp", "gif", "jpeg", "png", "tiff", "webp"): | ||
| 51 | - print(f"{t}: {count.get(t, 0)} seeds") | ||
| 52 | -PY | ||
crates/ec-image/src/lib.rsmodified+27 -65
| @@ -333,11 +333,6 @@ fn narrow(v: u16) -> u8 { | |||
| 333 | ((u32::from(v) + 128) / 257) as u8 | 333 | ((u32::from(v) + 128) / 257) as u8 |
| 334 | } | 334 | } |
| 335 | 335 | ||
| 336 | -/// 8-bit sample widened to 16: `v * 65535 / 255`, exact. | ||
| 337 | -fn widen(v: u8) -> u16 { | ||
| 338 | - u16::from(v) * 257 | ||
| 339 | -} | ||
| 340 | - | ||
| 341 | impl Image { | 336 | impl Image { |
| 342 | /// `(width, height)`. | 337 | /// `(width, height)`. |
| 343 | pub fn dimensions(&self) -> (u32, u32) { | 338 | pub fn dimensions(&self) -> (u32, u32) { |
| @@ -404,34 +399,6 @@ impl Image { | |||
| 404 | out | 399 | out |
| 405 | } | 400 | } |
| 406 | 401 | ||
| 407 | - /// Packed 16-bit R,G,B — 8-bit sources widened exactly (`v * 257`). | ||
| 408 | - pub fn to_rgb16(&self) -> Vec<u16> { | ||
| 409 | - match &self.pixels { | ||
| 410 | - Pixels::Rgb16(d) => d.clone(), | ||
| 411 | - Pixels::Rgba16(d) => d.as_chunks::<4>().0.iter().flat_map(|p| p[..3].to_vec()).collect(), | ||
| 412 | - Pixels::L16(d) => d.iter().flat_map(|&l| [l, l, l]).collect(), | ||
| 413 | - Pixels::La16(d) => d.as_chunks::<2>().0.iter().flat_map(|p| [p[0], p[0], p[0]]).collect(), | ||
| 414 | - _ => self.to_rgb8().into_iter().map(widen).collect(), | ||
| 415 | - } | ||
| 416 | - } | ||
| 417 | - | ||
| 418 | - /// Packed 16-bit R,G,B,A; opaque where the source had no alpha. | ||
| 419 | - pub fn to_rgba16(&self) -> Vec<u16> { | ||
| 420 | - match &self.pixels { | ||
| 421 | - Pixels::Rgba16(d) => d.clone(), | ||
| 422 | - Pixels::Rgb16(d) => d | ||
| 423 | - .as_chunks::<3>().0.iter() | ||
| 424 | - .flat_map(|p| [p[0], p[1], p[2], u16::MAX]) | ||
| 425 | - .collect(), | ||
| 426 | - Pixels::L16(d) => d.iter().flat_map(|&l| [l, l, l, u16::MAX]).collect(), | ||
| 427 | - Pixels::La16(d) => d | ||
| 428 | - .as_chunks::<2>().0.iter() | ||
| 429 | - .flat_map(|p| [p[0], p[0], p[0], p[1]]) | ||
| 430 | - .collect(), | ||
| 431 | - _ => self.to_rgba8().into_iter().map(widen).collect(), | ||
| 432 | - } | ||
| 433 | - } | ||
| 434 | - | ||
| 435 | /// The image as an [`ec_core::VideoFrame`], packed RGB8 or RGBA8. | 402 | /// The image as an [`ec_core::VideoFrame`], packed RGB8 or RGBA8. |
| 436 | /// | 403 | /// |
| 437 | /// The natural bridge for a caller that composes stills and decoded video | 404 | /// The natural bridge for a caller that composes stills and decoded video |
| @@ -466,6 +433,15 @@ pub struct Info { | |||
| 466 | pub orientation: u8, | 433 | pub orientation: u8, |
| 467 | } | 434 | } |
| 468 | 435 | ||
| 436 | +fn format_of(data: &[u8]) -> Result<ImageFormat> { | ||
| 437 | + ImageFormat::guess(data).ok_or_else(|| { | ||
| 438 | + Error::unsupported( | ||
| 439 | + "image", | ||
| 440 | + "no PNG, JPEG, WebP, GIF, BMP or TIFF signature at the start of the data", | ||
| 441 | + ) | ||
| 442 | + }) | ||
| 443 | +} | ||
| 444 | + | ||
| 469 | /// Decode `data`, guessing the format from its leading bytes. | 445 | /// Decode `data`, guessing the format from its leading bytes. |
| 470 | pub fn decode(data: &[u8]) -> Result<Image> { | 446 | pub fn decode(data: &[u8]) -> Result<Image> { |
| 471 | decode_with_limits(data, Limits::default()) | 447 | decode_with_limits(data, Limits::default()) |
| @@ -473,17 +449,13 @@ pub fn decode(data: &[u8]) -> Result<Image> { | |||
| 473 | 449 | ||
| 474 | /// [`decode`] with caller-chosen [`Limits`]. | 450 | /// [`decode`] with caller-chosen [`Limits`]. |
| 475 | pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result<Image> { | 451 | pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result<Image> { |
| 476 | - match ImageFormat::guess(data) { | 452 | + match format_of(data)? { |
| 477 | - Some(ImageFormat::Png) => png::decode(data, limits), | 453 | + ImageFormat::Png => png::decode(data, limits), |
| 478 | - Some(ImageFormat::Jpeg) => jpeg::decode(data, limits), | 454 | + ImageFormat::Jpeg => jpeg::decode(data, limits), |
| 479 | - Some(ImageFormat::WebP) => webp::decode(data, limits), | 455 | + ImageFormat::WebP => webp::decode(data, limits), |
| 480 | - Some(ImageFormat::Gif) => gif::decode(data, limits), | 456 | + ImageFormat::Gif => gif::decode(data, limits), |
| 481 | - Some(ImageFormat::Bmp) => bmp::decode(data, limits), | 457 | + ImageFormat::Bmp => bmp::decode(data, limits), |
| 482 | - Some(ImageFormat::Tiff) => tiff::decode(data, limits), | 458 | + ImageFormat::Tiff => tiff::decode(data, limits), |
| 483 | - None => Err(Error::unsupported( | ||
| 484 | - "image", | ||
| 485 | - "no PNG, JPEG, WebP, GIF, BMP or TIFF signature at the start of the data", | ||
| 486 | - )), | ||
| 487 | } | 459 | } |
| 488 | } | 460 | } |
| 489 | 461 | ||
| @@ -493,17 +465,13 @@ pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result<Image> { | |||
| 493 | /// The whole of `data` is read as header. To look at a bounded prefix or a | 465 | /// The whole of `data` is read as header. To look at a bounded prefix or a |
| 494 | /// stream instead, use [`probe`] or [`probe_reader`]. | 466 | /// stream instead, use [`probe`] or [`probe_reader`]. |
| 495 | pub fn info(data: &[u8]) -> Result<Info> { | 467 | pub fn info(data: &[u8]) -> Result<Info> { |
| 496 | - match ImageFormat::guess(data) { | 468 | + match format_of(data)? { |
| 497 | - Some(ImageFormat::Png) => png::info(data), | 469 | + ImageFormat::Png => png::info(data), |
| 498 | - Some(ImageFormat::Jpeg) => jpeg::info(data), | 470 | + ImageFormat::Jpeg => jpeg::info(data), |
| 499 | - Some(ImageFormat::WebP) => webp::info(data), | 471 | + ImageFormat::WebP => webp::info(data), |
| 500 | - Some(ImageFormat::Gif) => gif::info(data), | 472 | + ImageFormat::Gif => gif::info(data), |
| 501 | - Some(ImageFormat::Bmp) => bmp::info(data), | 473 | + ImageFormat::Bmp => bmp::info(data), |
| 502 | - Some(ImageFormat::Tiff) => tiff::info(data), | 474 | + ImageFormat::Tiff => tiff::info(data), |
| 503 | - None => Err(Error::unsupported( | ||
| 504 | - "image", | ||
| 505 | - "no PNG, JPEG, WebP, GIF, BMP or TIFF signature at the start of the data", | ||
| 506 | - )), | ||
| 507 | } | 475 | } |
| 508 | } | 476 | } |
| 509 | 477 | ||
| @@ -535,9 +503,9 @@ pub fn decode_animation(data: &[u8]) -> Result<Vec<AnimationFrame>> { | |||
| 535 | /// The limits bound every frame and the whole composite, so a caller with a | 503 | /// The limits bound every frame and the whole composite, so a caller with a |
| 536 | /// tighter memory budget than the default can lower them here. | 504 | /// tighter memory budget than the default can lower them here. |
| 537 | pub fn decode_animation_with_limits(data: &[u8], limits: Limits) -> Result<Vec<AnimationFrame>> { | 505 | pub fn decode_animation_with_limits(data: &[u8], limits: Limits) -> Result<Vec<AnimationFrame>> { |
| 538 | - match ImageFormat::guess(data) { | 506 | + match format_of(data)? { |
| 539 | - Some(ImageFormat::Gif) => gif::decode_animation(data, limits), | 507 | + ImageFormat::Gif => gif::decode_animation(data, limits), |
| 540 | - Some(ImageFormat::WebP) if webp::is_animated(data) => webp::decode_frames(data, limits), | 508 | + ImageFormat::WebP if webp::is_animated(data) => webp::decode_frames(data, limits), |
| 541 | _ => Ok(vec![AnimationFrame { | 509 | _ => Ok(vec![AnimationFrame { |
| 542 | image: decode_with_limits(data, limits)?, | 510 | image: decode_with_limits(data, limits)?, |
| 543 | delay_num: 0, | 511 | delay_num: 0, |
| @@ -552,12 +520,6 @@ pub fn open(path: impl AsRef<std::path::Path>) -> Result<Image> { | |||
| 552 | decode(&data) | 520 | decode(&data) |
| 553 | } | 521 | } |
| 554 | 522 | ||
| 555 | -/// Read the file at `path` and report its header dimensions. | ||
| 556 | -pub fn open_info(path: impl AsRef<std::path::Path>) -> Result<Info> { | ||
| 557 | - let data = std::fs::read(path).map_err(Error::Io)?; | ||
| 558 | - info(&data) | ||
| 559 | -} | ||
| 560 | - | ||
| 561 | #[cfg(test)] | 523 | #[cfg(test)] |
| 562 | mod tests { | 524 | mod tests { |
| 563 | use super::*; | 525 | use super::*; |
| @@ -582,7 +544,7 @@ mod tests { | |||
| 582 | #[test] | 544 | #[test] |
| 583 | fn sample_conversion_round_trips_through_eight_bits() { | 545 | fn sample_conversion_round_trips_through_eight_bits() { |
| 584 | for v in 0..=255u8 { | 546 | for v in 0..=255u8 { |
| 585 | - assert_eq!(narrow(widen(v)), v, "{v}"); | 547 | + assert_eq!(narrow(u16::from(v) * 257), v, "{v}"); |
| 586 | } | 548 | } |
| 587 | assert_eq!(narrow(0), 0); | 549 | assert_eq!(narrow(0), 0); |
| 588 | assert_eq!(narrow(u16::MAX), 255); | 550 | assert_eq!(narrow(u16::MAX), 255); |
crates/ec-image/tests/fuzz.rsdeleted+0 -774
| @@ -1,774 +0,0 @@ | |||
| 1 | -//! Malformed input never panics, never hangs and never allocates without | ||
| 2 | -//! bound. | ||
| 3 | -//! | ||
| 4 | -//! Ten thousand mutations per format, from a fixed seed so a failure is | ||
| 5 | -//! reproducible: bit flips, truncations, byte injections and pure noise behind | ||
| 6 | -//! each format's signature. Every one of them must come back as `Ok` or as an | ||
| 7 | -//! `Err` — a decoder reached by a file picker is reached by every broken file | ||
| 8 | -//! on the disk. | ||
| 9 | - | ||
| 10 | -use std::alloc::System; | ||
| 11 | -use std::cell::Cell; | ||
| 12 | -use std::sync::Once; | ||
| 13 | - | ||
| 14 | -use tracking_allocator::{AllocationGroupId, AllocationRegistry, AllocationTracker, Allocator}; | ||
| 15 | -use std::path::{Path, PathBuf}; | ||
| 16 | - | ||
| 17 | -/// Counting allocator: the "refused without doing unbounded work" tests | ||
| 18 | -/// below bound that work by *bytes allocated*, not by wall time. A clock is | ||
| 19 | -/// a machine-dependent proxy for exactly the thing those tests care about -- | ||
| 20 | -/// it measures the host's memcpy bandwidth, not the decoder's behaviour -- | ||
| 21 | -/// and it was measured failing that way: the same refused WebP decode takes | ||
| 22 | -/// 0.75-0.89 s on this desktop host and 3.89 s on a server, a 5x spread with | ||
| 23 | -/// byte-identical decoder work, which is what reddened a 2 s ceiling. | ||
| 24 | -/// Lives in the test binary only; the shipped crate has no allocator games. | ||
| 25 | -/// | ||
| 26 | -/// The tally is per-thread, not global: `cargo test` runs these tests in | ||
| 27 | -/// parallel, so a shared counter sums concurrent decodes together and | ||
| 28 | -/// reports work none of them did. | ||
| 29 | -struct CountingAlloc; | ||
| 30 | - | ||
| 31 | -std::thread_local! { | ||
| 32 | - static ALLOC_BYTES: Cell<u64> = const { Cell::new(0) }; | ||
| 33 | -} | ||
| 34 | - | ||
| 35 | -fn count_alloc(size: usize) { | ||
| 36 | - let _ = ALLOC_BYTES.try_with(|b| b.set(b.get() + size as u64)); | ||
| 37 | -} | ||
| 38 | - | ||
| 39 | -impl AllocationTracker for CountingAlloc { | ||
| 40 | - fn allocated(&self, _addr: usize, object_size: usize, _wrapped: usize, _g: AllocationGroupId) { | ||
| 41 | - count_alloc(object_size); | ||
| 42 | - } | ||
| 43 | - fn deallocated( | ||
| 44 | - &self, | ||
| 45 | - _addr: usize, | ||
| 46 | - _object_size: usize, | ||
| 47 | - _wrapped: usize, | ||
| 48 | - _source: AllocationGroupId, | ||
| 49 | - _current: AllocationGroupId, | ||
| 50 | - ) { | ||
| 51 | - } | ||
| 52 | -} | ||
| 53 | - | ||
| 54 | -#[global_allocator] | ||
| 55 | -static ALLOC: Allocator<System> = Allocator::system(); | ||
| 56 | - | ||
| 57 | -/// Installs the tracker once. Realloc reaches the tracker as an allocation of | ||
| 58 | -/// the new size, which is the accounting this file has always used. | ||
| 59 | -fn install_counter() { | ||
| 60 | - static ONCE: Once = Once::new(); | ||
| 61 | - ONCE.call_once(|| { | ||
| 62 | - let _ = AllocationRegistry::set_global_tracker(CountingAlloc); | ||
| 63 | - AllocationRegistry::enable_tracking(); | ||
| 64 | - }); | ||
| 65 | -} | ||
| 66 | - | ||
| 67 | -/// Runs `f` on this thread and returns its value together with every byte | ||
| 68 | -/// that thread allocated while it ran. That count is the decoder's own | ||
| 69 | -/// work, independent of how fast the host is at moving those bytes around. | ||
| 70 | -fn counting_allocations<T>(f: impl FnOnce() -> T) -> (T, u64) { | ||
| 71 | - install_counter(); | ||
| 72 | - ALLOC_BYTES.with(|b| b.set(0)); | ||
| 73 | - let out = f(); | ||
| 74 | - (out, ALLOC_BYTES.with(Cell::get)) | ||
| 75 | -} | ||
| 76 | - | ||
| 77 | -/// Serializes the tests that allocate up to the decoder's whole budget. | ||
| 78 | -/// | ||
| 79 | -/// Those tests each decode a near-limit canvas, so run together they need | ||
| 80 | -/// several GiB at once and the per-scope memory cap (`scripts/memguard-runner.sh`) | ||
| 81 | -/// SIGKILLs the test binary. One at a time they fit. The lock covers only | ||
| 82 | -/// those tests; the cheap ones stay parallel. A poisoned lock (a failed | ||
| 83 | -/// assertion in another heavy test) is recovered, so one failure does not | ||
| 84 | -/// cascade into spurious failures in the rest. | ||
| 85 | -/// | ||
| 86 | -/// The counting allocator needs no lock for its numbers: its tally is | ||
| 87 | -/// per-thread, so serializing does not change what any test measures. | ||
| 88 | -static HEAVY: std::sync::Mutex<()> = std::sync::Mutex::new(()); | ||
| 89 | - | ||
| 90 | -fn heavy() -> std::sync::MutexGuard<'static, ()> { | ||
| 91 | - HEAVY.lock().unwrap_or_else(|e| e.into_inner()) | ||
| 92 | -} | ||
| 93 | - | ||
| 94 | -/// Limits for the tests that run up to the total budget: 1 GiB total and 512 MiB per buffer. | ||
| 95 | -/// | ||
| 96 | -/// The default total (4 GiB) would need about 4 GiB resident before the refusal, which is past | ||
| 97 | -/// the 3500M memory cap on the lane servers. These limits keep the same behaviour (a total | ||
| 98 | -/// budget, a per-buffer cap) at a size the cap can hold. | ||
| 99 | -/// | ||
| 100 | -/// Also used by the mutation sweeps, which test robustness rather than the default limit values. | ||
| 101 | -/// | ||
| 102 | -/// The tests' canvases are 4000x2000 RGBA (32,000,000 bytes), which does not divide the 1 GiB | ||
| 103 | -/// total evenly. A canvas that did (say 4096x2048, 2^25 bytes) lets the last clone that fits | ||
| 104 | -/// land exactly on the budget, and the test's own small allocations then push the measured | ||
| 105 | -/// total a few kilobytes past it. | ||
| 106 | -fn budget_limits() -> ec_image::Limits { | ||
| 107 | - ec_image::Limits { | ||
| 108 | - max_total_alloc: 1 << 30, | ||
| 109 | - max_alloc: 1 << 29, | ||
| 110 | - ..ec_image::Limits::default() | ||
| 111 | - } | ||
| 112 | -} | ||
| 113 | - | ||
| 114 | -const ROUNDS: usize = 10_000; | ||
| 115 | - | ||
| 116 | -fn fixtures() -> PathBuf { | ||
| 117 | - Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/stills") | ||
| 118 | -} | ||
| 119 | - | ||
| 120 | -/// xorshift64*, so every run mutates the same way. | ||
| 121 | -struct Rng(u64); | ||
| 122 | - | ||
| 123 | -impl Rng { | ||
| 124 | - fn next(&mut self) -> u64 { | ||
| 125 | - self.0 ^= self.0 << 13; | ||
| 126 | - self.0 ^= self.0 >> 7; | ||
| 127 | - self.0 ^= self.0 << 17; | ||
| 128 | - self.0 | ||
| 129 | - } | ||
| 130 | - | ||
| 131 | - fn below(&mut self, bound: usize) -> usize { | ||
| 132 | - (self.next() % bound.max(1) as u64) as usize | ||
| 133 | - } | ||
| 134 | -} | ||
| 135 | - | ||
| 136 | -/// One mutated copy of `seed`: a few bit flips, a truncation, or an injection. | ||
| 137 | -/// | ||
| 138 | -/// `head` bounds where the flips land. Aiming them at the first few dozen | ||
| 139 | -/// bytes is what actually reaches the geometry and colour-type paths: spread | ||
| 140 | -/// over a whole file they nearly all land in the compressed data and stop at | ||
| 141 | -/// the first integrity check. | ||
| 142 | -fn mutate(rng: &mut Rng, seed: &[u8], head: Option<usize>) -> Vec<u8> { | ||
| 143 | - let mut data = seed.to_vec(); | ||
| 144 | - let region = head.unwrap_or(data.len()).min(data.len()); | ||
| 145 | - match rng.below(4) { | ||
| 146 | - 0 => { | ||
| 147 | - for _ in 0..1 + rng.below(8) { | ||
| 148 | - let at = rng.below(region); | ||
| 149 | - data[at] ^= 1 << rng.below(8); | ||
| 150 | - } | ||
| 151 | - } | ||
| 152 | - 1 => data.truncate(rng.below(data.len())), | ||
| 153 | - 2 => { | ||
| 154 | - for _ in 0..1 + rng.below(16) { | ||
| 155 | - let at = rng.below(region); | ||
| 156 | - data[at] = (rng.next() & 0xff) as u8; | ||
| 157 | - } | ||
| 158 | - } | ||
| 159 | - _ => { | ||
| 160 | - // Keep the signature, replace the body with noise: this is the | ||
| 161 | - // shape that exercises header fields hardest. | ||
| 162 | - let keep = 12.min(data.len()); | ||
| 163 | - data.truncate(keep); | ||
| 164 | - for _ in 0..rng.below(400) { | ||
| 165 | - data.push((rng.next() & 0xff) as u8); | ||
| 166 | - } | ||
| 167 | - } | ||
| 168 | - } | ||
| 169 | - data | ||
| 170 | -} | ||
| 171 | - | ||
| 172 | -/// Recompute every chunk CRC of a mutated PNG. | ||
| 173 | -/// | ||
| 174 | -/// Without this the checksum catches every mutation at the door and the | ||
| 175 | -/// decoder proper is never fuzzed at all — the sweep would prove only that | ||
| 176 | -/// CRC-32 works. | ||
| 177 | -fn repair_png_crcs(data: &mut [u8]) { | ||
| 178 | - let mut at = 8usize; | ||
| 179 | - while at + 12 <= data.len() { | ||
| 180 | - let len = u32::from_be_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]) as usize; | ||
| 181 | - if len > data.len() || at + 12 + len > data.len() { | ||
| 182 | - return; | ||
| 183 | - } | ||
| 184 | - let crc = crc32(&data[at + 4..at + 8 + len]); | ||
| 185 | - data[at + 8 + len..at + 12 + len].copy_from_slice(&crc.to_be_bytes()); | ||
| 186 | - at += 12 + len; | ||
| 187 | - } | ||
| 188 | -} | ||
| 189 | - | ||
| 190 | -fn sweep(name: &str, seed_file: &str) { | ||
| 191 | - // Mutated headers can claim canvases up to the budget, so a sweep is heavy too. | ||
| 192 | - let _heavy = heavy(); | ||
| 193 | - let seed = std::fs::read(fixtures().join(seed_file)).unwrap(); | ||
| 194 | - let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ name.len() as u64); | ||
| 195 | - let mut decoded = 0usize; | ||
| 196 | - for round in 0..ROUNDS { | ||
| 197 | - // Half the rounds aim at the header, half at the whole file. | ||
| 198 | - let head = if round % 2 == 0 { Some(48) } else { None }; | ||
| 199 | - let mut data = mutate(&mut rng, &seed, head); | ||
| 200 | - if seed_file.ends_with(".png") { | ||
| 201 | - repair_png_crcs(&mut data); | ||
| 202 | - } | ||
| 203 | - // The call is the assertion: a panic here fails the test with the | ||
| 204 | - // round number, and the round number plus the fixed seed reproduces it. | ||
| 205 | - if let Ok(image) = ec_image::decode_with_limits(&data, budget_limits()) { | ||
| 206 | - decoded += 1; | ||
| 207 | - let pixels = image.to_rgba8(); | ||
| 208 | - assert_eq!( | ||
| 209 | - pixels.len(), | ||
| 210 | - (image.width as usize) * (image.height as usize) * 4, | ||
| 211 | - "{name} round {round}: buffer does not match the dimensions" | ||
| 212 | - ); | ||
| 213 | - } | ||
| 214 | - // Header-only parsing must survive the same input. | ||
| 215 | - let _ = ec_image::info(&data); | ||
| 216 | - } | ||
| 217 | - eprintln!("{name}: {ROUNDS} mutations, {decoded} still decoded"); | ||
| 218 | -} | ||
| 219 | - | ||
| 220 | -/// Single-seed sweeps: (old test name, format label, seed fixture). Each was a #[test] | ||
| 221 | -/// of its own; they run as one table so the mutation loop is written once. | ||
| 222 | -const SWEEPS: &[(&str, &str, &str)] = &[ | ||
| 223 | - ("png_survives_mutation", "png", "tiny.png"), | ||
| 224 | - ("jpeg_survives_mutation", "jpeg", "tiny.jpg"), | ||
| 225 | - ("webp_lossy_survives_mutation", "webp-lossy", "tiny-lossy.webp"), | ||
| 226 | - ("webp_lossless_survives_mutation", "webp-lossless", "tiny-lossless.webp"), | ||
| 227 | - ("gif_survives_mutation", "gif", "tiny.gif"), | ||
| 228 | - // BMP sizes three separate things from header fields -- a palette, a row | ||
| 229 | - // stride and, for the run-length compressions, a decoded row buffer -- so a | ||
| 230 | - // mutation can put any two of them in disagreement. | ||
| 231 | - ("bmp_survives_mutation", "bmp", "tiny.bmp"), | ||
| 232 | - // The run-length path is the one that writes at a position the *file* chooses | ||
| 233 | - // (delta codes move the cursor), so it gets its own seed. | ||
| 234 | - ("a_run_length_bmp_survives_mutation", "bmp-rle", "rle8.bmp"), | ||
| 235 | - // TIFF is a directory of offsets into itself: a mutation can point a strip, | ||
| 236 | - // a palette or the directory's own continuation anywhere in the file. | ||
| 237 | - ("tiff_survives_mutation", "tiff", "tiny.tiff"), | ||
| 238 | - // The compressed, predicted path decodes into a row buffer whose length comes | ||
| 239 | - // from tags the mutation is free to disagree about, so it gets its own seed. | ||
| 240 | - ("a_compressed_tiff_survives_mutation", "tiff-lzw", "rgb8-lzw-pred.tiff"), | ||
| 241 | -]; | ||
| 242 | - | ||
| 243 | -#[test] | ||
| 244 | -fn single_seed_sweeps_survive_mutation() { | ||
| 245 | - // Scoped threads, as the separate #[test]s ran in parallel. `heavy()` still serializes the sweeps. | ||
| 246 | - let failures: Vec<&str> = std::thread::scope(|s| { | ||
| 247 | - let handles: Vec<_> = SWEEPS | ||
| 248 | - .iter() | ||
| 249 | - .map(|&(test, name, seed)| (test, s.spawn(move || sweep(name, seed)))) | ||
| 250 | - .collect(); | ||
| 251 | - handles | ||
| 252 | - .into_iter() | ||
| 253 | - .filter_map(|(test, h)| h.join().is_err().then_some(test)) | ||
| 254 | - .collect() | ||
| 255 | - }); | ||
| 256 | - assert!(failures.is_empty(), "failed cases: {failures:?}"); | ||
| 257 | -} | ||
| 258 | - | ||
| 259 | -/// The animation path has its own frame loop, its own canvas and its own | ||
| 260 | -/// disposal state machine, none of which `decode` reaches past frame one. | ||
| 261 | -#[test] | ||
| 262 | -fn a_gif_animation_survives_mutation() { | ||
| 263 | - let seed = std::fs::read(fixtures().join("animated.gif")).unwrap(); | ||
| 264 | - let _heavy = heavy(); | ||
| 265 | - let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ 0x9e37); | ||
| 266 | - let mut decoded = 0usize; | ||
| 267 | - for round in 0..ROUNDS { | ||
| 268 | - let head = if round % 2 == 0 { Some(48) } else { None }; | ||
| 269 | - let data = mutate(&mut rng, &seed, head); | ||
| 270 | - if let Ok(frames) = ec_image::decode_animation_with_limits(&data, budget_limits()) { | ||
| 271 | - decoded += 1; | ||
| 272 | - for frame in &frames { | ||
| 273 | - let image = &frame.image; | ||
| 274 | - assert_eq!( | ||
| 275 | - image.to_rgba8().len(), | ||
| 276 | - (image.width as usize) * (image.height as usize) * 4, | ||
| 277 | - "gif-animation round {round}: buffer does not match the dimensions" | ||
| 278 | - ); | ||
| 279 | - } | ||
| 280 | - } | ||
| 281 | - } | ||
| 282 | - eprintln!("gif-animation: {ROUNDS} mutations, {decoded} still decoded"); | ||
| 283 | -} | ||
| 284 | - | ||
| 285 | -/// The WebP animation path parses its own ANMF headers and composites onto a | ||
| 286 | -/// canvas sized by a different chunk, so a mutation can make the two disagree. | ||
| 287 | -#[test] | ||
| 288 | -fn an_animated_webp_survives_mutation() { | ||
| 289 | - let seed = std::fs::read(fixtures().join("anim-alpha.webp")).unwrap(); | ||
| 290 | - let _heavy = heavy(); | ||
| 291 | - let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ 0x5eed); | ||
| 292 | - let mut decoded = 0usize; | ||
| 293 | - for round in 0..ROUNDS { | ||
| 294 | - let head = if round % 2 == 0 { Some(48) } else { None }; | ||
| 295 | - let data = mutate(&mut rng, &seed, head); | ||
| 296 | - if let Ok(frames) = ec_image::decode_animation_with_limits(&data, budget_limits()) { | ||
| 297 | - decoded += 1; | ||
| 298 | - for frame in &frames { | ||
| 299 | - let image = &frame.image; | ||
| 300 | - assert_eq!( | ||
| 301 | - image.to_rgba8().len(), | ||
| 302 | - (image.width as usize) * (image.height as usize) * 4, | ||
| 303 | - "webp-animation round {round}: buffer does not match the dimensions" | ||
| 304 | - ); | ||
| 305 | - } | ||
| 306 | - } | ||
| 307 | - } | ||
| 308 | - eprintln!("webp-animation: {ROUNDS} mutations, {decoded} still decoded"); | ||
| 309 | -} | ||
| 310 | - | ||
| 311 | -#[test] | ||
| 312 | -fn arbitrary_bytes_behind_a_signature_are_refused_not_believed() { | ||
| 313 | - let signatures: [&[u8]; 6] = [ | ||
| 314 | - &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a], | ||
| 315 | - &[0xff, 0xd8, 0xff, 0xe0], | ||
| 316 | - b"RIFF\x40\x00\x00\x00WEBPVP8 ", | ||
| 317 | - b"GIF89a", | ||
| 318 | - // A TIFF header whose directory offset is inside the header itself. | ||
| 319 | - b"II\x2a\x00\x04\x00\x00\x00", | ||
| 320 | - // "BM" alone is two bytes anything could start with, so the guess also | ||
| 321 | - // asks the file header to agree with itself: this prefix declares a | ||
| 322 | - // 40-byte info header and pixels at 54, which is what makes the bytes | ||
| 323 | - // behind it reach the decoder at all. | ||
| 324 | - b"BM\x00\x10\x00\x00\x00\x00\x00\x00\x36\x00\x00\x00\x28\x00\x00\x00", | ||
| 325 | - ]; | ||
| 326 | - let _heavy = heavy(); | ||
| 327 | - let mut rng = Rng(0x9e37_79b9_7f4a_7c15); | ||
| 328 | - for signature in signatures { | ||
| 329 | - for _ in 0..ROUNDS / 4 { | ||
| 330 | - let mut data = signature.to_vec(); | ||
| 331 | - for _ in 0..rng.below(200) { | ||
| 332 | - data.push((rng.next() & 0xff) as u8); | ||
| 333 | - } | ||
| 334 | - let _ = ec_image::decode_with_limits(&data, budget_limits()); | ||
| 335 | - let _ = ec_image::info(&data); | ||
| 336 | - } | ||
| 337 | - } | ||
| 338 | -} | ||
| 339 | - | ||
| 340 | -#[test] | ||
| 341 | -fn a_header_asking_for_more_pixels_than_the_limit_is_refused() { | ||
| 342 | - // A PNG IHDR claiming 65535x65535 is 4 gigapixels: the limit must refuse | ||
| 343 | - // it before any buffer is sized from those numbers. | ||
| 344 | - let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]; | ||
| 345 | - let mut ihdr = Vec::new(); | ||
| 346 | - ihdr.extend_from_slice(&65535u32.to_be_bytes()); | ||
| 347 | - ihdr.extend_from_slice(&65535u32.to_be_bytes()); | ||
| 348 | - ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); | ||
| 349 | - png.extend_from_slice(&(ihdr.len() as u32).to_be_bytes()); | ||
| 350 | - let start = png.len(); | ||
| 351 | - png.extend_from_slice(b"IHDR"); | ||
| 352 | - png.extend_from_slice(&ihdr); | ||
| 353 | - let crc = crc32(&png[start..]); | ||
| 354 | - png.extend_from_slice(&crc.to_be_bytes()); | ||
| 355 | - let err = ec_image::decode(&png).expect_err("4 gigapixels is past the limit"); | ||
| 356 | - assert!(format!("{err}").contains("limit"), "{err}"); | ||
| 357 | -} | ||
| 358 | - | ||
| 359 | -/// LSB-first bit packer, matching how every decoder in this crate reads a | ||
| 360 | -/// GIF LZW or VP8L bitstream: used to hand-craft the smallest possible valid | ||
| 361 | -/// compressed payload for the budget tests below. | ||
| 362 | -struct BitWriter { | ||
| 363 | - buffer: u64, | ||
| 364 | - bits: u8, | ||
| 365 | - out: Vec<u8>, | ||
| 366 | -} | ||
| 367 | - | ||
| 368 | -impl BitWriter { | ||
| 369 | - fn new() -> Self { | ||
| 370 | - BitWriter { | ||
| 371 | - buffer: 0, | ||
| 372 | - bits: 0, | ||
| 373 | - out: Vec::new(), | ||
| 374 | - } | ||
| 375 | - } | ||
| 376 | - | ||
| 377 | - fn push(&mut self, value: u16, width: u8) { | ||
| 378 | - self.buffer |= u64::from(value) << self.bits; | ||
| 379 | - self.bits += width; | ||
| 380 | - while self.bits >= 8 { | ||
| 381 | - self.out.push((self.buffer & 0xff) as u8); | ||
| 382 | - self.buffer >>= 8; | ||
| 383 | - self.bits -= 8; | ||
| 384 | - } | ||
| 385 | - } | ||
| 386 | - | ||
| 387 | - fn finish(mut self) -> Vec<u8> { | ||
| 388 | - if self.bits > 0 { | ||
| 389 | - self.out.push((self.buffer & 0xff) as u8); | ||
| 390 | - } | ||
| 391 | - self.out | ||
| 392 | - } | ||
| 393 | -} | ||
| 394 | - | ||
| 395 | -/// A minimal GIF: no global colour table, one 0x2C image descriptor with a | ||
| 396 | -/// 2-colour local table and a one-pixel LZW stream (clear, colour 0, end), | ||
| 397 | -/// followed by the trailer. `canvas_w`/`canvas_h` size the logical screen; | ||
| 398 | -/// the frame itself is always 1x1 so its own indices buffer is trivial — | ||
| 399 | -/// what grows per frame is the *composited canvas* `composite` clones. | ||
| 400 | -fn one_pixel_gif(canvas_w: u16, canvas_h: u16, frames: usize) -> Vec<u8> { | ||
| 401 | - let mut w = BitWriter::new(); | ||
| 402 | - w.push(4, 3); // clear code (min_code_size 2 -> clear = 1<<2) | ||
| 403 | - w.push(0, 3); // colour index 0, literal | ||
| 404 | - w.push(5, 3); // end code | ||
| 405 | - let lzw = w.finish(); | ||
| 406 | - | ||
| 407 | - let mut data = Vec::new(); | ||
| 408 | - data.extend_from_slice(b"GIF87a"); | ||
| 409 | - data.extend_from_slice(&canvas_w.to_le_bytes()); | ||
| 410 | - data.extend_from_slice(&canvas_h.to_le_bytes()); | ||
| 411 | - data.push(0x00); // no global colour table | ||
| 412 | - data.push(0); | ||
| 413 | - data.push(0); | ||
| 414 | - for _ in 0..frames { | ||
| 415 | - data.push(0x2C); | ||
| 416 | - data.extend_from_slice(&0u16.to_le_bytes()); // left | ||
| 417 | - data.extend_from_slice(&0u16.to_le_bytes()); // top | ||
| 418 | - data.extend_from_slice(&1u16.to_le_bytes()); // width | ||
| 419 | - data.extend_from_slice(&1u16.to_le_bytes()); // height | ||
| 420 | - data.push(0x80); // has LCT, sorted=0, size field 0 -> 2 colours | ||
| 421 | - data.extend_from_slice(&[0, 0, 0, 255, 255, 255]); // 2-colour LCT | ||
| 422 | - data.push(2); // min code size | ||
| 423 | - data.push(lzw.len() as u8); | ||
| 424 | - data.extend_from_slice(&lzw); | ||
| 425 | - data.push(0); // sub-block terminator | ||
| 426 | - } | ||
| 427 | - data.push(0x3B); // trailer | ||
| 428 | - data | ||
| 429 | -} | ||
| 430 | - | ||
| 431 | -#[test] | ||
| 432 | -fn a_gif_frame_asking_for_more_pixels_than_the_limit_is_refused() { | ||
| 433 | - // A single 0x2C image descriptor declaring a 60000x60000 frame: the | ||
| 434 | - // frame's own rectangle is a header field like the canvas is, and must | ||
| 435 | - // be refused before it sizes the indices buffer below it. | ||
| 436 | - let mut data = Vec::new(); | ||
| 437 | - data.extend_from_slice(b"GIF87a"); | ||
| 438 | - data.extend_from_slice(&4u16.to_le_bytes()); | ||
| 439 | - data.extend_from_slice(&4u16.to_le_bytes()); | ||
| 440 | - data.push(0x00); | ||
| 441 | - data.push(0); | ||
| 442 | - data.push(0); | ||
| 443 | - data.push(0x2C); | ||
| 444 | - data.extend_from_slice(&0u16.to_le_bytes()); | ||
| 445 | - data.extend_from_slice(&0u16.to_le_bytes()); | ||
| 446 | - data.extend_from_slice(&60000u16.to_le_bytes()); | ||
| 447 | - data.extend_from_slice(&60000u16.to_le_bytes()); | ||
| 448 | - data.push(0x00); | ||
| 449 | - | ||
| 450 | - // Bounded by bytes, not by a clock: this refusal happens before the | ||
| 451 | - // frame sizes anything at all, so the whole decode is a few hundred | ||
| 452 | - // bytes of header parsing (measured: 421 B in 2.6 us) whatever the host's | ||
| 453 | - // speed. The old 100 ms clock was a machine-dependent proxy for that. | ||
| 454 | - let (err, allocated) = counting_allocations(|| { | ||
| 455 | - ec_image::decode_animation(&data).expect_err("60000x60000 frame is past the limit") | ||
| 456 | - }); | ||
| 457 | - assert!(format!("{err}").contains("limit"), "{err}"); | ||
| 458 | - assert!( | ||
| 459 | - allocated <= 64 * 1024, | ||
| 460 | - "a header-only refusal allocated {allocated} bytes; it must refuse before sizing the frame" | ||
| 461 | - ); | ||
| 462 | -} | ||
| 463 | - | ||
| 464 | -#[test] | ||
| 465 | -fn a_gif_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget() { | ||
| 466 | - let _heavy = heavy(); | ||
| 467 | - // Each frame is 1x1 -- cheap to encode, cheap to check on its own -- but | ||
| 468 | - // `composite` clones the *whole* canvas onto the result once per frame. | ||
| 469 | - // A canvas near the single-buffer limit, repeated a few dozen times, | ||
| 470 | - // must be caught by the decode-wide budget even though no single frame | ||
| 471 | - // or single buffer ever looks large by itself. | ||
| 472 | - let data = one_pixel_gif(4000, 2000, 64); | ||
| 473 | - // A few real canvas clones run before the budget catches up (the budget | ||
| 474 | - // is spent per frame, so it can't refuse before at least one clone), so | ||
| 475 | - // this bounds "the decoder's own total budget, not a byte more", not "no | ||
| 476 | - // allocation at all". Bytes, not a clock -- see the counting allocator | ||
| 477 | - // above. | ||
| 478 | - let limits = budget_limits(); | ||
| 479 | - let budget = limits.max_total_alloc as u64; | ||
| 480 | - let (err, allocated) = counting_allocations(|| { | ||
| 481 | - ec_image::decode_animation_with_limits(&data, limits) | ||
| 482 | - .expect_err("64 clones of a near-limit canvas is past the total budget") | ||
| 483 | - }); | ||
| 484 | - assert!(format!("{err}").contains("limit"), "{err}"); | ||
| 485 | - assert!( | ||
| 486 | - allocated <= budget, | ||
| 487 | - "refused decode allocated {allocated} bytes, past the {budget}-byte total budget" | ||
| 488 | - ); | ||
| 489 | - | ||
| 490 | - // Size-relative, and the half that pins the guard: 64x the frames in the | ||
| 491 | - // file must not buy 64x the work. A budget spent per *input* frame, or | ||
| 492 | - // after the clone instead of before it, refuses later or not at all as | ||
| 493 | - // the frame count grows. | ||
| 494 | - let bomb = one_pixel_gif(4000, 2000, 4096); | ||
| 495 | - let (err, allocated) = counting_allocations(|| { | ||
| 496 | - ec_image::decode_animation_with_limits(&bomb, limits) | ||
| 497 | - .expect_err("4096 clones of a near-limit canvas is past the total budget") | ||
| 498 | - }); | ||
| 499 | - assert!(format!("{err}").contains("limit"), "{err}"); | ||
| 500 | - assert!( | ||
| 501 | - allocated <= budget, | ||
| 502 | - "a 64x larger file allocated {allocated} bytes, past the {budget}-byte total budget" | ||
| 503 | - ); | ||
| 504 | -} | ||
| 505 | - | ||
| 506 | -#[test] | ||
| 507 | -fn a_gif_with_a_few_tiny_frames_over_a_huge_canvas_still_decodes() { | ||
| 508 | - let _heavy = heavy(); | ||
| 509 | - // The other side of the same budget: a handful of frames over a large | ||
| 510 | - // canvas is exactly what a real animation looks like, and must not be | ||
| 511 | - // refused just because the guard above exists. | ||
| 512 | - let data = one_pixel_gif(4000, 4000, 3); | ||
| 513 | - let frames = ec_image::decode_animation_with_limits(&data, budget_limits()) | ||
| 514 | - .expect("well within every limit"); | ||
| 515 | - assert_eq!(frames.len(), 3); | ||
| 516 | -} | ||
| 517 | - | ||
| 518 | -/// A minimal RIFF WebP with an ANIM/VP8X header and `frames` ANMF chunks, | ||
| 519 | -/// each carrying a 1x1 VP8L payload (the smallest valid lossless image: a | ||
| 520 | -/// bitstream header plus one pixel, no transforms, no colour cache). | ||
| 521 | -fn one_pixel_animated_webp(canvas_w: u32, canvas_h: u32, frames: usize) -> Vec<u8> { | ||
| 522 | - // VP8L bitstream for a 1x1 image: signature 0x2f, 14-bit width-1=0, | ||
| 523 | - // 14-bit height-1=0, 1-bit alpha flag=0, 3-bit version=0, then the | ||
| 524 | - // image data: no colour cache, no meta prefix, one simple prefix code | ||
| 525 | - // per channel (colour index 0 for all four), then the single pixel. | ||
| 526 | - let mut w = BitWriter::new(); | ||
| 527 | - w.push(0, 14); // width - 1 | ||
| 528 | - w.push(0, 14); // height - 1 | ||
| 529 | - w.push(0, 1); // alpha_is_used | ||
| 530 | - w.push(0, 3); // version | ||
| 531 | - w.push(0, 1); // no transform | ||
| 532 | - w.push(0, 1); // no colour cache | ||
| 533 | - w.push(0, 1); // no meta prefix | ||
| 534 | - for _ in 0..5 { | ||
| 535 | - // green/red/blue/alpha/distance, in that order: a simple code, one | ||
| 536 | - // symbol, value 0. | ||
| 537 | - w.push(1, 1); // simple code | ||
| 538 | - w.push(0, 1); // one symbol | ||
| 539 | - w.push(0, 1); // symbol is not a literal byte read as 8 bits | ||
| 540 | - w.push(0, 1); // symbol0 = 0 | ||
| 541 | - } | ||
| 542 | - let vp8l_bits = w.finish(); | ||
| 543 | - let mut vp8l = vec![0x2f]; | ||
| 544 | - vp8l.extend_from_slice(&vp8l_bits); | ||
| 545 | - if vp8l.len() % 2 == 1 { | ||
| 546 | - vp8l.push(0); | ||
| 547 | - } | ||
| 548 | - | ||
| 549 | - fn chunk(tag: &[u8; 4], body: &[u8]) -> Vec<u8> { | ||
| 550 | - let mut c = Vec::new(); | ||
| 551 | - c.extend_from_slice(tag); | ||
| 552 | - c.extend_from_slice(&(body.len() as u32).to_le_bytes()); | ||
| 553 | - c.extend_from_slice(body); | ||
| 554 | - if body.len() % 2 == 1 { | ||
| 555 | - c.push(0); | ||
| 556 | - } | ||
| 557 | - c | ||
| 558 | - } | ||
| 559 | - | ||
| 560 | - let mut vp8x = vec![0x02, 0, 0, 0]; // flags: bit 0x02 is "has animation" | ||
| 561 | - let off24 = |v: u32| v.to_le_bytes()[..3].to_vec(); | ||
| 562 | - let dim24 = |v: u32| (v - 1).to_le_bytes()[..3].to_vec(); | ||
| 563 | - vp8x.extend_from_slice(&dim24(canvas_w)); | ||
| 564 | - vp8x.extend_from_slice(&dim24(canvas_h)); | ||
| 565 | - let mut anim = vec![0, 0, 0, 0, 0, 0]; // background colour | ||
| 566 | - anim.extend_from_slice(&0u16.to_le_bytes()); // loop count | ||
| 567 | - | ||
| 568 | - let mut anmf_body = Vec::new(); | ||
| 569 | - anmf_body.extend_from_slice(&off24(0)); // x offset (raw value, x = field*2) | ||
| 570 | - anmf_body.extend_from_slice(&off24(0)); // y offset | ||
| 571 | - anmf_body.extend_from_slice(&dim24(1)); // width - 1 | ||
| 572 | - anmf_body.extend_from_slice(&dim24(1)); // height - 1 | ||
| 573 | - anmf_body.extend_from_slice(&off24(1)); // duration | ||
| 574 | - anmf_body.push(0x00); // reserved/blend/dispose | ||
| 575 | - anmf_body.extend_from_slice(&chunk(b"VP8L", &vp8l)); | ||
| 576 | - | ||
| 577 | - let mut payload = Vec::new(); | ||
| 578 | - payload.extend_from_slice(&chunk(b"VP8X", &vp8x)); | ||
| 579 | - payload.extend_from_slice(&chunk(b"ANIM", &anim)); | ||
| 580 | - for _ in 0..frames { | ||
| 581 | - payload.extend_from_slice(&chunk(b"ANMF", &anmf_body)); | ||
| 582 | - } | ||
| 583 | - | ||
| 584 | - let mut data = Vec::new(); | ||
| 585 | - data.extend_from_slice(b"RIFF"); | ||
| 586 | - data.extend_from_slice(&(4 + payload.len() as u32).to_le_bytes()); | ||
| 587 | - data.extend_from_slice(b"WEBP"); | ||
| 588 | - data.extend_from_slice(&payload); | ||
| 589 | - data | ||
| 590 | -} | ||
| 591 | - | ||
| 592 | -#[test] | ||
| 593 | -fn a_webp_animation_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget() { | ||
| 594 | - let _heavy = heavy(); | ||
| 595 | - // The WebP analogue of the GIF test above: `decode_frames` clones the | ||
| 596 | - // whole composited canvas into the result once per ANMF chunk. | ||
| 597 | - // | ||
| 598 | - // The bound here is *bytes*, not a clock. What this protects against is | ||
| 599 | - // a guard that stops refusing and lets the clone multiplier run -- 64 | ||
| 600 | - // frames over this canvas is 64 GiB of compositing -- and a clock cannot | ||
| 601 | - // express that: it measures the host's memcpy bandwidth, measured at | ||
| 602 | - // 0.75-0.89 s on this desktop host against 3.89 s on a server for | ||
| 603 | - // byte-identical decoder work, which is what reddened the old 2 s | ||
| 604 | - // ceiling. | ||
| 605 | - // | ||
| 606 | - // The byte bound is an INDEPENDENT measurement, not the guard's own | ||
| 607 | - // tally: `AllocBudget::spend` sums DECLARED byte counts at chosen call | ||
| 608 | - // sites, while `counting_allocations` sums the ACTUAL `layout.size()` of | ||
| 609 | - // every allocation (and every realloc's full new size, so an | ||
| 610 | - // incrementally grown Vec contributes more than its final size), plus the | ||
| 611 | - // refusal's own formatting inside the measured window. So "refused at the | ||
| 612 | - // budget" does NOT by itself mean "allocated no more than the budget" -- | ||
| 613 | - // and this test's red proof (one clone moved past the spend -> 5.12e9 | ||
| 614 | - // bytes against the 4.29e9 budget) is exactly the check that the two | ||
| 615 | - // stay close enough for the budget to be a meaningful ceiling. | ||
| 616 | - let limits = budget_limits(); | ||
| 617 | - let budget = limits.max_total_alloc as u64; | ||
| 618 | - let data = one_pixel_animated_webp(4000, 2000, 64); | ||
| 619 | - let (err, allocated) = counting_allocations(|| { | ||
| 620 | - ec_image::decode_animation_with_limits(&data, limits) | ||
| 621 | - .expect_err("64 clones of a near-limit canvas is past the total budget") | ||
| 622 | - }); | ||
| 623 | - assert!(format!("{err}").contains("limit"), "{err}"); | ||
| 624 | - assert!( | ||
| 625 | - allocated <= budget, | ||
| 626 | - "the refused decode allocated {allocated} bytes, past the {budget}-byte total budget" | ||
| 627 | - ); | ||
| 628 | - | ||
| 629 | - // Size-relative, and the half that pins the guard: 64x the frames in | ||
| 630 | - // the file must not buy 64x the work. A budget spent per *input* frame, | ||
| 631 | - // or after the clone instead of before it, refuses later or not at all | ||
| 632 | - // as the frame count grows -- and no clock can tell those apart, since | ||
| 633 | - // the work is the same order either way. | ||
| 634 | - let bomb = one_pixel_animated_webp(4000, 2000, 4096); | ||
| 635 | - assert!( | ||
| 636 | - bomb.len() > data.len() * 16, | ||
| 637 | - "the second input is meant to be far larger: {} vs {} bytes", | ||
| 638 | - bomb.len(), | ||
| 639 | - data.len() | ||
| 640 | - ); | ||
| 641 | - let (err, allocated) = counting_allocations(|| { | ||
| 642 | - ec_image::decode_animation_with_limits(&bomb, limits) | ||
| 643 | - .expect_err("4096 clones of a near-limit canvas is past the total budget") | ||
| 644 | - }); | ||
| 645 | - assert!(format!("{err}").contains("limit"), "{err}"); | ||
| 646 | - assert!( | ||
| 647 | - allocated <= budget, | ||
| 648 | - "a 64x larger file allocated {allocated} bytes, past the {budget}-byte total budget" | ||
| 649 | - ); | ||
| 650 | -} | ||
| 651 | - | ||
| 652 | -/// Build an LZW-compressed data stream that keeps expanding after the | ||
| 653 | -/// dictionary itself has stopped growing: a run of `cScSc` codes (each equal | ||
| 654 | -/// to the not-yet-assigned `next_code`) fills the 4096-entry dictionary with | ||
| 655 | -/// entries of increasing length, then a run of plain references to the | ||
| 656 | -/// longest entry keeps emitting ~4 KB of output per 12-bit code with no | ||
| 657 | -/// further dictionary growth to bound it. This is the classic GIF LZW bomb: | ||
| 658 | -/// a stream well under 200 KB that decodes, uncapped, to hundreds of | ||
| 659 | -/// megabytes. | ||
| 660 | -fn lzw_bomb() -> Vec<u8> { | ||
| 661 | - let min_code_size = 2u8; | ||
| 662 | - let clear_code = 1u16 << min_code_size; // 4 | ||
| 663 | - let end_code = clear_code + 1; // 5 | ||
| 664 | - let mut next_code = clear_code + 2; // 6 | ||
| 665 | - let mut code_size = min_code_size + 1; // 3 | ||
| 666 | - | ||
| 667 | - let mut w = BitWriter::new(); | ||
| 668 | - w.push(clear_code, code_size); | ||
| 669 | - w.push(0, code_size); // first code after clear: a literal, no dictionary entry | ||
| 670 | - | ||
| 671 | - // Phase 1: cScSc every time -- fills the dictionary, entries growing | ||
| 672 | - // 2, 3, 4, ... bytes long (mirrors `Lzw::derive`'s widening rule exactly, | ||
| 673 | - // so the decoder reads this stream at the same code width we wrote it). | ||
| 674 | - while next_code < 4096 { | ||
| 675 | - w.push(next_code, code_size); | ||
| 676 | - if next_code >= (1u16 << code_size) - 1 && code_size < 12 { | ||
| 677 | - code_size += 1; | ||
| 678 | - } | ||
| 679 | - next_code += 1; | ||
| 680 | - } | ||
| 681 | - | ||
| 682 | - // Phase 2: dictionary is full (`derive` is now a no-op), so repeating the | ||
| 683 | - // longest entry's code keeps producing ~4 KB per code with nothing left | ||
| 684 | - // to cap it. | ||
| 685 | - let longest = next_code - 1; | ||
| 686 | - for _ in 0..100_000 { | ||
| 687 | - w.push(longest, code_size); | ||
| 688 | - } | ||
| 689 | - | ||
| 690 | - w.push(end_code, code_size); | ||
| 691 | - w.finish() | ||
| 692 | -} | ||
| 693 | - | ||
| 694 | -/// A GIF whose frame declares 4x4 (16 indices) but whose LZW stream, if | ||
| 695 | -/// decoded past that point, expands to hundreds of megabytes: guards the | ||
| 696 | -/// `lzw_decode` bound at gif.rs that stops the loop once `out` already holds | ||
| 697 | -/// `expected` bytes, rather than only checking after the loop. | ||
| 698 | -#[test] | ||
| 699 | -fn a_gif_lzw_bomb_does_not_expand_past_its_declared_frame() { | ||
| 700 | - let _heavy = heavy(); | ||
| 701 | - let lzw = lzw_bomb(); | ||
| 702 | - eprintln!("gif-lzw-bomb: {} bytes of LZW data", lzw.len()); | ||
| 703 | - | ||
| 704 | - let mut data = Vec::new(); | ||
| 705 | - data.extend_from_slice(b"GIF87a"); | ||
| 706 | - data.extend_from_slice(&4u16.to_le_bytes()); | ||
| 707 | - data.extend_from_slice(&4u16.to_le_bytes()); | ||
| 708 | - data.push(0x00); // no global colour table | ||
| 709 | - data.push(0); | ||
| 710 | - data.push(0); | ||
| 711 | - data.push(0x2C); | ||
| 712 | - data.extend_from_slice(&0u16.to_le_bytes()); // left | ||
| 713 | - data.extend_from_slice(&0u16.to_le_bytes()); // top | ||
| 714 | - data.extend_from_slice(&4u16.to_le_bytes()); // width | ||
| 715 | - data.extend_from_slice(&4u16.to_le_bytes()); // height | ||
| 716 | - data.push(0x81); // has LCT, size field 1 -> 4 colours (indices 0..3) | ||
| 717 | - data.extend_from_slice(&[0, 0, 0, 64, 64, 64, 128, 128, 128, 255, 255, 255]); | ||
| 718 | - data.push(2); // min code size | ||
| 719 | - for chunk in lzw.chunks(255) { | ||
| 720 | - data.push(chunk.len() as u8); | ||
| 721 | - data.extend_from_slice(chunk); | ||
| 722 | - } | ||
| 723 | - data.push(0); // sub-block terminator | ||
| 724 | - data.push(0x3B); // trailer | ||
| 725 | - | ||
| 726 | - // The frame declares 4x4, so the decoder may hold 16 indices, a 4-colour | ||
| 727 | - // palette and a 4x4 canvas -- kilobytes at most. Unbounded expansion is | ||
| 728 | - // hundreds of megabytes. Bytes, not a clock: the same clock-versus-bytes | ||
| 729 | - // split as the budget tests above, and here the signal is much larger | ||
| 730 | - // than any host's speed difference. | ||
| 731 | - let (_out, allocated) = | ||
| 732 | - counting_allocations(|| ec_image::decode_with_limits(&data, budget_limits())); | ||
| 733 | - assert!( | ||
| 734 | - allocated <= 1 << 20, | ||
| 735 | - "a 4x4 GIF frame allocated {allocated} bytes; the LZW stream expanded past its frame" | ||
| 736 | - ); | ||
| 737 | -} | ||
| 738 | - | ||
| 739 | -/// The plain entry point must apply `Limits::default()`, and the limits must bind. | ||
| 740 | -/// | ||
| 741 | -/// A canvas just over the default `max_alloc` cannot be built: `max_pixels` caps the canvas at | ||
| 742 | -/// exactly `max_alloc` bytes, so the total budget is the first limit a GIF canvas can cross. | ||
| 743 | -#[test] | ||
| 744 | -fn decode_animation_applies_the_default_limits() { | ||
| 745 | - let data = one_pixel_gif(2, 2, 2); | ||
| 746 | - let plain = ec_image::decode_animation(&data).expect("two frames within the default limits"); | ||
| 747 | - let explicit = ec_image::decode_animation_with_limits(&data, ec_image::Limits::default()) | ||
| 748 | - .expect("the same two frames"); | ||
| 749 | - assert_eq!(plain, explicit); | ||
| 750 | - | ||
| 751 | - let tiny = ec_image::Limits { | ||
| 752 | - max_total_alloc: 1, | ||
| 753 | - ..ec_image::Limits::default() | ||
| 754 | - }; | ||
| 755 | - assert!( | ||
| 756 | - ec_image::decode_animation_with_limits(&data, tiny).is_err(), | ||
| 757 | - "a one-byte total budget must refuse the same file" | ||
| 758 | - ); | ||
| 759 | -} | ||
| 760 | - | ||
| 761 | -fn crc32(data: &[u8]) -> u32 { | ||
| 762 | - let mut c = 0xffff_ffffu32; | ||
| 763 | - for &b in data { | ||
| 764 | - c ^= u32::from(b); | ||
| 765 | - for _ in 0..8 { | ||
| 766 | - c = if c & 1 != 0 { | ||
| 767 | - 0xedb8_8320 ^ (c >> 1) | ||
| 768 | - } else { | ||
| 769 | - c >> 1 | ||
| 770 | - }; | ||
| 771 | - } | ||
| 772 | - } | ||
| 773 | - c ^ 0xffff_ffff | ||
| 774 | -} | ||
crates/ec-image/tests/it/differential.rsmodified+12 -1
| @@ -85,6 +85,17 @@ fn psnr(a: &[u8], b: &[u8]) -> f64 { | |||
| 85 | } | 85 | } |
| 86 | } | 86 | } |
| 87 | 87 | ||
| 88 | +fn rgba16(img: &ec_image::Image) -> Vec<u16> { | ||
| 89 | + use ec_image::Pixels; | ||
| 90 | + match &img.pixels { | ||
| 91 | + Pixels::L16(d) => d.iter().flat_map(|&l| [l, l, l, u16::MAX]).collect(), | ||
| 92 | + Pixels::La16(d) => d.as_chunks::<2>().0.iter().flat_map(|p| [p[0], p[0], p[0], p[1]]).collect(), | ||
| 93 | + Pixels::Rgb16(d) => d.as_chunks::<3>().0.iter().flat_map(|p| [p[0], p[1], p[2], u16::MAX]).collect(), | ||
| 94 | + Pixels::Rgba16(d) => d.clone(), | ||
| 95 | + _ => unreachable!("only called for 16-bit pictures"), | ||
| 96 | + } | ||
| 97 | +} | ||
| 98 | + | ||
| 88 | #[test] | 99 | #[test] |
| 89 | fn png_decodes_pixel_exactly() { | 100 | fn png_decodes_pixel_exactly() { |
| 90 | let files = corpus("png"); | 101 | let files = corpus("png"); |
| @@ -102,7 +113,7 @@ fn png_decodes_pixel_exactly() { | |||
| 102 | if ours.pixels.bit_depth() == 16 { | 113 | if ours.pixels.bit_depth() == 16 { |
| 103 | // Compared at 16 bits so the comparison is not laundered through | 114 | // Compared at 16 bits so the comparison is not laundered through |
| 104 | // two different 16-to-8 rounding conventions. | 115 | // two different 16-to-8 rounding conventions. |
| 105 | - let a = ours.to_rgba16(); | 116 | + let a = rgba16(&ours); |
| 106 | let b = theirs.to_rgba16().into_raw(); | 117 | let b = theirs.to_rgba16().into_raw(); |
| 107 | assert_eq!(a, b, "{} (16-bit samples)", path.display()); | 118 | assert_eq!(a, b, "{} (16-bit samples)", path.display()); |
| 108 | } else { | 119 | } else { |
crates/ec-inflate/examples/bench.rsdeleted+0 -69
| @@ -1,69 +0,0 @@ | |||
| 1 | -//! bench: zlib inflate rows for lanes/bench.md ("lane benchrest"). | ||
| 2 | -//! | ||
| 3 | -//! usage: | ||
| 4 | -//! bench zlib <in.zlib> <out.bin> [reps] | ||
| 5 | -//! bench blocks <in.blocks> <out.bin> [reps] | ||
| 6 | -//! | ||
| 7 | -//! `zlib` inflates one zlib stream with `inflate_zlib`, `reps` times (default 5), and keeps the | ||
| 8 | -//! best wall time. `blocks` reads a sequence of `[u32 little-endian length][zlib stream]` records | ||
| 9 | -//! (one per subtitle-sized packet) and inflates every record with `inflate_zlib`, timing the whole | ||
| 10 | -//! loop. Both write the concatenated output of the last pass to `<out.bin>`, untimed, for the md5 | ||
| 11 | -//! check against python's `zlib.decompress`. | ||
| 12 | -use std::hint::black_box; | ||
| 13 | -use std::time::Instant; | ||
| 14 | - | ||
| 15 | -/// Output ceiling passed to every call: far above the inputs used here, but not "no ceiling". | ||
| 16 | -const LIMIT: usize = 1 << 30; | ||
| 17 | - | ||
| 18 | -fn split_blocks(data: &[u8]) -> Vec<&[u8]> { | ||
| 19 | - let mut out = Vec::new(); | ||
| 20 | - let mut at = 0usize; | ||
| 21 | - while at < data.len() { | ||
| 22 | - let len = u32::from_le_bytes(data[at..at + 4].try_into().expect("4 bytes")) as usize; | ||
| 23 | - at += 4; | ||
| 24 | - out.push(&data[at..at + len]); | ||
| 25 | - at += len; | ||
| 26 | - } | ||
| 27 | - out | ||
| 28 | -} | ||
| 29 | - | ||
| 30 | -fn main() { | ||
| 31 | - let args: Vec<String> = std::env::args().collect(); | ||
| 32 | - match args.get(1).map(String::as_str) { | ||
| 33 | - Some(mode @ ("zlib" | "blocks")) if args.len() >= 4 => { | ||
| 34 | - let reps: usize = args.get(4).map_or(5, |s| s.parse().expect("reps")); | ||
| 35 | - assert!(reps >= 1, "reps must be at least 1"); | ||
| 36 | - let data = std::fs::read(&args[2]).expect("read input"); | ||
| 37 | - let blocks = if mode == "blocks" { split_blocks(&data) } else { Vec::new() }; | ||
| 38 | - let mut best = f64::MAX; | ||
| 39 | - let mut out = Vec::new(); | ||
| 40 | - for _ in 0..reps { | ||
| 41 | - let t = Instant::now(); | ||
| 42 | - out = Vec::new(); | ||
| 43 | - if mode == "zlib" { | ||
| 44 | - out = ec_inflate::inflate_zlib(black_box(&data), LIMIT).expect("inflate"); | ||
| 45 | - } else { | ||
| 46 | - for b in &blocks { | ||
| 47 | - let v = ec_inflate::inflate_zlib(black_box(b), LIMIT).expect("inflate block"); | ||
| 48 | - out.extend_from_slice(&v); | ||
| 49 | - } | ||
| 50 | - } | ||
| 51 | - best = best.min(t.elapsed().as_secs_f64()); | ||
| 52 | - } | ||
| 53 | - std::fs::write(&args[3], &out).expect("write output"); | ||
| 54 | - let streams = if mode == "blocks" { blocks.len() } else { 1 }; | ||
| 55 | - println!( | ||
| 56 | - "mode={mode} streams={streams} in_bytes={} out_bytes={} best_inflate_s={best:.4} mb_per_s={:.2} reps={reps}", | ||
| 57 | - data.len(), | ||
| 58 | - out.len(), | ||
| 59 | - out.len() as f64 / best / 1e6 | ||
| 60 | - ); | ||
| 61 | - } | ||
| 62 | - _ => { | ||
| 63 | - eprintln!( | ||
| 64 | - "usage: bench zlib <in.zlib> <out.bin> [reps]\n bench blocks <in.blocks> <out.bin> [reps]" | ||
| 65 | - ); | ||
| 66 | - std::process::exit(2); | ||
| 67 | - } | ||
| 68 | - } | ||
| 69 | -} | ||
crates/ec-inflate/fuzz/fuzz_targets/inflate_diff.rsmodified+3 -2
| @@ -1,6 +1,6 @@ | |||
| 1 | #![no_main] | 1 | #![no_main] |
| 2 | 2 | ||
| 3 | -use ec_inflate::{inflate, inflate_zlib}; | 3 | +use ec_inflate::{Format, inflate_into, inflate_zlib}; |
| 4 | use libfuzzer_sys::fuzz_target; | 4 | use libfuzzer_sys::fuzz_target; |
| 5 | 5 | ||
| 6 | const LIMIT: usize = 16 << 20; | 6 | const LIMIT: usize = 16 << 20; |
| @@ -12,8 +12,9 @@ fuzz_target!(|data: &[u8]| { | |||
| 12 | return; | 12 | return; |
| 13 | }; | 13 | }; |
| 14 | let (ours, theirs) = if sel & 1 == 0 { | 14 | let (ours, theirs) = if sel & 1 == 0 { |
| 15 | + let mut out = Vec::new(); | ||
| 15 | ( | 16 | ( |
| 16 | - inflate(body, LIMIT), | 17 | + inflate_into(body, &mut out, LIMIT, Format::Raw).map(|()| out), |
| 17 | miniz_oxide::inflate::decompress_to_vec_with_limit(body, LIMIT), | 18 | miniz_oxide::inflate::decompress_to_vec_with_limit(body, LIMIT), |
| 18 | ) | 19 | ) |
| 19 | } else { | 20 | } else { |
crates/ec-inflate/fuzz/fuzz_targets/inflate_raw.rsmodified+2 -2
| @@ -1,9 +1,9 @@ | |||
| 1 | #![no_main] | 1 | #![no_main] |
| 2 | 2 | ||
| 3 | -use ec_inflate::inflate; | 3 | +use ec_inflate::{Format, inflate_into}; |
| 4 | use libfuzzer_sys::fuzz_target; | 4 | use libfuzzer_sys::fuzz_target; |
| 5 | 5 | ||
| 6 | // Whole input is one raw DEFLATE stream, capped at 16 MiB of output. | 6 | // Whole input is one raw DEFLATE stream, capped at 16 MiB of output. |
| 7 | fuzz_target!(|data: &[u8]| { | 7 | fuzz_target!(|data: &[u8]| { |
| 8 | - let _ = inflate(data, 16 << 20); | 8 | + let _ = inflate_into(data, &mut Vec::new(), 16 << 20, Format::Raw); |
| 9 | }); | 9 | }); |
crates/ec-inflate/src/bits.rsmodified+2 -2
| @@ -39,8 +39,8 @@ impl<'a> Bits<'a> { | |||
| 39 | /// most symbols. | 39 | /// most symbols. |
| 40 | #[inline] | 40 | #[inline] |
| 41 | pub(crate) fn refill(&mut self) { | 41 | pub(crate) fn refill(&mut self) { |
| 42 | - if let Some(next) = self.src.get(self.pos..self.pos + 8) { | 42 | + if let Some(next) = self.src.get(self.pos..).and_then(<[u8]>::first_chunk::<8>) { |
| 43 | - let bytes = u64::from_le_bytes(next.try_into().expect("an eight byte slice")); | 43 | + let bytes = u64::from_le_bytes(*next); |
| 44 | self.buf |= bytes << self.count; | 44 | self.buf |= bytes << self.count; |
| 45 | self.pos += ((63 - self.count) >> 3) as usize; | 45 | self.pos += ((63 - self.count) >> 3) as usize; |
| 46 | self.count |= 56; | 46 | self.count |= 56; |
crates/ec-inflate/src/deflate.rsmodified+6 -1
| @@ -205,7 +205,7 @@ fn stored_blocks(input: &[u8]) -> Vec<u8> { | |||
| 205 | #[cfg(test)] | 205 | #[cfg(test)] |
| 206 | mod tests { | 206 | mod tests { |
| 207 | use super::*; | 207 | use super::*; |
| 208 | - use crate::{inflate, inflate_zlib}; | 208 | + use crate::inflate_zlib; |
| 209 | 209 | ||
| 210 | fn pseudo_random(n: usize, seed: u32) -> Vec<u8> { | 210 | fn pseudo_random(n: usize, seed: u32) -> Vec<u8> { |
| 211 | let mut s = seed; | 211 | let mut s = seed; |
| @@ -217,6 +217,11 @@ mod tests { | |||
| 217 | .collect() | 217 | .collect() |
| 218 | } | 218 | } |
| 219 | 219 | ||
| 220 | + fn inflate(raw: &[u8], limit: usize) -> Result<Vec<u8>, crate::Error> { | ||
| 221 | + let mut out = Vec::new(); | ||
| 222 | + crate::inflate_into(raw, &mut out, limit, crate::Format::Raw).map(|()| out) | ||
| 223 | + } | ||
| 224 | + | ||
| 220 | #[test] | 225 | #[test] |
| 221 | fn empty_and_tiny_inputs_round_trip() { | 226 | fn empty_and_tiny_inputs_round_trip() { |
| 222 | for input in [&b""[..], b"a", b"ab", b"abc", b"abcabcabc"] { | 227 | for input in [&b""[..], b"a", b"ab", b"abc", b"abcabcabc"] { |
crates/ec-inflate/src/lib.rsmodified+8 -17
| @@ -1,9 +1,9 @@ | |||
| 1 | //! DEFLATE (RFC 1951) and zlib (RFC 1950) decompression. | 1 | //! DEFLATE (RFC 1951) and zlib (RFC 1950) decompression. |
| 2 | //! | 2 | //! |
| 3 | -//! Two entry points, both one-shot over a complete buffer: [`inflate`] for a | 3 | +//! Two entry points, both one-shot over a complete buffer: [`inflate_zlib`] for a |
| 4 | -//! raw DEFLATE stream (what PNG's `IDAT` chain and Matroska header stripping | 4 | +//! zlib stream, header checked and Adler-32 verified, and [`inflate_into`] for |
| 5 | -//! hand over) and [`inflate_zlib`] for the same thing inside a zlib wrapper, | 5 | +//! either wrapper, with [`Format::Raw`] for a bare DEFLATE stream (what |
| 6 | -//! header checked and Adler-32 verified. | 6 | +//! Matroska header stripping hands over). |
| 7 | //! | 7 | //! |
| 8 | //! Contracts worth knowing before implementing against this crate: | 8 | //! Contracts worth knowing before implementing against this crate: |
| 9 | //! | 9 | //! |
| @@ -117,13 +117,6 @@ pub enum Format { | |||
| 117 | Zlib, | 117 | Zlib, |
| 118 | } | 118 | } |
| 119 | 119 | ||
| 120 | -/// Decompress a raw DEFLATE stream, producing at most `limit` bytes. | ||
| 121 | -pub fn inflate(input: &[u8], limit: usize) -> Result<Vec<u8>, Error> { | ||
| 122 | - let mut out = Vec::new(); | ||
| 123 | - inflate_into(input, &mut out, limit, Format::Raw)?; | ||
| 124 | - Ok(out) | ||
| 125 | -} | ||
| 126 | - | ||
| 127 | /// Decompress a zlib stream, producing at most `limit` bytes. | 120 | /// Decompress a zlib stream, producing at most `limit` bytes. |
| 128 | /// | 121 | /// |
| 129 | /// The two header bytes are checked and the Adler-32 trailer is verified | 122 | /// The two header bytes are checked and the Adler-32 trailer is verified |
| @@ -153,13 +146,11 @@ pub fn inflate_into( | |||
| 153 | let mut bits = Bits::new(body); | 146 | let mut bits = Bits::new(body); |
| 154 | let end = inflate::blocks(&mut bits, out, limit)?; | 147 | let end = inflate::blocks(&mut bits, out, limit)?; |
| 155 | if format == Format::Zlib { | 148 | if format == Format::Zlib { |
| 156 | - let trailer: [u8; 4] = body | 149 | + let trailer = body |
| 157 | .get(end..) | 150 | .get(end..) |
| 158 | - .and_then(|rest| rest.get(..4)) | 151 | + .and_then(<[u8]>::first_chunk::<4>) |
| 159 | - .ok_or(Error::Truncated)? | 152 | + .ok_or(Error::Truncated)?; |
| 160 | - .try_into() | 153 | + let expected = u32::from_be_bytes(*trailer); |
| 161 | - .expect("a four byte slice"); | ||
| 162 | - let expected = u32::from_be_bytes(trailer); | ||
| 163 | let actual = adler32(&out[start..]); | 154 | let actual = adler32(&out[start..]); |
| 164 | if expected != actual { | 155 | if expected != actual { |
| 165 | return Err(Error::Adler32Mismatch { expected, actual }); | 156 | return Err(Error::Adler32Mismatch { expected, actual }); |
crates/ec-inflate/tests/inflate.rsmodified+6 -1
| @@ -7,12 +7,17 @@ | |||
| 7 | 7 | ||
| 8 | use std::io::Write; | 8 | use std::io::Write; |
| 9 | 9 | ||
| 10 | -use ec_inflate::{Error, Format, inflate, inflate_into, inflate_zlib}; | 10 | +use ec_inflate::{Error, Format, inflate_into, inflate_zlib}; |
| 11 | use flate2::Compression; | 11 | use flate2::Compression; |
| 12 | use flate2::write::{DeflateEncoder, ZlibEncoder}; | 12 | use flate2::write::{DeflateEncoder, ZlibEncoder}; |
| 13 | 13 | ||
| 14 | const NO_LIMIT: usize = usize::MAX; | 14 | const NO_LIMIT: usize = usize::MAX; |
| 15 | 15 | ||
| 16 | +fn inflate(input: &[u8], limit: usize) -> Result<Vec<u8>, Error> { | ||
| 17 | + let mut out = Vec::new(); | ||
| 18 | + inflate_into(input, &mut out, limit, Format::Raw).map(|()| out) | ||
| 19 | +} | ||
| 20 | + | ||
| 16 | /// xorshift64*, so the "random" inputs are the same on every run. | 21 | /// xorshift64*, so the "random" inputs are the same on every run. |
| 17 | fn pseudo_random(seed: u64, len: usize) -> Vec<u8> { | 22 | fn pseudo_random(seed: u64, len: usize) -> Vec<u8> { |
| 18 | let mut state = seed | 1; | 23 | let mut state = seed | 1; |