use std::collections::HashMap;
use accesskit::NodeId;
use crate::tree::{A11yNode, WidgetRole};
#[derive(Debug, Default)]
pub struct NodePool {
active: HashMap<NodeId, A11yNode>,
free_list: Vec<A11yNode>,
}
impl NodePool {
pub fn new() -> Self {
Self::default()
}
pub fn alloc(&mut self, id: NodeId, node: A11yNode) {
self.active.insert(id, node);
}
pub fn alloc_recycled(
&mut self,
id: NodeId,
role: WidgetRole,
label: Option<String>,
) -> &mut A11yNode {
let mut node = match self.free_list.pop() {
Some(mut recycled) => {
recycled.id = id;
recycled.role = role;
recycled.label = label;
recycled.children.clear();
recycled.props = crate::props::A11yNodeProps::default();
recycled.text_content = None;
recycled
}
None => A11yNode::simple(id, role, label),
};
node.id = id;
self.active.insert(id, node);
self.active
.get_mut(&id)
.unwrap_or_else(|| unreachable!("just inserted"))
}
pub fn get(&self, id: &NodeId) -> Option<&A11yNode> {
self.active.get(id)
}
pub fn get_mut(&mut self, id: &NodeId) -> Option<&mut A11yNode> {
self.active.get_mut(id)
}
pub fn recycle(&mut self) {
for (_, node) in self.active.drain() {
self.free_list.push(node);
}
}
pub fn active_count(&self) -> usize {
self.active.len()
}
pub fn free_count(&self) -> usize {
self.free_list.len()
}
pub fn clear(&mut self) {
self.active.clear();
self.free_list.clear();
}
pub fn iter_active(&self) -> impl Iterator<Item = (&NodeId, &A11yNode)> {
self.active.iter()
}
}