use crate::LayoutId;
#[derive(Clone, Copy, Default)]
struct Entry<V> {
node: u64,
pass: u32,
value: V,
}
pub(crate) struct LayoutIdMap<V> {
entries: Vec<Entry<V>>,
pass: u32,
}
impl<V> Default for LayoutIdMap<V> {
fn default() -> Self {
Self {
entries: Vec::new(),
pass: 1,
}
}
}
#[inline]
fn raw(id: &LayoutId) -> u64 {
u64::from(taffy::NodeId::from(*id))
}
#[inline]
fn slot(raw: u64) -> usize {
raw as u32 as usize
}
impl<V: Copy + Default> LayoutIdMap<V> {
#[inline]
pub(crate) fn get(&self, id: &LayoutId) -> Option<&V> {
let raw = raw(id);
self.entries
.get(slot(raw))
.filter(|entry| entry.pass == self.pass && entry.node == raw)
.map(|entry| &entry.value)
}
#[inline]
pub(crate) fn insert(&mut self, id: LayoutId, value: V) {
let raw = raw(&id);
let slot = slot(raw);
if slot >= self.entries.len() {
self.entries.resize(slot + 1, Entry::default());
}
self.entries[slot] = Entry {
node: raw,
pass: self.pass,
value,
};
}
#[inline]
pub(crate) fn remove(&mut self, id: &LayoutId) {
let raw = raw(id);
if let Some(entry) = self.entries.get_mut(slot(raw))
&& entry.node == raw
{
entry.pass = 0;
}
}
pub(crate) fn clear(&mut self) {
self.pass = self.pass.wrapping_add(1);
if self.pass == 0 {
self.entries.fill(Entry::default());
self.pass = 1;
}
}
}
#[cfg(test)]
mod tests {
use super::LayoutIdMap;
use crate::LayoutId;
use taffy::{TaffyTree, style::Style};
#[test]
fn entries_last_one_pass_and_belong_to_one_node_of_a_slot() {
let mut taffy: TaffyTree<()> = TaffyTree::new();
let first: LayoutId = taffy.new_leaf(Style::default()).unwrap().into();
let mut map = LayoutIdMap::<u32>::default();
map.insert(first, 7);
assert_eq!(map.get(&first), Some(&7));
taffy.remove(first.into()).unwrap();
let second: LayoutId = taffy.new_leaf(Style::default()).unwrap().into();
assert_ne!(first, second);
assert_eq!(map.get(&second), None);
map.remove(&second);
assert_eq!(map.get(&first), Some(&7));
map.insert(second, 8);
assert_eq!(map.get(&second), Some(&8));
assert_eq!(map.get(&first), None);
map.remove(&second);
assert_eq!(map.get(&second), None);
map.insert(second, 9);
map.clear();
assert_eq!(map.get(&second), None);
map.insert(second, 10);
assert_eq!(map.get(&second), Some(&10));
}
}