use rustc_hash::FxHashMap;
use std::hash::Hash;
use crate::parser::{RelativeSelector, SelectorKey};
use crate::{tree::OpaqueElement, SelectorImpl};
#[derive(Clone, Copy)]
pub enum RelativeSelectorCachedMatch {
Matched,
NotMatched,
}
impl RelativeSelectorCachedMatch {
pub fn matched(&self) -> bool {
matches!(*self, Self::Matched)
}
}
#[derive(Clone, Copy, Hash, Eq, PartialEq)]
struct Key {
element: OpaqueElement,
selector: SelectorKey,
}
impl Key {
pub fn new<Impl: SelectorImpl>(
element: OpaqueElement,
selector: &RelativeSelector<Impl>,
) -> Self {
Key {
element,
selector: SelectorKey::new(&selector.selector),
}
}
}
#[derive(Default)]
pub struct RelativeSelectorCache {
cache: FxHashMap<Key, RelativeSelectorCachedMatch>,
}
impl RelativeSelectorCache {
pub fn add<Impl: SelectorImpl>(
&mut self,
anchor: OpaqueElement,
selector: &RelativeSelector<Impl>,
matched: RelativeSelectorCachedMatch,
) {
self.cache.insert(Key::new(anchor, selector), matched);
}
pub fn lookup<Impl: SelectorImpl>(
&mut self,
element: OpaqueElement,
selector: &RelativeSelector<Impl>,
) -> Option<RelativeSelectorCachedMatch> {
self.cache.get(&Key::new(element, selector)).copied()
}
}