Source code

Revision control

Other Tools

1
/* This Source Code Form is subject to the terms of the Mozilla Public
2
* License, v. 2.0. If a copy of the MPL was not distributed with this
3
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5
use crate::tree::OpaqueElement;
6
use fxhash::FxHashMap;
7
8
/// A cache to speed up matching of nth-index-like selectors.
9
///
10
/// See [1] for some discussion around the design tradeoffs.
11
///
13
#[derive(Default)]
14
pub struct NthIndexCache {
15
nth: NthIndexCacheInner,
16
nth_last: NthIndexCacheInner,
17
nth_of_type: NthIndexCacheInner,
18
nth_last_of_type: NthIndexCacheInner,
19
}
20
21
impl NthIndexCache {
22
/// Gets the appropriate cache for the given parameters.
23
pub fn get(&mut self, is_of_type: bool, is_from_end: bool) -> &mut NthIndexCacheInner {
24
match (is_of_type, is_from_end) {
25
(false, false) => &mut self.nth,
26
(false, true) => &mut self.nth_last,
27
(true, false) => &mut self.nth_of_type,
28
(true, true) => &mut self.nth_last_of_type,
29
}
30
}
31
}
32
33
/// The concrete per-pseudo-class cache.
34
#[derive(Default)]
35
pub struct NthIndexCacheInner(FxHashMap<OpaqueElement, i32>);
36
37
impl NthIndexCacheInner {
38
/// Does a lookup for a given element in the cache.
39
pub fn lookup(&mut self, el: OpaqueElement) -> Option<i32> {
40
self.0.get(&el).map(|x| *x)
41
}
42
43
/// Inserts an entry into the cache.
44
pub fn insert(&mut self, element: OpaqueElement, index: i32) {
45
self.0.insert(element, index);
46
}
47
48
/// Returns whether the cache is empty.
49
pub fn is_empty(&self) -> bool {
50
self.0.is_empty()
51
}
52
}