imageproc_patched/
property_testing.rs1use crate::definitions::Image;
7use image::{GenericImage, ImageBuffer, Luma, Pixel, Primitive, Rgb};
8use quickcheck::{Arbitrary, Gen};
9use rand::Rng;
10use rand_distr::{Distribution, Standard};
11use std::fmt;
12
13#[derive(Clone)]
15pub struct TestBuffer<T: Pixel>(pub Image<T>);
16
17pub type GrayTestImage = TestBuffer<Luma<u8>>;
19
20pub type RgbTestImage = TestBuffer<Rgb<u8>>;
22
23impl<T: Pixel + ArbitraryPixel + Send + 'static> Arbitrary for TestBuffer<T>
24where
25 <T as Pixel>::Subpixel: Send,
26{
27 fn arbitrary<G: Gen>(g: &mut G) -> Self {
28 let (width, height) = small_image_dimensions(g);
29 let mut image = ImageBuffer::new(width, height);
30 for y in 0..height {
31 for x in 0..width {
32 let pix: T = ArbitraryPixel::arbitrary(g);
33 image.put_pixel(x, y, pix);
34 }
35 }
36 TestBuffer(image)
37 }
38
39 fn shrink(&self) -> Box<dyn Iterator<Item = TestBuffer<T>>> {
40 Box::new(shrink(&self.0).map(TestBuffer))
41 }
42}
43
44pub trait ArbitraryPixel {
47 fn arbitrary<G: Gen>(g: &mut G) -> Self;
49}
50
51fn shrink<I>(image: &I) -> Box<dyn Iterator<Item = Image<I::Pixel>>>
52where
53 I: GenericImage,
54 I::Pixel: 'static,
55{
56 let mut subs = vec![];
57
58 let w = image.width();
59 let h = image.height();
60
61 if w > 0 {
62 let left = copy_sub(image, 0, 0, w - 1, h);
63 subs.push(left);
64 let right = copy_sub(image, 1, 0, w - 1, h);
65 subs.push(right);
66 }
67 if h > 0 {
68 let top = copy_sub(image, 0, 0, w, h - 1);
69 subs.push(top);
70 let bottom = copy_sub(image, 0, 1, w, h - 1);
71 subs.push(bottom);
72 }
73
74 Box::new(subs.into_iter())
75}
76
77fn copy_sub<I>(image: &I, x: u32, y: u32, width: u32, height: u32) -> Image<I::Pixel>
78where
79 I: GenericImage,
80{
81 let mut out = ImageBuffer::new(width, height);
82 for dy in 0..height {
83 let oy = y + dy;
84 for dx in 0..width {
85 let ox = x + dx;
86 out.put_pixel(dx, dy, image.get_pixel(ox, oy));
87 }
88 }
89 out
90}
91
92impl<T: fmt::Debug + Pixel> fmt::Debug for TestBuffer<T> {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 write!(
95 f,
96 "width: {}, height: {}, data: {:?}",
97 self.0.width(),
98 self.0.height(),
99 self.0.enumerate_pixels().collect::<Vec<_>>()
100 )
101 }
102}
103
104fn small_image_dimensions<G: Gen>(g: &mut G) -> (u32, u32) {
105 let dims: (u8, u8) = Arbitrary::arbitrary(g);
106 ((dims.0 % 10) as u32, (dims.1 % 10) as u32)
107}
108
109impl<T: Send + Primitive> ArbitraryPixel for Rgb<T>
110where
111 Standard: Distribution<T>,
112{
113 fn arbitrary<G: Gen>(g: &mut G) -> Self {
114 let red: T = g.gen();
115 let green: T = g.gen();
116 let blue: T = g.gen();
117 Rgb([red, green, blue])
118 }
119}
120
121impl<T: Send + Primitive> ArbitraryPixel for Luma<T>
122where
123 Standard: Distribution<T>,
124{
125 fn arbitrary<G: Gen>(g: &mut G) -> Self {
126 let val: T = g.gen();
127 Luma([val])
128 }
129}