use emblema::*;
use proptest::prelude::*;
const ALLOCATION_CEILING: usize = 256 * 1024 * 1024;
struct Watermark;
static PEAK: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
fn refuse(size: usize) -> ! {
let mut digits = [0u8; 20];
let mut at = digits.len();
let mut value = size;
loop {
at -= 1;
digits[at] = b'0' + u8::try_from(value % 10).unwrap_or(0);
value /= 10;
if value == 0 || at == 0 {
break;
}
}
use std::io::Write as _;
let mut err = std::io::stderr();
let _ = err.write_all(b"\nhostile_api: refused a single allocation of ");
let _ = err.write_all(&digits[at..]);
let _ = err.write_all(b" bytes, which is over ALLOCATION_CEILING\n");
std::process::abort()
}
unsafe impl std::alloc::GlobalAlloc for Watermark {
unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 {
if layout.size() >= ALLOCATION_CEILING {
refuse(layout.size());
}
PEAK.fetch_max(layout.size(), std::sync::atomic::Ordering::Relaxed);
unsafe { std::alloc::System.alloc(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: std::alloc::Layout) {
unsafe { std::alloc::System.dealloc(ptr, layout) };
}
unsafe fn realloc(&self, ptr: *mut u8, layout: std::alloc::Layout, new_size: usize) -> *mut u8 {
if new_size >= ALLOCATION_CEILING {
refuse(new_size);
}
PEAK.fetch_max(new_size, std::sync::atomic::Ordering::Relaxed);
unsafe { std::alloc::System.realloc(ptr, layout, new_size) }
}
}
#[global_allocator]
static WATERMARK: Watermark = Watermark;
fn reset_peak() {
PEAK.store(0, std::sync::atomic::Ordering::Relaxed);
}
fn peak_allocation() -> usize {
PEAK.load(std::sync::atomic::Ordering::Relaxed)
}
fn hostile_coord() -> impl Strategy<Value = f32> {
prop_oneof![
8 => -500.0f32..500.0,
1 => Just(f32::NAN),
1 => Just(f32::INFINITY),
1 => Just(f32::NEG_INFINITY),
1 => Just(0.0f32),
1 => Just(-0.0f32),
1 => Just(f32::MIN_POSITIVE),
1 => Just(f32::MAX),
1 => Just(1e20f32),
1 => Just(-1e20f32),
]
}
fn hostile_point() -> impl Strategy<Value = [f32; 2]> {
(hostile_coord(), hostile_coord()).prop_map(|(x, y)| [x, y])
}
fn hostile_color() -> impl Strategy<Value = Color> {
(
hostile_coord(),
hostile_coord(),
hostile_coord(),
hostile_coord(),
)
.prop_map(|(r, g, b, a)| Color::srgb(r, g, b, a))
}
fn recording_is_addressable(recording: &Recording) -> Result<(), String> {
for (n, pass) in recording.passes.iter().enumerate() {
let vertices = pass.batch.vertices().len();
for index in pass.batch.indices() {
if *index as usize >= vertices {
return Err(format!(
"pass {n}: index {index} against {vertices} vertices"
));
}
}
if pass.batch.indices().len() % 3 != 0 {
return Err(format!(
"pass {n}: {} indices is not whole triangles",
pass.batch.indices().len()
));
}
for slot in pass.batch.texture_slots() {
if slot as usize >= pass.sources.len() {
return Err(format!(
"pass {n}: slot {slot} against {} sources",
pass.sources.len()
));
}
}
}
Ok(())
}
const SIZE: Extent2D = Extent2D {
width: 128,
height: 128,
};
proptest! {
#![proptest_config(ProptestConfig { cases: 2048, ..ProptestConfig::default() })]
#[test]
fn a_mesh_of_any_shape_records_something_addressable(
positions in prop::collection::vec(hostile_point(), 0..12),
indices in prop::collection::vec(0u32..16, 0..24),
colors in prop::collection::vec(hostile_color(), 0..12),
) {
let positions: Vec<Vec2> = positions.iter().map(|p| Vec2::new(p[0], p[1])).collect();
for mode in [VertexMode::Triangles, VertexMode::TriangleStrip, VertexMode::TriangleFan] {
let mesh = Vertices::indexed(mode, positions.clone(), Vec::new(), indices.clone());
let _ = &colors;
let Ok(mesh) = mesh else { continue };
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let _ = canvas.draw_vertices(&mesh, &Paint::fill(Color::WHITE));
let recording = canvas.finish();
prop_assert!(
recording_is_addressable(&recording).is_ok(),
"{:?}",
recording_is_addressable(&recording)
);
}
}
#[test]
fn a_gradient_of_any_stops_records_something_addressable(
stops in prop::collection::vec((hostile_color(), hostile_coord()), 0..12),
start in hostile_point(),
end in hostile_point(),
) {
let stops: Vec<GradientStop> = stops
.into_iter()
.map(|(color, offset)| GradientStop::new(color, offset))
.collect();
let paint = Paint::default().with_shader(Shader::LinearGradient {
start: Vec2::new(start[0], start[1]),
end: Vec2::new(end[0], end[1]),
stops,
tile: TileMode::Clamp,
});
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let _ = canvas.draw_rect(Rect::new(8.0, 8.0, 120.0, 120.0), &paint);
let recording = canvas.finish();
prop_assert!(
recording_is_addressable(&recording).is_ok(),
"{:?}",
recording_is_addressable(&recording)
);
}
#[test]
fn a_glyph_run_of_any_placement_records_something_addressable(
placements in prop::collection::vec((hostile_point(), hostile_point(), 0u32..64), 0..10),
) {
let glyphs: Vec<PositionedGlyph> = placements
.into_iter()
.map(|(position, size, id)| PositionedGlyph {
key: GlyphKey::new(0, id as u16, 12),
position,
size,
})
.collect();
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let atlas = Atlas::new(64);
let _ = canvas.draw_glyphs(&glyphs, &atlas, 0, &Paint::fill(Color::WHITE));
let recording = canvas.finish();
prop_assert!(
recording_is_addressable(&recording).is_ok(),
"{:?}",
recording_is_addressable(&recording)
);
}
#[test]
fn an_atlas_of_any_sprites_records_something_addressable(
sprites in prop::collection::vec(
(hostile_coord(), hostile_coord(), hostile_coord(), hostile_coord(), hostile_point()),
0..10,
),
) {
let sprites: Vec<Sprite> = sprites
.into_iter()
.map(|(x, y, w, h, at)| Sprite {
source: SourceRect::new(x, y, w, h),
color: Color::WHITE,
transform: Affine2::from_translation(Vec2::new(at[0], at[1])),
})
.collect();
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let _ = canvas.draw_atlas(&sprites, SIZE, &Paint::fill(Color::WHITE));
let recording = canvas.finish();
prop_assert!(
recording_is_addressable(&recording).is_ok(),
"{:?}",
recording_is_addressable(&recording)
);
}
}
#[test]
fn a_stack_of_layers_deeper_than_anything_needs_is_still_a_recording() {
for depth in [1usize, 64, 1024] {
let mut canvas = Canvas::new(Extent2D::new(64, 64));
canvas.clear(Color::BLACK);
for _ in 0..depth {
canvas.save_layer(Layer::opacity(0.9));
}
assert_eq!(
canvas.layer_depth(),
depth,
"the canvas lost count of the layers it has open"
);
canvas
.draw_rect(Rect::new(8.0, 8.0, 56.0, 56.0), &Paint::fill(Color::WHITE))
.expect("a rectangle inside a deep stack is still a rectangle");
for _ in 0..depth {
canvas.restore();
}
assert_eq!(canvas.layer_depth(), 0, "a balanced stack did not unwind");
let recording = canvas.finish();
assert_eq!(
recording.passes.len(),
depth + 1,
"a nest of {depth} produced {} passes",
recording.passes.len()
);
}
}
#[test]
fn layers_left_open_are_finished_rather_than_lost() {
let mut canvas = Canvas::new(Extent2D::new(64, 64));
canvas.clear(Color::BLACK);
for _ in 0..32 {
canvas.save_layer(Layer::opacity(0.9));
}
canvas
.draw_rect(Rect::new(8.0, 8.0, 56.0, 56.0), &Paint::fill(Color::WHITE))
.expect("a rectangle");
assert_eq!(canvas.layer_depth(), 32, "the layers did not open");
let recording = canvas.finish();
assert_eq!(
recording.passes.len(),
33,
"an unbalanced stack lost the passes its layers opened"
);
assert!(
recording.draw_count() > 0,
"the drawing inside an unclosed layer went nowhere"
);
}
fn hostile_layer() -> impl Strategy<Value = Layer> {
(
(hostile_coord(), hostile_coord(), hostile_coord()),
(
prop::sample::select(BlendMode::ALL),
prop::option::of((hostile_coord(), hostile_coord(), hostile_coord())),
prop::option::of((hostile_coord(), hostile_coord(), any::<bool>())),
),
(
prop_oneof![
4 => Just(ColorFilter::None),
1 => (hostile_coord(), prop::sample::select(BlendMode::ALL))
.prop_map(|(c, mode)| ColorFilter::Blend {
color: [c, c, c, c],
mode,
}),
1 => Just(ColorFilter::Gamma { direction: Gamma::LinearToSrgb }),
1 => Just(ColorFilter::Gamma { direction: Gamma::SrgbToLinear }),
],
prop::option::of(any::<i64>()),
),
)
.prop_map(
|(
(blur_x, blur_y, alpha),
(blend, matrix, morphology),
(color_filter, backdrop_id),
)| Layer {
blur: Vec2::new(blur_x, blur_y),
alpha,
blend,
matrix: matrix.map(|(x, y, r)| {
Transform2D::from(Affine2::from_scale(Vec2::new(x, y)))
* Transform2D::from(Affine2::from_angle(r))
}),
backdrop_blur: blur_y,
backdrop_id,
morphology: morphology.map(|(x, y, dilate)| Morphology {
radius: [x, y],
dilate,
}),
color_filter,
},
)
}
#[derive(Debug, Clone)]
enum Op {
Save,
Restore,
SaveLayer(Layer),
SaveLayerBounds(Layer, [f32; 4]),
ClipRect([f32; 4]),
ClipOutRect([f32; 4]),
Translate(f32, f32),
Scale(f32, f32),
Rotate(f32),
DrawRect([f32; 4], Color),
DrawCircle([f32; 2], f32, Color),
DrawPaint(Color),
Clear(Color),
}
fn hostile_rect() -> impl Strategy<Value = [f32; 4]> {
(
hostile_coord(),
hostile_coord(),
hostile_coord(),
hostile_coord(),
)
.prop_map(|(a, b, c, d)| [a, b, c, d])
}
fn ops() -> impl Strategy<Value = Vec<Op>> {
let op = prop_oneof![
3 => Just(Op::Save),
4 => Just(Op::Restore),
3 => hostile_layer().prop_map(Op::SaveLayer),
2 => (hostile_layer(), hostile_rect())
.prop_map(|(l, r)| Op::SaveLayerBounds(l, r)),
2 => hostile_rect().prop_map(Op::ClipRect),
1 => hostile_rect().prop_map(Op::ClipOutRect),
2 => (hostile_coord(), hostile_coord()).prop_map(|(x, y)| Op::Translate(x, y)),
2 => (hostile_coord(), hostile_coord()).prop_map(|(x, y)| Op::Scale(x, y)),
1 => hostile_coord().prop_map(Op::Rotate),
4 => (hostile_rect(), hostile_color()).prop_map(|(r, c)| Op::DrawRect(r, c)),
2 => (hostile_point(), hostile_coord(), hostile_color())
.prop_map(|(at, radius, c)| Op::DrawCircle(at, radius, c)),
1 => hostile_color().prop_map(Op::DrawPaint),
1 => hostile_color().prop_map(Op::Clear),
];
prop::collection::vec(op, 0..40)
}
fn apply(canvas: &mut Canvas, op: &Op) {
let rect = |r: &[f32; 4]| Rect::new(r[0], r[1], r[2], r[3]);
match op {
Op::Save => {
canvas.save();
}
Op::Restore => {
canvas.restore();
}
Op::SaveLayer(layer) => {
canvas.save_layer(*layer);
}
Op::SaveLayerBounds(layer, r) => {
canvas.save_layer_bounds(*layer, rect(r));
}
Op::ClipRect(r) => {
let _ = canvas.clip_rect(rect(r));
}
Op::ClipOutRect(r) => {
let _ = canvas.clip_out_rect(rect(r));
}
Op::Translate(x, y) => {
canvas.translate(*x, *y);
}
Op::Scale(x, y) => {
canvas.scale(*x, *y);
}
Op::Rotate(r) => {
canvas.rotate(*r);
}
Op::DrawRect(r, color) => {
let _ = canvas.draw_rect(rect(r), &Paint::fill(*color));
}
Op::DrawCircle(at, radius, color) => {
let _ = canvas.draw_circle(Vec2::new(at[0], at[1]), *radius, &Paint::fill(*color));
}
Op::DrawPaint(color) => {
let _ = canvas.draw_paint(&Paint::fill(*color));
}
Op::Clear(color) => {
canvas.clear(*color);
}
}
}
fn opens(ops: &[Op]) -> usize {
ops.iter()
.filter(|op| matches!(op, Op::Save | Op::SaveLayer(_) | Op::SaveLayerBounds(..)))
.count()
}
proptest! {
#![proptest_config(ProptestConfig { cases: 2048, ..ProptestConfig::default() })]
#[test]
fn a_sequence_of_any_operations_records_something_addressable(ops in ops()) {
reset_peak();
let mut canvas = Canvas::new(SIZE);
for op in &ops {
apply(&mut canvas, op);
prop_assert!(
canvas.layer_depth() <= canvas.save_depth(),
"{} layers open against {} saves, so a layer is not on the stack \
it is counted from",
canvas.layer_depth(),
canvas.save_depth()
);
prop_assert!(
canvas.save_depth() <= opens(&ops),
"{} saves outstanding after at most {} operations that open one",
canvas.save_depth(),
opens(&ops)
);
}
let recording = canvas.finish();
prop_assert!(
recording_is_addressable(&recording).is_ok(),
"{}",
recording_is_addressable(&recording).unwrap_err()
);
let peak = peak_allocation();
prop_assert!(
peak < ALLOCATION_CEILING,
"a sequence of {} operations asked for a single allocation of {peak} bytes",
ops.len()
);
}
#[test]
fn the_stack_unwinds_in_as_many_restores_as_it_says(ops in ops()) {
reset_peak();
let mut canvas = Canvas::new(SIZE);
for op in &ops {
apply(&mut canvas, op);
}
let peak = peak_allocation();
prop_assert!(
peak < ALLOCATION_CEILING,
"a sequence of {} operations asked for a single allocation of {peak} bytes",
ops.len()
);
let outstanding = canvas.save_depth();
for _ in 0..outstanding {
canvas.restore();
}
prop_assert_eq!(
canvas.save_depth(),
0,
"{} restores left the stack un-emptied",
outstanding
);
prop_assert_eq!(
canvas.layer_depth(),
0,
"the saves are balanced but {} layers are still open",
canvas.layer_depth()
);
canvas.restore();
prop_assert_eq!(canvas.save_depth(), 0);
let peak = peak_allocation();
prop_assert!(
peak < ALLOCATION_CEILING,
"unwinding {} operations asked for a single allocation of {peak} bytes",
ops.len()
);
}
#[test]
fn a_layer_of_any_configuration_records_something_addressable(
layer in hostile_layer(),
bounds in prop::option::of(hostile_rect()),
) {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
match bounds {
Some(r) => {
canvas.save_layer_bounds(layer, Rect::new(r[0], r[1], r[2], r[3]));
}
None => {
canvas.save_layer(layer);
}
}
let _ = canvas.draw_rect(Rect::new(8.0, 8.0, 56.0, 56.0), &Paint::fill(Color::WHITE));
canvas.restore();
let recording = canvas.finish();
prop_assert!(
recording_is_addressable(&recording).is_ok(),
"{}",
recording_is_addressable(&recording).unwrap_err()
);
}
}
#[test]
fn the_generated_sequences_reach_the_states_worth_reaching() {
use proptest::strategy::ValueTree;
use proptest::test_runner::TestRunner;
let mut runner = TestRunner::deterministic();
let strategy = ops();
let mut opened = 0usize;
let mut left_open = 0usize;
let mut over_restored = 0usize;
let mut drew = 0usize;
const TRIES: usize = 512;
for _ in 0..TRIES {
let ops = strategy
.new_tree(&mut runner)
.expect("the generator above is infallible")
.current();
let mut canvas = Canvas::new(SIZE);
let mut bottomed = false;
for op in &ops {
if matches!(op, Op::Restore) && canvas.save_depth() == 0 {
bottomed = true;
}
apply(&mut canvas, op);
}
if ops
.iter()
.any(|op| matches!(op, Op::SaveLayer(_) | Op::SaveLayerBounds(..)))
{
opened += 1;
}
if canvas.layer_depth() > 0 {
left_open += 1;
}
if bottomed {
over_restored += 1;
}
if canvas.finish().draw_count() > 0 {
drew += 1;
}
}
for (what, count) in [
("opened a layer", opened),
("left a layer open at finish", left_open),
("restored past the bottom", over_restored),
("recorded a draw", drew),
] {
assert!(
count * 10 >= TRIES,
"only {count} of {TRIES} generated sequences {what}, so the \
properties over that state are close to vacuous"
);
}
}
fn hostile_paint() -> impl Strategy<Value = Paint> {
(
(
hostile_color(),
prop_oneof![
3 => Just(Style::Fill),
1 => (hostile_coord(), hostile_coord()).prop_map(|(width, miter_limit)| {
Style::Stroke(StrokeStyle {
width,
cap: LineCap::Butt,
join: LineJoin::Miter,
miter_limit,
})
}),
],
prop::sample::select(
[
MaskBlurStyle::Normal,
MaskBlurStyle::Solid,
MaskBlurStyle::Outer,
MaskBlurStyle::Inner,
]
.as_slice(),
),
),
(
prop_oneof![
4 => Just(ImageFilter::None),
1 => (hostile_coord(), hostile_coord()).prop_map(|(x, y)| ImageFilter::Blur {
sigma_x: x,
sigma_y: y,
}),
1 => (hostile_coord(), hostile_coord()).prop_map(|(x, y)| ImageFilter::Dilate {
radius_x: x,
radius_y: y,
}),
],
prop_oneof![
4 => Just(ColorFilter::None),
1 => Just(ColorFilter::Gamma { direction: Gamma::SrgbToLinear }),
],
prop::option::of(
(
prop::collection::vec(hostile_coord(), 0..4),
hostile_coord(),
)
.prop_map(|(intervals, phase)| Dash::new(intervals, phase)),
),
),
(
hostile_coord(),
prop::sample::select(BlendMode::ALL),
prop::sample::select(BlendMode::ALL),
any::<bool>(),
),
)
.prop_map(
|(
(color, style, mask_blur_style),
(image_filter, color_filter, dash),
(mask_blur, blend, tint_blend, anti_alias),
)| Paint {
shader: Shader::Solid(color),
style,
mask_blur_style,
image_filter,
color_filter,
dash,
mask_blur,
blend,
tint_blend,
anti_alias,
shader_transform: Transform2D::IDENTITY,
opacity: 1.0,
},
)
}
fn hostile_shader_transform() -> impl Strategy<Value = Transform2D> {
prop::collection::vec(hostile_coord(), 9).prop_map(|c| {
Transform2D::from_column_major_4x4(&[
c[0], c[1], 0.0, c[2], c[3], c[4], 0.0, c[5], 0.0, 0.0, 1.0, 0.0, c[6], c[7], 0.0, c[8],
])
})
}
fn shaders_with_a_space() -> Vec<Paint> {
let stops = || {
vec![
GradientStop::new(Color::linear(1.0, 0.0, 0.0, 1.0), 0.0),
GradientStop::new(Color::linear(0.0, 0.0, 1.0, 1.0), 1.0),
]
};
vec![
Paint::image(0, Rect::new(0.0, 0.0, 64.0, 64.0)),
Paint::linear_gradient(Vec2::ZERO, Vec2::new(64.0, 0.0), stops()),
Paint::radial_gradient(Vec2::splat(64.0), 32.0, stops()),
Paint::conical_gradient(Vec2::splat(48.0), 4.0, Vec2::splat(64.0), 40.0, stops()),
Paint::sweep_gradient(Vec2::splat(64.0), 0.0, 3.0, stops()),
]
}
proptest! {
#![proptest_config(ProptestConfig { cases: 1024, ..ProptestConfig::default() })]
#[test]
fn a_hostile_shader_transform_records_something_addressable(
transform in hostile_shader_transform(),
opacity in hostile_coord(),
which in 0..5usize,
mesh in any::<bool>(),
) {
let paint = shaders_with_a_space()[which]
.clone()
.with_shader_transform(transform)
.with_opacity(opacity);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
if mesh {
let vertices = Vertices::textured(
VertexMode::Triangles,
vec![Vec2::new(0.0, 0.0), Vec2::new(96.0, 0.0), Vec2::new(0.0, 96.0)],
vec![Vec2::ZERO, Vec2::X, Vec2::Y],
)
.expect("mesh");
let _ = canvas.draw_vertices(&vertices, &paint);
} else {
let _ = canvas.draw_rect(Rect::new(16.0, 16.0, 112.0, 112.0), &paint);
}
let recording = canvas.finish();
prop_assert!(
recording_is_addressable(&recording).is_ok(),
"{}",
recording_is_addressable(&recording).unwrap_err()
);
}
}
fn hostile_layers() -> Vec<Layer> {
let base = Layer::opacity(1.0);
vec![
base,
Layer {
blur: Vec2::new(f32::INFINITY, 0.0),
..base
},
Layer {
blur: Vec2::new(f32::MAX, f32::MAX),
..base
},
Layer {
backdrop_blur: f32::INFINITY,
..base
},
Layer {
morphology: Some(Morphology {
radius: [1e20, 1e20],
dilate: true,
}),
..base
},
Layer {
matrix: Some(Transform2D::from(Affine2::from_scale(Vec2::new(
1.1754944e-38,
3.4028235e38,
)))),
..base
},
Layer {
alpha: f32::NAN,
blend: BlendMode::Clear,
..base
},
]
}
proptest! {
#![proptest_config(ProptestConfig { cases: 2048, ..ProptestConfig::default() })]
#[test]
fn a_paint_of_any_configuration_records_something_addressable(
paint in hostile_paint(),
opacity in hostile_coord(),
curved in any::<bool>(),
) {
let paint = paint.with_opacity(opacity);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
if curved {
let mut path = PathBuilder::new();
path.move_to(Vec2::new(16.0, 16.0));
path.cubic_to(
Vec2::new(96.0, 8.0),
Vec2::new(8.0, 96.0),
Vec2::new(112.0, 112.0),
);
let path = path.build();
let _ = canvas.draw_path(&path, &paint);
} else {
let _ = canvas.draw_rect(Rect::new(16.0, 16.0, 112.0, 112.0), &paint);
}
let recording = canvas.finish();
prop_assert!(
recording_is_addressable(&recording).is_ok(),
"{}",
recording_is_addressable(&recording).unwrap_err()
);
}
#[test]
fn a_paint_inside_a_filtered_layer_records_something_addressable(
paint in hostile_paint(),
opacity in hostile_coord(),
layer in prop::sample::select(hostile_layers()),
) {
let paint = paint.with_opacity(opacity);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
canvas.save_layer(layer);
let _ = canvas.draw_rect(Rect::new(16.0, 16.0, 112.0, 112.0), &paint);
canvas.restore();
let recording = canvas.finish();
prop_assert!(
recording_is_addressable(&recording).is_ok(),
"{}",
recording_is_addressable(&recording).unwrap_err()
);
}
}
#[test]
fn a_composition_deeper_than_anything_needs_is_refused_rather_than_fatal() {
fn nested(depth: usize) -> ImageFilter {
let mut filter = ImageFilter::Blur {
sigma_x: 1.0,
sigma_y: 1.0,
};
for _ in 0..depth {
filter = ImageFilter::Compose {
outer: Box::new(ImageFilter::Color(ColorFilter::Gamma {
direction: Gamma::SrgbToLinear,
})),
inner: Box::new(filter),
};
}
filter
}
let draw = |filter: &ImageFilter| -> (bool, usize) {
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
let taken = canvas
.save_layer_filtered(Layer::opacity(1.0), None, filter)
.is_ok();
let _ = canvas.draw_rect(Rect::new(8.0, 8.0, 56.0, 56.0), &Paint::fill(Color::WHITE));
canvas.restore();
(taken, canvas.finish().passes.len())
};
for depth in [1usize, 16, 64] {
let (taken, passes) = draw(&nested(depth));
assert!(taken, "a composition {depth} deep was refused");
assert!(
passes > depth,
"a composition {depth} deep produced only {passes} passes"
);
}
for depth in [4096usize, 8192] {
let (taken, passes) = draw(&nested(depth));
assert!(
!taken,
"a composition {depth} deep was accepted, which is the crash this \
refusal replaced"
);
assert_eq!(
passes, 1,
"a refused filter still built {passes} passes, so the layer was opened \
after all"
);
}
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
assert!(
canvas
.save_layer_backdrop(Layer::opacity(1.0), None, &nested(4096))
.is_err(),
"a backdrop filter deeper than the limit was accepted"
);
let mut canvas = Canvas::new(SIZE);
canvas.clear(Color::BLACK);
assert!(
canvas
.draw_rect(
Rect::new(8.0, 8.0, 56.0, 56.0),
&Paint::fill(Color::WHITE).with_image_filter(nested(4096)),
)
.is_err(),
"a paint's filter deeper than the limit was accepted"
);
}