fix(web): optimize and fix present_with_damage (#150)

Co-authored-by: daxpedda <daxpedda@gmail.com>
This commit is contained in:
Benoît Cortier 2023-09-09 11:30:38 -04:00 committed by GitHub
parent 9b44f2eaea
commit 908408ba80
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 85 additions and 14 deletions

View file

@ -1,6 +1,10 @@
// Not needed on all platforms
#![allow(dead_code)]
use std::cmp;
use std::num::NonZeroU32;
use crate::Rect;
use crate::SoftBufferError;
/// Takes a mutable reference to a container and a function deriving a
@ -44,6 +48,41 @@ impl<'a, T: 'static + ?Sized, U: 'static + ?Sized> BorrowStack<'a, T, U> {
}
}
/// Calculates the smallest `Rect` necessary to represent all damaged `Rect`s.
pub(crate) fn union_damage(damage: &[Rect]) -> Option<Rect> {
struct Region {
left: u32,
top: u32,
bottom: u32,
right: u32,
}
let region = damage
.iter()
.map(|rect| Region {
left: rect.x,
top: rect.y,
right: rect.x + rect.width.get(),
bottom: rect.y + rect.height.get(),
})
.reduce(|mut prev, next| {
prev.left = cmp::min(prev.left, next.left);
prev.top = cmp::min(prev.top, next.top);
prev.right = cmp::max(prev.right, next.right);
prev.bottom = cmp::max(prev.bottom, next.bottom);
prev
})?;
Some(Rect {
x: region.left,
y: region.top,
width: NonZeroU32::new(region.right - region.left)
.expect("`right` must always be bigger then `left`"),
height: NonZeroU32::new(region.bottom - region.top)
.expect("`bottom` must always be bigger then `top`"),
})
}
#[cfg(test)]
mod tests {
use super::*;