use std::cell::{Cell, RefCell};
use crate::layout::{Constraints, layout_result::LayoutResult};
const MAX_CACHED_LAYOUTS: usize = 2;
pub struct LayoutCache {
inner: RefCell<Vec<CachedLayout>>,
local_dirty: Cell<bool>,
descendant_dirty: Cell<bool>,
descendants_match_front: Cell<bool>,
}
#[derive(Clone)]
struct CachedLayout {
constraints: Constraints,
result: LayoutResult,
}
impl LayoutCache {
pub fn new() -> Self {
Self {
inner: RefCell::new(Vec::new()),
local_dirty: Cell::new(false),
descendant_dirty: Cell::new(false),
descendants_match_front: Cell::new(true),
}
}
pub fn get(&self, constraints: Constraints) -> Option<LayoutResult> {
if self.is_dirty() {
return None;
}
let mut entries = self.inner.borrow_mut();
let index = entries.iter().position(|cached| cached.constraints == constraints)?;
if index > 0 {
let served = entries.remove(index);
entries.insert(0, served);
self.descendants_match_front.set(false);
}
Some(entries[0].result.clone())
}
pub(crate) fn contains(&self, constraints: Constraints) -> bool {
if self.is_dirty() {
return false;
}
self
.inner
.borrow()
.iter()
.any(|cached| cached.constraints == constraints)
}
pub(crate) fn record_reuse(&self, constraints: Constraints, result: &LayoutResult) {
let mut entries = self.inner.borrow_mut();
let reused = match entries.iter().position(|cached| cached.constraints == constraints) {
Some(0) => return,
Some(index) => entries.remove(index),
None => CachedLayout {
constraints,
result: result.clone(),
},
};
entries.insert(0, reused);
entries.truncate(MAX_CACHED_LAYOUTS);
self.descendants_match_front.set(false);
}
pub(crate) fn get_repairable(&self, constraints: Constraints) -> Option<LayoutResult> {
if !self.descendants_match_front.get() {
return None;
}
let entries = self.inner.borrow();
let front = entries.first()?;
(front.constraints == constraints).then(|| front.result.clone())
}
pub(crate) fn constraints(&self) -> Option<Constraints> {
self.inner.borrow().first().map(|cached| cached.constraints)
}
pub(crate) fn has_cached_result(&self) -> bool {
!self.inner.borrow().is_empty()
}
pub(crate) fn cached_entry(&self) -> Option<(Constraints, crate::layout::Size)> {
self
.inner
.borrow()
.first()
.map(|cached| (cached.constraints, cached.result.size))
}
pub(crate) fn preserve_from(&self, old: &Self) {
*self.inner.borrow_mut() = old.inner.borrow().clone();
self.descendants_match_front.set(old.descendants_match_front.get());
self.local_dirty.set(self.local_dirty.get() || old.local_dirty.get());
self
.descendant_dirty
.set(self.descendant_dirty.get() || old.descendant_dirty.get());
}
pub fn store(&self, constraints: Constraints, result: LayoutResult) {
let mut borrow = self.inner.borrow_mut();
if self.is_dirty() {
borrow.clear();
} else if let Some(index) = borrow.iter().position(|cached| cached.constraints == constraints) {
borrow.remove(index);
}
borrow.insert(0, CachedLayout { constraints, result });
borrow.truncate(MAX_CACHED_LAYOUTS);
self.descendants_match_front.set(true);
self.clear_dirty();
}
pub fn invalidate(&self) {
self.inner.borrow_mut().clear();
self.descendants_match_front.set(true);
self.clear_dirty();
}
pub(crate) fn mark_local_dirty(&self) {
self.local_dirty.set(true);
}
pub(crate) fn mark_descendant_dirty(&self) {
self.descendant_dirty.set(true);
}
pub(crate) fn is_local_dirty(&self) -> bool {
self.local_dirty.get()
}
pub(crate) fn is_descendant_dirty(&self) -> bool {
self.descendant_dirty.get()
}
pub(crate) fn is_dirty(&self) -> bool {
self.is_local_dirty() || self.is_descendant_dirty()
}
fn clear_dirty(&self) {
self.local_dirty.set(false);
self.descendant_dirty.set(false);
}
pub(crate) fn estimated_memory_bytes(&self) -> usize {
let borrow = self.inner.borrow();
let cached_bytes = borrow
.iter()
.map(|cached| std::mem::size_of::<CachedLayout>() + cached.result.estimated_memory_bytes())
.sum::<usize>();
std::mem::size_of::<Self>() + borrow.capacity() * std::mem::size_of::<CachedLayout>() + cached_bytes
}
}
impl Default for LayoutCache {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::layout::Size;
fn constraints(max_width: f32) -> Constraints {
Constraints {
min_width: 0.0,
min_height: 0.0,
max_width,
max_height: f32::MAX,
}
}
fn result(width: f32) -> LayoutResult {
LayoutResult {
size: Size::new(width, 10.0),
children: vec![],
text_layout: None,
dropped: false,
}
}
#[test]
fn store_on_a_dirty_cache_drops_stale_sibling_entries() {
let cache = LayoutCache::new();
cache.store(constraints(100.0), result(40.0));
cache.store(constraints(90.0), result(38.0));
assert!(cache.get(constraints(100.0)).is_some());
assert!(cache.get(constraints(90.0)).is_some());
cache.mark_descendant_dirty();
cache.store(constraints(90.0), result(45.0));
assert_eq!(
cache.get(constraints(90.0)).map(|cached| cached.size.width),
Some(45.0),
"the freshly stored entry is served"
);
assert!(
cache.get(constraints(100.0)).is_none(),
"the pre-invalidation sibling entry must not be served as fresh"
);
}
#[test]
fn clean_stores_keep_both_entries() {
let cache = LayoutCache::new();
cache.store(constraints(100.0), result(40.0));
cache.store(constraints(90.0), result(38.0));
assert_eq!(
cache.get(constraints(100.0)).map(|cached| cached.size.width),
Some(40.0)
);
assert_eq!(cache.get(constraints(90.0)).map(|cached| cached.size.width), Some(38.0));
}
#[test]
fn serving_an_entry_makes_its_constraints_the_front_ones() {
let cache = LayoutCache::new();
cache.store(constraints(1440.0), result(1440.0));
cache.store(constraints(960.0), result(960.0));
assert!(cache.get(constraints(1440.0)).is_some());
assert_eq!(cache.constraints().map(|front| front.max_width), Some(1440.0));
assert_eq!(cache.cached_entry().map(|(_, size)| size.width), Some(1440.0));
}
#[test]
fn a_repair_needs_the_front_entry_its_descendants_were_laid_out_for() {
let cache = LayoutCache::new();
cache.store(constraints(1440.0), result(1440.0));
cache.store(constraints(960.0), result(960.0));
assert!(cache.get_repairable(constraints(960.0)).is_some());
assert!(
cache.get_repairable(constraints(1440.0)).is_none(),
"an entry behind the front one is not repairable"
);
assert!(cache.get(constraints(1440.0)).is_some());
assert!(
cache.get_repairable(constraints(1440.0)).is_none(),
"a served older entry skipped its descendants"
);
assert!(
cache.get(constraints(1440.0)).is_some(),
"the served entry is still a clean hit"
);
cache.store(constraints(1440.0), result(1440.0));
assert!(cache.get_repairable(constraints(1440.0)).is_some());
}
#[test]
fn preserving_a_cache_keeps_whether_its_descendants_match_the_front_entry() {
let old = LayoutCache::new();
old.store(constraints(1440.0), result(1440.0));
old.store(constraints(960.0), result(960.0));
assert!(old.get(constraints(1440.0)).is_some());
let new = LayoutCache::new();
new.preserve_from(&old);
assert!(new.get_repairable(constraints(1440.0)).is_none());
}
#[test]
fn a_reused_result_becomes_the_front_entry() {
let cache = LayoutCache::new();
cache.store(constraints(292.0), result(292.0));
cache.store(constraints(300.0), result(300.0));
cache.record_reuse(constraints(292.0), &result(292.0));
assert_eq!(cache.constraints().map(|front| front.max_width), Some(292.0));
assert!(cache.get_repairable(constraints(292.0)).is_none());
cache.store(constraints(300.0), result(300.0));
cache.store(constraints(310.0), result(310.0));
cache.record_reuse(constraints(292.0), &result(292.0));
assert_eq!(
cache.cached_entry().map(|(front, size)| (front.max_width, size.width)),
Some((292.0, 292.0))
);
assert!(cache.get(constraints(310.0)).is_some(), "the newer entry stays");
}
}