use crate::convert::{
ConvertPolicy, RawImage, convert_from_raw, convert_from_raw_into, premultiply_alpha,
unpremultiply_alpha,
};
use crate::{ColorModel, Dimensions, ErrorKind, ImageBuf, Pixel, PixelFormat, Sample};
type Engine<S, Q> = fn(RawImage<'_, S>, ConvertPolicy) -> crate::Result<ImageBuf<Q>>;
type IntoEngine<S, Q> =
fn(RawImage<'_, S>, ConvertPolicy, &mut [<Q as Pixel>::Sample]) -> crate::Result<()>;
pub const MAX_EDGE: u32 = 32;
pub const NARROW_FORMATS: [PixelFormat; 7] = [
PixelFormat::Gray8,
PixelFormat::Bilevel,
PixelFormat::Indexed8,
PixelFormat::Rgb8,
PixelFormat::Rgba8,
PixelFormat::Cmyk8,
PixelFormat::GrayAlpha8,
];
pub const WIDE_FORMATS: [PixelFormat; 4] = [
PixelFormat::Gray16,
PixelFormat::Rgb16,
PixelFormat::Rgba16,
PixelFormat::GrayAlpha16,
];
#[must_use]
pub fn normalise_dims(width: u32, height: u32) -> (u32, u32) {
(width % MAX_EDGE + 1, height % MAX_EDGE + 1)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Violation {
law: &'static str,
detail: String,
}
impl Violation {
fn new(law: &'static str, detail: String) -> Self {
Self { law, detail }
}
#[must_use]
pub fn law(&self) -> &'static str {
self.law
}
#[must_use]
pub fn detail(&self) -> &str {
&self.detail
}
}
impl core::fmt::Display for Violation {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}: {}", self.law, self.detail)
}
}
pub fn acceptance_is_independent_of_the_samples<S: Sample, Q: Pixel>(
format: PixelFormat,
dims: Dimensions,
first: &[S],
second: &[S],
policy: ConvertPolicy,
) -> Result<(), Violation> {
acceptance_is_independent_of_the_samples_under(
convert_from_raw::<S, Q>,
format,
dims,
first,
second,
policy,
)
}
fn acceptance_is_independent_of_the_samples_under<S: Sample, Q: Pixel>(
engine: Engine<S, Q>,
format: PixelFormat,
dims: Dimensions,
first: &[S],
second: &[S],
policy: ConvertPolicy,
) -> Result<(), Violation> {
const LAW: &str = "acceptance_is_independent_of_the_samples";
let (Ok(a), Ok(b)) = (
RawImage::<S>::new(first, format, dims),
RawImage::<S>::new(second, format, dims),
) else {
return Ok(());
};
let first_ok = engine(a, policy).is_ok();
let second_ok = engine(b, policy).is_ok();
if first_ok == second_ok {
Ok(())
} else {
Err(Violation::new(
LAW,
format!(
"{format:?} -> {:?}: one sample buffer was accepted and another refused",
Q::FORMAT
),
))
}
}
pub fn output_shape_matches_the_target_layout<S: Sample, Q: Pixel>(
format: PixelFormat,
dims: Dimensions,
samples: &[S],
policy: ConvertPolicy,
) -> Result<(), Violation> {
output_shape_matches_the_target_layout_under(
convert_from_raw::<S, Q>,
format,
dims,
samples,
policy,
)
}
fn output_shape_matches_the_target_layout_under<S: Sample, Q: Pixel>(
engine: Engine<S, Q>,
format: PixelFormat,
dims: Dimensions,
samples: &[S],
policy: ConvertPolicy,
) -> Result<(), Violation> {
const LAW: &str = "output_shape_matches_the_target_layout";
let Ok(src) = RawImage::<S>::new(samples, format, dims) else {
return Ok(());
};
let Ok(out) = engine(src, policy) else {
return Ok(());
};
if out.dimensions() != dims {
return Err(Violation::new(
LAW,
format!(
"{format:?} -> {:?}: dimensions {:?} became {:?}",
Q::FORMAT,
dims,
out.dimensions()
),
));
}
let want = dims
.sample_count(Q::CHANNELS)
.expect("dimensions are bounded by MAX_EDGE, so the product cannot overflow");
if out.as_samples().len() != want {
return Err(Violation::new(
LAW,
format!(
"{format:?} -> {:?}: expected {want} samples, got {}",
Q::FORMAT,
out.as_samples().len()
),
));
}
Ok(())
}
pub fn converting_a_layout_to_itself_changes_nothing<P: Pixel>(
dims: Dimensions,
samples: &[P::Sample],
policy: ConvertPolicy,
) -> Result<(), Violation> {
converting_a_layout_to_itself_changes_nothing_under::<P>(
convert_from_raw::<P::Sample, P>,
dims,
samples,
policy,
)
}
fn converting_a_layout_to_itself_changes_nothing_under<P: Pixel>(
engine: Engine<P::Sample, P>,
dims: Dimensions,
samples: &[P::Sample],
policy: ConvertPolicy,
) -> Result<(), Violation> {
const LAW: &str = "converting_a_layout_to_itself_changes_nothing";
let Ok(src) = RawImage::<P::Sample>::new(samples, P::FORMAT, dims) else {
return Ok(());
};
let out = match engine(src, policy) {
Ok(out) => out,
Err(error) => {
return Err(Violation::new(
LAW,
format!("{:?} -> itself was refused: {error}", P::FORMAT),
));
}
};
if out.as_samples() == samples {
Ok(())
} else {
Err(Violation::new(
LAW,
format!("{:?} -> itself altered the samples", P::FORMAT),
))
}
}
pub fn palette_and_cmyk_convert_only_to_themselves<S: Sample, Q: Pixel>(
format: PixelFormat,
dims: Dimensions,
samples: &[S],
policy: ConvertPolicy,
) -> Result<(), Violation> {
const LAW: &str = "palette_and_cmyk_convert_only_to_themselves";
let closed = |f: PixelFormat| matches!(f, PixelFormat::Indexed8 | PixelFormat::Cmyk8);
if !(closed(format) || closed(Q::FORMAT)) || format == Q::FORMAT {
return Ok(());
}
let Ok(src) = RawImage::<S>::new(samples, format, dims) else {
return Ok(());
};
match convert_from_raw::<S, Q>(src, policy) {
Ok(_) => Err(Violation::new(
LAW,
format!("{format:?} -> {:?} was accepted", Q::FORMAT),
)),
Err(error) if error.kind() == ErrorKind::Unsupported => Ok(()),
Err(error) => Err(Violation::new(
LAW,
format!(
"{format:?} -> {:?} was refused as {:?}, not Unsupported",
Q::FORMAT,
error.kind()
),
)),
}
}
pub fn the_in_place_door_matches_the_allocating_door<S: Sample, Q: Pixel>(
format: PixelFormat,
dims: Dimensions,
samples: &[S],
policy: ConvertPolicy,
) -> Result<(), Violation> {
the_in_place_door_matches_the_allocating_door_under(
convert_from_raw::<S, Q>,
convert_from_raw_into::<S, Q>,
format,
dims,
samples,
policy,
)
}
fn the_in_place_door_matches_the_allocating_door_under<S: Sample, Q: Pixel>(
allocating: Engine<S, Q>,
into: IntoEngine<S, Q>,
format: PixelFormat,
dims: Dimensions,
samples: &[S],
policy: ConvertPolicy,
) -> Result<(), Violation> {
const LAW: &str = "the_in_place_door_matches_the_allocating_door";
let (Ok(a), Ok(b)) = (
RawImage::<S>::new(samples, format, dims),
RawImage::<S>::new(samples, format, dims),
) else {
return Ok(());
};
let allocated = allocating(a, policy);
let Some(want) = dims.sample_count(Q::CHANNELS) else {
return Ok(());
};
let mut storage: Vec<Q::Sample> = vec![Q::Sample::default(); want];
let in_place = into(b, policy, &mut storage);
match (allocated, in_place) {
(Ok(out), Ok(())) => {
if out.as_samples() == storage.as_slice() {
Ok(())
} else {
Err(Violation::new(
LAW,
format!(
"{format:?} -> {:?}: the two doors wrote different samples",
Q::FORMAT
),
))
}
}
(Err(_), Err(_)) => Ok(()),
(Ok(_), Err(error)) => Err(Violation::new(
LAW,
format!(
"{format:?} -> {:?}: the allocating door accepted, the in-place one refused: {error}",
Q::FORMAT
),
)),
(Err(error), Ok(())) => Err(Violation::new(
LAW,
format!(
"{format:?} -> {:?}: the in-place door accepted, the allocating one refused: {error}",
Q::FORMAT
),
)),
}
}
pub fn widening_to_16_bit_and_back_is_exact<
Narrow: Pixel<Sample = u8>,
Wide: Pixel<Sample = u16>,
>(
dims: Dimensions,
samples: &[u8],
policy: ConvertPolicy,
) -> Result<(), Violation> {
const LAW: &str = "widening_to_16_bit_and_back_is_exact";
let Ok(src) = RawImage::<u8>::new(samples, Narrow::FORMAT, dims) else {
return Ok(());
};
let Ok(wide) = convert_from_raw::<u8, Wide>(src, policy) else {
return Ok(());
};
let Ok(back) = RawImage::<u16>::new(wide.as_samples(), Wide::FORMAT, dims) else {
return Ok(());
};
let Ok(narrow) = convert_from_raw::<u16, Narrow>(back, policy) else {
return Ok(());
};
for (index, (&got, &want)) in narrow.as_samples().iter().zip(samples.iter()).enumerate() {
if got != want {
return Err(Violation::new(
LAW,
format!(
"{:?} -> {:?} -> {:?}: sample {index} was {want}, came back {got}",
Narrow::FORMAT,
Wide::FORMAT,
Narrow::FORMAT
),
));
}
}
Ok(())
}
fn alpha_code_max<S: Sample>() -> u64 {
match core::mem::size_of::<S>() {
1 => 255,
_ => 65_535,
}
}
fn alpha_code<S: Sample>(sample: S) -> u64 {
u64::from(sample.to_full_range_u16()) / (65_535 / alpha_code_max::<S>())
}
fn split_pixel<S: Sample>(pixel: &[S]) -> (Vec<u64>, u64) {
let (colour, alpha) = pixel.split_at(pixel.len() - 1);
(
colour.iter().map(|&s| alpha_code(s)).collect(),
alpha_code(alpha[0]),
)
}
fn alpha_image<P: Pixel>(dims: Dimensions, samples: &[P::Sample]) -> Option<ImageBuf<P>> {
if !matches!(
P::FORMAT.color_model(),
ColorModel::Rgba | ColorModel::GrayAlpha
) {
return None;
}
ImageBuf::<P>::new(samples.to_vec(), dims).ok()
}
pub fn opaque_pixels_are_fixed_points<P: Pixel>(
dims: Dimensions,
samples: &[P::Sample],
) -> Result<(), Violation> {
const LAW: &str = "opaque_pixels_are_fixed_points";
let Some(original) = alpha_image::<P>(dims, samples) else {
return Ok(());
};
let max = alpha_code_max::<P::Sample>();
let mut premultiplied = original.clone();
premultiply_alpha(&mut premultiplied);
let mut unpremultiplied = original.clone();
unpremultiply_alpha(&mut unpremultiplied);
let pixels = original.as_samples().chunks_exact(P::CHANNELS);
let forward = premultiplied.as_samples().chunks_exact(P::CHANNELS);
let backward = unpremultiplied.as_samples().chunks_exact(P::CHANNELS);
for (index, ((source, there), back)) in pixels.zip(forward).zip(backward).enumerate() {
if split_pixel(source).1 != max {
continue;
}
if there != source || back != source {
return Err(Violation::new(
LAW,
format!(
"{:?} pixel {index} {source:?}: premultiplied to {there:?}, unpremultiplied to {back:?}",
P::FORMAT
),
));
}
}
Ok(())
}
pub fn premultiply_rounds_to_nearest<P: Pixel>(
dims: Dimensions,
samples: &[P::Sample],
) -> Result<(), Violation> {
const LAW: &str = "premultiply_rounds_to_nearest";
let Some(original) = alpha_image::<P>(dims, samples) else {
return Ok(());
};
let max = alpha_code_max::<P::Sample>();
let mut premultiplied = original.clone();
premultiply_alpha(&mut premultiplied);
let pixels = original.as_samples().chunks_exact(P::CHANNELS);
let results = premultiplied.as_samples().chunks_exact(P::CHANNELS);
for (index, (source, result)) in pixels.zip(results).enumerate() {
let (colours, alpha) = split_pixel(source);
let (associated, kept_alpha) = split_pixel(result);
let nearest = colours
.iter()
.zip(&associated)
.all(|(&c, &p)| 2 * (p * max).abs_diff(c * alpha) <= max);
if kept_alpha != alpha || !nearest {
return Err(Violation::new(
LAW,
format!(
"{:?} pixel {index} {source:?} premultiplied to {result:?}",
P::FORMAT
),
));
}
}
Ok(())
}
pub fn unpremultiply_rounds_to_nearest_or_clamps<P: Pixel>(
dims: Dimensions,
samples: &[P::Sample],
) -> Result<(), Violation> {
const LAW: &str = "unpremultiply_rounds_to_nearest_or_clamps";
let Some(original) = alpha_image::<P>(dims, samples) else {
return Ok(());
};
let max = alpha_code_max::<P::Sample>();
let mut unpremultiplied = original.clone();
unpremultiply_alpha(&mut unpremultiplied);
let pixels = original.as_samples().chunks_exact(P::CHANNELS);
let results = unpremultiplied.as_samples().chunks_exact(P::CHANNELS);
for (index, (source, result)) in pixels.zip(results).enumerate() {
let (associated, alpha) = split_pixel(source);
let (colours, kept_alpha) = split_pixel(result);
let lawful = associated.iter().zip(&colours).all(|(&p, &c)| {
if alpha == 0 {
c == 0
} else if c == max {
2 * p * max >= (2 * max - 1) * alpha
} else {
2 * (c * alpha).abs_diff(p * max) <= alpha
}
});
if kept_alpha != alpha || !lawful {
return Err(Violation::new(
LAW,
format!(
"{:?} pixel {index} {source:?} unpremultiplied to {result:?}",
P::FORMAT
),
));
}
}
Ok(())
}
pub fn premultiply_round_trip_is_bounded_and_idempotent<P: Pixel>(
dims: Dimensions,
samples: &[P::Sample],
) -> Result<(), Violation> {
const LAW: &str = "premultiply_round_trip_is_bounded_and_idempotent";
let Some(original) = alpha_image::<P>(dims, samples) else {
return Ok(());
};
let max = alpha_code_max::<P::Sample>();
let mut associated = original.clone();
premultiply_alpha(&mut associated);
let mut recovered = associated.clone();
unpremultiply_alpha(&mut recovered);
let mut again = recovered.clone();
premultiply_alpha(&mut again);
let pixels = original.as_samples().chunks_exact(P::CHANNELS);
let backs = recovered.as_samples().chunks_exact(P::CHANNELS);
for (index, (source, back)) in pixels.zip(backs).enumerate() {
let (colours, alpha) = split_pixel(source);
let (recovered_colours, _) = split_pixel(back);
let bounded = alpha == 0
|| colours
.iter()
.zip(&recovered_colours)
.all(|(&c, &r)| c.abs_diff(r) <= (alpha + max) / (2 * alpha));
if !bounded {
return Err(Violation::new(
LAW,
format!(
"{:?} pixel {index} {source:?} came back as {back:?}",
P::FORMAT
),
));
}
}
if again != associated {
return Err(Violation::new(
LAW,
format!(
"{:?}: re-premultiplying the recovered image did not reproduce the associated one",
P::FORMAT
),
));
}
Ok(())
}
#[cfg(test)]
mod tests {
use proptest::prelude::{Just, Strategy, prop_assert, prop_oneof, proptest};
use proptest::test_runner::{Config, RngSeed};
use super::{
MAX_EDGE, NARROW_FORMATS, Violation, WIDE_FORMATS,
acceptance_is_independent_of_the_samples, acceptance_is_independent_of_the_samples_under,
alpha_image, converting_a_layout_to_itself_changes_nothing,
converting_a_layout_to_itself_changes_nothing_under, normalise_dims,
opaque_pixels_are_fixed_points, output_shape_matches_the_target_layout,
output_shape_matches_the_target_layout_under, palette_and_cmyk_convert_only_to_themselves,
premultiply_round_trip_is_bounded_and_idempotent, premultiply_rounds_to_nearest,
split_pixel, the_in_place_door_matches_the_allocating_door,
the_in_place_door_matches_the_allocating_door_under,
unpremultiply_rounds_to_nearest_or_clamps, widening_to_16_bit_and_back_is_exact,
};
use crate::convert::{AlphaPolicy, ConvertPolicy, DepthPolicy, LumaPolicy};
use crate::{
Bilevel, Cmyk8, Dimensions, Error, Gray8, Gray16, GrayAlpha8, GrayAlpha16, ImageBuf,
Indexed8, Pixel, PixelFormat, Rgb8, Rgb16, Rgba8, Rgba16,
};
fn config() -> Config {
Config {
cases: 256,
max_shrink_iters: 2048,
max_shrink_time: 10_000,
rng_seed: RngSeed::Fixed(0x6761_6D75_745F_636F),
failure_persistence: None,
..Config::default()
}
}
macro_rules! for_each_narrow_target {
($law:ident, $($arg:expr),* $(,)?) => {{
let mut result: Result<(), Violation> = Ok(());
if result.is_ok() { result = $law::<u8, Gray8>($($arg),*); }
if result.is_ok() { result = $law::<u8, Bilevel>($($arg),*); }
if result.is_ok() { result = $law::<u8, Indexed8>($($arg),*); }
if result.is_ok() { result = $law::<u8, Rgb8>($($arg),*); }
if result.is_ok() { result = $law::<u8, Rgba8>($($arg),*); }
if result.is_ok() { result = $law::<u8, Cmyk8>($($arg),*); }
if result.is_ok() { result = $law::<u8, GrayAlpha8>($($arg),*); }
result
}};
}
fn dimensions() -> impl Strategy<Value = Dimensions> {
(0..MAX_EDGE, 0..MAX_EDGE).prop_map(|(w, h)| {
let (width, height) = normalise_dims(w, h);
Dimensions::new(width, height).expect("normalise_dims yields a non-zero edge")
})
}
fn policy() -> impl Strategy<Value = ConvertPolicy> {
(
prop_oneof![
Just(AlphaPolicy::Reject),
Just(AlphaPolicy::Drop),
Just(AlphaPolicy::CompositeOver),
],
prop_oneof![Just(DepthPolicy::Reject), Just(DepthPolicy::Rescale)],
prop_oneof![
Just(LumaPolicy::Reject),
Just(LumaPolicy::Bt601),
Just(LumaPolicy::Bt709),
Just(LumaPolicy::Bt2020),
],
proptest::array::uniform3(proptest::num::u16::ANY),
proptest::num::u16::ANY,
)
.prop_map(|(alpha, depth, luma, background, threshold)| {
ConvertPolicy::lossless()
.with_alpha(alpha)
.with_depth(depth)
.with_luma(luma)
.with_background(background)
.with_threshold(threshold)
})
}
fn describe(result: &Result<(), Violation>) -> String {
match result {
Ok(()) => String::new(),
Err(violation) => violation.to_string(),
}
}
fn filler(len: usize, seed: u8) -> Vec<u8> {
(0..len)
.map(|i| seed.wrapping_add((i % 251) as u8))
.collect()
}
proptest! {
#![proptest_config(config())]
#[test]
fn acceptance_never_depends_on_the_pixel_values(
source in proptest::sample::select(NARROW_FORMATS.as_slice()),
dims in dimensions(),
policy in policy(),
seed in proptest::num::u8::ANY,
) {
let len = dims.sample_count(source.channels()).expect("bounded dims");
let zeros = vec![0u8; len];
let varied = filler(len, seed);
let outcome = for_each_narrow_target!(
acceptance_is_independent_of_the_samples,
source, dims, &zeros, &varied, policy
);
prop_assert!(outcome.is_ok(), "{}", describe(&outcome));
}
#[test]
fn an_accepted_conversion_has_the_target_layouts_shape(
source in proptest::sample::select(NARROW_FORMATS.as_slice()),
dims in dimensions(),
policy in policy(),
seed in proptest::num::u8::ANY,
) {
let len = dims.sample_count(source.channels()).expect("bounded dims");
let samples = filler(len, seed);
let outcome = for_each_narrow_target!(
output_shape_matches_the_target_layout,
source, dims, &samples, policy
);
prop_assert!(outcome.is_ok(), "{}", describe(&outcome));
}
#[test]
fn palette_and_cmyk_are_closed_under_every_policy(
source in proptest::sample::select(NARROW_FORMATS.as_slice()),
dims in dimensions(),
policy in policy(),
seed in proptest::num::u8::ANY,
) {
let len = dims.sample_count(source.channels()).expect("bounded dims");
let samples = filler(len, seed);
let outcome = for_each_narrow_target!(
palette_and_cmyk_convert_only_to_themselves,
source, dims, &samples, policy
);
prop_assert!(outcome.is_ok(), "{}", describe(&outcome));
}
#[test]
fn both_doors_onto_the_engine_produce_the_same_image(
source in proptest::sample::select(NARROW_FORMATS.as_slice()),
dims in dimensions(),
policy in policy(),
seed in proptest::num::u8::ANY,
) {
let len = dims.sample_count(source.channels()).expect("bounded dims");
let samples = filler(len, seed);
let outcome = for_each_narrow_target!(
the_in_place_door_matches_the_allocating_door,
source, dims, &samples, policy
);
prop_assert!(outcome.is_ok(), "{}", describe(&outcome));
}
#[test]
fn every_layout_converts_to_itself_unchanged(
dims in dimensions(),
policy in policy(),
seed in proptest::num::u8::ANY,
) {
macro_rules! identity {
($p:ty, $sample:ty) => {{
let len = dims
.sample_count(<$p as Pixel>::CHANNELS)
.expect("bounded dims");
let samples: Vec<$sample> = (0..len)
.map(|i| <$sample>::from(seed).wrapping_add(i as $sample))
.collect();
let result =
converting_a_layout_to_itself_changes_nothing::<$p>(dims, &samples, policy);
prop_assert!(result.is_ok(), "{}", describe(&result));
}};
}
identity!(Gray8, u8);
identity!(Bilevel, u8);
identity!(Indexed8, u8);
identity!(Rgb8, u8);
identity!(Rgba8, u8);
identity!(Cmyk8, u8);
identity!(GrayAlpha8, u8);
identity!(Gray16, u16);
identity!(Rgb16, u16);
identity!(Rgba16, u16);
identity!(GrayAlpha16, u16);
}
#[test]
fn widening_to_16_bit_and_rescaling_back_recovers_every_sample(
dims in dimensions(),
seed in proptest::num::u8::ANY,
) {
let policy = ConvertPolicy::lossless().with_depth(DepthPolicy::Rescale);
macro_rules! exact {
($narrow:ty, $wide:ty) => {{
let len = dims
.sample_count(<$narrow as Pixel>::CHANNELS)
.expect("bounded dims");
let samples = filler(len, seed);
let result = widening_to_16_bit_and_back_is_exact::<$narrow, $wide>(
dims, &samples, policy,
);
prop_assert!(result.is_ok(), "{}", describe(&result));
}};
}
exact!(Gray8, Gray16);
exact!(Rgb8, Rgb16);
exact!(Rgba8, Rgba16);
exact!(GrayAlpha8, GrayAlpha16);
}
#[test]
fn associated_alpha_laws_hold_for_every_alpha_layout(
dims in dimensions(),
colours in proptest::collection::vec(proptest::num::u16::ANY, (MAX_EDGE * MAX_EDGE * 3) as usize),
alphas in proptest::collection::vec(
prop_oneof![Just(0u16), Just(u16::MAX), proptest::num::u16::ANY],
(MAX_EDGE * MAX_EDGE) as usize,
),
) {
macro_rules! laws {
($p:ty, $sample:ty, $narrow:expr) => {{
let pixels = dims.sample_count(1).expect("bounded dims");
let colour_channels = <$p as Pixel>::CHANNELS - 1;
let mut samples: Vec<$sample> = Vec::new();
for pixel in 0..pixels {
for channel in 0..colour_channels {
samples.push($narrow(colours[pixel * 3 + channel]));
}
samples.push($narrow(alphas[pixel]));
}
for result in [
opaque_pixels_are_fixed_points::<$p>(dims, &samples),
premultiply_rounds_to_nearest::<$p>(dims, &samples),
unpremultiply_rounds_to_nearest_or_clamps::<$p>(dims, &samples),
premultiply_round_trip_is_bounded_and_idempotent::<$p>(dims, &samples),
] {
prop_assert!(result.is_ok(), "{}", describe(&result));
}
}};
}
let narrow = |v: u16| (v >> 8) as u8;
let wide = |v: u16| v;
laws!(Rgba8, u8, narrow);
laws!(GrayAlpha8, u8, narrow);
laws!(Rgba16, u16, wide);
laws!(GrayAlpha16, u16, wide);
}
}
#[test]
fn associated_alpha_laws_hold_for_every_8_bit_pair() {
let dims = Dimensions::new(256, 256).expect("non-zero");
let mut rgba = Vec::with_capacity(256 * 256 * 4);
let mut grey_alpha = Vec::with_capacity(256 * 256 * 2);
for alpha in 0..=u8::MAX {
for colour in 0..=u8::MAX {
rgba.extend_from_slice(&[colour, u8::MAX - colour, colour.rotate_left(4), alpha]);
grey_alpha.extend_from_slice(&[colour, alpha]);
}
}
for result in [
opaque_pixels_are_fixed_points::<Rgba8>(dims, &rgba),
premultiply_rounds_to_nearest::<Rgba8>(dims, &rgba),
unpremultiply_rounds_to_nearest_or_clamps::<Rgba8>(dims, &rgba),
premultiply_round_trip_is_bounded_and_idempotent::<Rgba8>(dims, &rgba),
opaque_pixels_are_fixed_points::<GrayAlpha8>(dims, &grey_alpha),
premultiply_rounds_to_nearest::<GrayAlpha8>(dims, &grey_alpha),
unpremultiply_rounds_to_nearest_or_clamps::<GrayAlpha8>(dims, &grey_alpha),
premultiply_round_trip_is_bounded_and_idempotent::<GrayAlpha8>(dims, &grey_alpha),
] {
assert!(result.is_ok(), "{}", describe(&result));
}
}
#[test]
fn the_alpha_laws_govern_only_alpha_layouts() {
let dims = Dimensions::new(1, 1).expect("non-zero");
assert!(alpha_image::<Rgb8>(dims, &[1, 2, 3]).is_none());
assert!(alpha_image::<Rgba8>(dims, &[1, 2, 3, 4]).is_some());
assert!(alpha_image::<Rgba8>(dims, &[1, 2, 3]).is_none());
assert_eq!(split_pixel(&[7u8, 9, 255]), (vec![7, 9], 255));
assert_eq!(split_pixel(&[7u16, 0xFFFF]), (vec![7], 65_535));
}
#[test]
fn the_closure_law_does_not_govern_an_open_pair() {
let dims = Dimensions::new(2, 2).expect("non-zero");
let samples = [1u8, 2, 3, 4];
assert!(
palette_and_cmyk_convert_only_to_themselves::<u8, Rgb8>(
PixelFormat::Gray8,
dims,
&samples,
ConvertPolicy::permissive(),
)
.is_ok()
);
}
#[test]
fn the_closure_law_governs_a_closed_pair_and_the_engine_refuses_it() {
let dims = Dimensions::new(2, 2).expect("non-zero");
let samples = [1u8, 2, 3, 4];
let src = crate::convert::RawImage::<u8>::new(&samples, PixelFormat::Indexed8, dims)
.expect("4 samples is one channel at 2x2");
assert!(
crate::convert::convert_from_raw::<u8, Rgb8>(src, ConvertPolicy::permissive()).is_err(),
"Indexed8 -> Rgb8 must be refused whatever the policy permits"
);
}
fn two_by_two() -> Dimensions {
Dimensions::new(2, 2).expect("non-zero")
}
fn refusal() -> Error {
Error::unsupported("invariants test", "refused by a broken engine")
}
#[test]
fn an_engine_that_reads_the_samples_violates_the_acceptance_law() {
let violation = acceptance_is_independent_of_the_samples_under::<u8, Gray8>(
|src, _| {
if src.as_samples().iter().all(|&s| s == 0) {
ImageBuf::zeroed(src.dimensions())
} else {
Err(refusal())
}
},
PixelFormat::Gray8,
two_by_two(),
&[0, 0, 0, 0],
&[0, 0, 0, 1],
ConvertPolicy::lossless(),
)
.expect_err("data-dependent acceptance must violate the law");
assert_eq!(violation.law(), "acceptance_is_independent_of_the_samples");
assert!(
violation
.detail()
.contains("Gray8 -> Gray8: one sample buffer was accepted"),
"{violation}"
);
}
#[test]
fn an_engine_that_resizes_the_image_violates_the_shape_law() {
let violation = output_shape_matches_the_target_layout_under::<u8, Gray8>(
|_, _| ImageBuf::zeroed(Dimensions::new(1, 1).expect("non-zero")),
PixelFormat::Gray8,
two_by_two(),
&[1, 2, 3, 4],
ConvertPolicy::lossless(),
)
.expect_err("a resized output must violate the law");
assert_eq!(violation.law(), "output_shape_matches_the_target_layout");
assert!(violation.detail().contains("dimensions"), "{violation}");
}
#[test]
fn an_engine_that_refuses_the_identity_violates_the_identity_law() {
let violation = converting_a_layout_to_itself_changes_nothing_under::<Gray8>(
|_, _| Err(refusal()),
two_by_two(),
&[1, 2, 3, 4],
ConvertPolicy::lossless(),
)
.expect_err("a refused identity must violate the law");
assert_eq!(
violation.law(),
"converting_a_layout_to_itself_changes_nothing"
);
assert!(
violation.detail().contains("Gray8 -> itself was refused"),
"{violation}"
);
}
#[test]
fn an_engine_that_alters_the_samples_violates_the_identity_law() {
let violation = converting_a_layout_to_itself_changes_nothing_under::<Gray8>(
|src, _| ImageBuf::zeroed(src.dimensions()),
two_by_two(),
&[1, 2, 3, 4],
ConvertPolicy::lossless(),
)
.expect_err("an altered identity must violate the law");
assert_eq!(
violation.law(),
"converting_a_layout_to_itself_changes_nothing"
);
assert!(
violation
.detail()
.contains("Gray8 -> itself altered the samples"),
"{violation}"
);
}
#[test]
fn doors_that_write_different_samples_violate_the_door_law() {
let violation = the_in_place_door_matches_the_allocating_door_under::<u8, Gray8>(
crate::convert::convert_from_raw::<u8, Gray8>,
|_, _, dst| {
dst.fill(9);
Ok(())
},
PixelFormat::Gray8,
two_by_two(),
&[1, 2, 3, 4],
ConvertPolicy::lossless(),
)
.expect_err("diverging samples must violate the law");
assert_eq!(
violation.law(),
"the_in_place_door_matches_the_allocating_door"
);
assert!(
violation.detail().contains("wrote different samples"),
"{violation}"
);
}
#[test]
fn an_in_place_door_that_refuses_alone_violates_the_door_law() {
let violation = the_in_place_door_matches_the_allocating_door_under::<u8, Gray8>(
crate::convert::convert_from_raw::<u8, Gray8>,
|_, _, _| Err(refusal()),
PixelFormat::Gray8,
two_by_two(),
&[1, 2, 3, 4],
ConvertPolicy::lossless(),
)
.expect_err("a one-sided refusal must violate the law");
assert!(
violation
.detail()
.contains("the allocating door accepted, the in-place one refused"),
"{violation}"
);
}
#[test]
fn an_allocating_door_that_refuses_alone_violates_the_door_law() {
let violation = the_in_place_door_matches_the_allocating_door_under::<u8, Gray8>(
|_, _| Err(refusal()),
crate::convert::convert_from_raw_into::<u8, Gray8>,
PixelFormat::Gray8,
two_by_two(),
&[1, 2, 3, 4],
ConvertPolicy::lossless(),
)
.expect_err("a one-sided refusal must violate the law");
assert!(
violation
.detail()
.contains("the in-place door accepted, the allocating one refused"),
"{violation}"
);
}
#[test]
fn sample_count_multiplies_the_pixel_count_by_the_channel_count() {
let dims = Dimensions::new(2, 2).expect("non-zero");
assert_eq!(dims.sample_count(1), Some(4));
assert_eq!(dims.sample_count(3), Some(12));
assert_eq!(dims.sample_count(4), Some(16));
}
#[test]
fn normalise_dims_always_yields_a_usable_edge() {
for (w, h) in [
(0u32, 0u32),
(1, 1),
(u32::MAX, u32::MAX),
(MAX_EDGE, MAX_EDGE),
] {
let (width, height) = normalise_dims(w, h);
assert!((1..=MAX_EDGE).contains(&width), "{w} gave {width}");
assert!((1..=MAX_EDGE).contains(&height), "{h} gave {height}");
assert!(Dimensions::new(width, height).is_ok());
}
}
#[test]
fn the_format_tables_cover_the_whole_pixel_matrix() {
let eight_bit: Vec<PixelFormat> = PixelFormat::ALL
.iter()
.copied()
.filter(|f| f.bytes_per_sample() == 1)
.collect();
let sixteen_bit: Vec<PixelFormat> = PixelFormat::ALL
.iter()
.copied()
.filter(|f| f.bytes_per_sample() == 2)
.collect();
assert_eq!(eight_bit, NARROW_FORMATS);
assert_eq!(sixteen_bit, WIDE_FORMATS);
assert_eq!(eight_bit.len() + sixteen_bit.len(), PixelFormat::ALL.len());
}
}