use crate::ui_tree::UITree;
use std::cell::RefCell;
use std::collections::HashMap;
#[derive(Debug, Clone, Default)]
pub struct Children<Msg>(pub Vec<UITree<Msg>>);
impl<Msg> Children<Msg> {
pub fn none() -> Self {
Children(Vec::new())
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn len(&self) -> usize {
self.0.len()
}
}
thread_local! {
static MEMO_CACHE: RefCell<HashMap<u64, Box<dyn std::any::Any>>> =
RefCell::new(HashMap::new());
}
pub fn memoize<P, Msg, F>(id: u64, key: P, build: F) -> UITree<Msg>
where
P: PartialEq + Clone + 'static,
Msg: Clone + 'static,
F: FnOnce(&P) -> UITree<Msg>,
{
MEMO_CACHE.with(|cache| {
let mut cache = cache.borrow_mut();
if let Some(entry) = cache.get(&id) {
if let Some((prev_key, prev_tree)) =
entry.downcast_ref::<(P, UITree<Msg>)>()
{
if *prev_key == key {
return prev_tree.clone();
}
}
}
let tree = build(&key);
cache.insert(id, Box::new((key, tree.clone())) as Box<dyn std::any::Any>);
tree
})
}