1use crate::os_lib::dom::{Node, NodeType};
9use alloc::boxed::Box;
10use alloc::collections::{BTreeMap, BTreeSet};
11use alloc::rc::Rc;
12use alloc::string::String;
13use alloc::vec::Vec;
14
15#[derive(Clone, Copy)]
17pub(crate) struct KeyHasher {
18 a: u64,
19 b: u64,
20}
21
22impl KeyHasher {
23 pub(crate) fn new() -> Self {
24 Self { a: 0xcbf2_9ce4_8422_2325, b: 0x6c62_272e_07bb_0142 }
25 }
26
27 pub(crate) fn bytes(&mut self, s: &[u8]) {
28 for &x in s {
29 self.a = (self.a ^ x as u64).wrapping_mul(0x0000_0100_0000_01b3);
30 self.b = (self.b.rotate_left(5) ^ x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
31 }
32 self.u64(s.len() as u64);
34 }
35
36 pub(crate) fn u64(&mut self, v: u64) {
37 for i in 0..8 {
38 let x = (v >> (i * 8)) as u8;
39 self.a = (self.a ^ x as u64).wrapping_mul(0x0000_0100_0000_01b3);
40 self.b = (self.b.rotate_left(5) ^ x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
41 }
42 }
43
44 pub(crate) fn key(&mut self, k: MemoKey) {
45 self.u64(k.0);
46 self.u64(k.1);
47 }
48
49 pub(crate) fn finish(&self) -> MemoKey {
50 (self.a, self.b)
51 }
52}
53
54pub(crate) type MemoKey = (u64, u64);
55
56#[inline]
59pub(crate) fn compute_node_features(nt: &NodeType) -> MemoKey {
60 crate::os_lib::dom::compute_node_features(nt)
61}
62
63#[inline]
65fn node_features(h: &mut KeyHasher, n: &Node) {
66 h.key(n.features_hash);
67}
68
69pub(crate) fn children_hash(node: &Node) -> MemoKey {
71 let mut h = KeyHasher::new();
72 h.u64(node.children.len() as u64);
73 for c in &node.children {
74 node_features(&mut h, c);
75 h.key(children_shape(c));
76 }
77 h.finish()
78}
79
80#[inline]
82pub(crate) fn node_subtree_hash(node: &Node) -> MemoKey {
83 node.subtree_hash
84}
85
86fn node_shape(h: &mut KeyHasher, n: &Node) {
88 match &n.node_type {
89 NodeType::Element { tag_name, .. } => {
90 h.u64(1);
91 h.bytes(tag_name.as_bytes());
92 }
93 NodeType::Text(t) => {
94 h.u64(2);
95 h.u64(u64::from(!t.is_empty()));
96 }
97 }
98}
99
100#[inline]
102pub(crate) fn children_shape(node: &Node) -> MemoKey {
103 node.children_shape_hash
104}
105
106pub(crate) fn sibling_keys(parent: &Node, full: bool, relevant: impl Fn(&Node) -> bool) -> Vec<(MemoKey, MemoKey)> {
116 let n = parent.children.len();
117 if full {
118 let all = children_hash(parent);
119 return (0..n)
120 .map(|i| {
121 let mut h = KeyHasher::new();
122 h.key(all);
123 h.u64(i as u64);
124 let k = h.finish();
125 (k, k)
126 })
127 .collect();
128 }
129 let mut after = alloc::vec![(0u64, 0u64); n];
130 let mut s = KeyHasher::new();
131 for i in (0..n).rev() {
132 if let (Some(slot), Some(c)) = (after.get_mut(i), parent.children.get(i)) {
133 *slot = s.finish();
134 node_shape(&mut s, c);
135 }
136 }
137 let mut p = KeyHasher::new();
139 p.u64(n as u64);
140 let mut q = p;
141 parent
142 .children
143 .iter()
144 .zip(after)
145 .map(|(c, a)| {
146 let mut h = p;
147 node_features(&mut h, c);
148 h.key(a);
149 let mut pos = q;
150 node_shape(&mut pos, c);
151 pos.key(a);
152 if relevant(c) {
153 node_features(&mut p, c);
155 p.key(children_shape(c));
156 } else {
157 node_shape(&mut p, c);
158 }
159 node_shape(&mut q, c);
160 (h.finish(), pos.finish())
161 })
162 .collect()
163}
164
165#[derive(Clone, Copy, Default)]
169pub(crate) struct NodeKeys {
170 pub own: MemoKey,
171 pub desc: MemoKey,
172}
173
174pub(crate) fn desc_key(parent: MemoKey, n: &Node, extra: &[MemoKey]) -> MemoKey {
176 let mut h = KeyHasher::new();
177 h.key(parent);
178 node_features(&mut h, n);
179 for &k in extra {
180 h.key(k);
181 }
182 h.finish()
183}
184
185pub(crate) fn child_key(parent: MemoKey, siblings: MemoKey, own_children: MemoKey) -> MemoKey {
187 let mut h = KeyHasher::new();
188 h.key(parent);
189 h.key(siblings);
190 h.key(own_children);
191 h.finish()
192}
193
194#[derive(Clone)]
196pub(crate) struct MemoEntry {
197 pub specified: Rc<BTreeMap<String, String>>,
198 pub css_vars: Rc<super::types::CssVars>,
199 pub counters_after: BTreeMap<String, i64>,
200 pub counters_reset: BTreeSet<String>,
201 pub hover: Option<BTreeMap<String, String>>,
202 pub focus: Option<BTreeMap<String, String>>,
203 pub active: Option<BTreeMap<String, String>>,
204 pub inherited_for_children: Rc<BTreeMap<String, String>>,
205 pub root_font_px: Option<f32>,
207 pub result_hash: MemoKey,
209 used_gen: u32,
210}
211
212impl MemoEntry {
213 #[allow(clippy::too_many_arguments)]
214 pub(crate) fn new(
215 specified: Rc<BTreeMap<String, String>>,
216 css_vars: Rc<super::types::CssVars>,
217 counters_after: BTreeMap<String, i64>,
218 counters_reset: BTreeSet<String>,
219 hover: Option<BTreeMap<String, String>>,
220 focus: Option<BTreeMap<String, String>>,
221 active: Option<BTreeMap<String, String>>,
222 inherited_for_children: Rc<BTreeMap<String, String>>,
223 root_font_px: Option<f32>,
224 ) -> Self {
225 let mut h = KeyHasher::new();
226 for m in [&*specified, &*inherited_for_children] {
227 h.u64(m.len() as u64);
228 for (k, v) in m {
229 h.bytes(k.as_bytes());
230 h.bytes(v.as_bytes());
231 }
232 }
233 h.key(css_vars.content_hash());
234 let result_hash = h.finish();
235 Self { specified, css_vars, counters_after, counters_reset, hover, focus, active, inherited_for_children, root_font_px, result_hash, used_gen: 0 }
236 }
237
238 pub(crate) fn same_result(&self, o: &MemoEntry) -> bool {
240 *self.specified == *o.specified
241 && *self.css_vars == *o.css_vars
242 && self.counters_after == o.counters_after
243 && self.counters_reset == o.counters_reset
244 && self.hover == o.hover
245 && self.focus == o.focus
246 && self.active == o.active
247 && *self.inherited_for_children == *o.inherited_for_children
248 }
249}
250
251#[derive(Clone)]
253pub(crate) struct CachedPseudoStyles {
254 pub hover: Option<BTreeMap<String, String>>,
255 pub focus: Option<BTreeMap<String, String>>,
256 pub active: Option<BTreeMap<String, String>>,
257}
258
259#[derive(Clone)]
261pub(crate) enum CachedSubtreeChild {
262 Text,
263 Element(Rc<CachedElementSubtree>),
264}
265
266pub(crate) struct CachedElementSubtree {
270 pub node_features: MemoKey,
271 pub specified_values: Rc<BTreeMap<String, String>>,
272 pub css_vars: Rc<super::types::CssVars>,
273 pub inherited_for_children: Rc<BTreeMap<String, String>>,
274 pub text_child_specified: Option<Rc<BTreeMap<String, String>>>,
275 pub pseudo: Option<Box<CachedPseudoStyles>>,
276 pub root_font_px: Option<f32>,
277 pub children: Vec<CachedSubtreeChild>,
278 pub element_count: u32,
279}
280
281impl CachedElementSubtree {
282 pub(crate) fn instantiate<'a>(&self, node: &'a Node) -> Option<super::types::StyledNode<'a>> {
285 let NodeType::Element { .. } = &node.node_type else {
286 return None;
287 };
288 if node.features_hash != self.node_features || node.children.len() != self.children.len() {
289 return None;
290 }
291 let mut out_children = Vec::with_capacity(self.children.len());
292 for (cached_ch, dom_ch) in self.children.iter().zip(node.children.iter()) {
293 match cached_ch {
294 CachedSubtreeChild::Text => {
295 let NodeType::Text(_) = &dom_ch.node_type else {
296 return None;
297 };
298 let text_spec = self.text_child_specified.clone().unwrap_or_else(|| {
299 let mut m = BTreeMap::new();
300 m.insert(String::from("display"), String::from("inline"));
301 for (k, v) in self.inherited_for_children.iter() {
302 m.insert(k.clone(), v.clone());
303 }
304 Rc::new(m)
305 });
306 out_children.push(super::types::StyledNode {
307 node: dom_ch,
308 specified_values: text_spec,
309 hover_values: None,
310 focus_values: None,
311 active_values: None,
312 css_vars: self.css_vars.clone(),
313 children: Vec::new(),
314 edges_cache: Default::default(),
315 intrinsic_size_cache: Default::default(),
316 block_intrinsic_cache: Default::default(),
317 layout_subtree_cache: Default::default(),
318 });
319 }
320 CachedSubtreeChild::Element(sub) => {
321 out_children.push(sub.instantiate(dom_ch)?);
322 }
323 }
324 }
325 super::cascade::attach_flow_pseudo_boxes(node, &self.specified_values, &self.css_vars, &mut out_children);
326 let (hover_values, focus_values, active_values) = match &self.pseudo {
327 Some(p) => (p.hover.clone(), p.focus.clone(), p.active.clone()),
328 None => (None, None, None),
329 };
330 Some(super::types::StyledNode {
331 node,
332 specified_values: self.specified_values.clone(),
333 hover_values,
334 focus_values,
335 active_values,
336 css_vars: self.css_vars.clone(),
337 children: out_children,
338 edges_cache: Default::default(),
339 intrinsic_size_cache: Default::default(),
340 block_intrinsic_cache: Default::default(),
341 layout_subtree_cache: Default::default(),
342 })
343 }
344}
345
346struct CachedSubtreeEntry {
347 tree: Rc<CachedElementSubtree>,
348 used_gen: u32,
349}
350
351#[derive(Default)]
353pub struct StyleMemo {
354 global: MemoKey,
356 entries: BTreeMap<MemoKey, MemoEntry>,
357 features_states: BTreeMap<MemoKey, u8>,
361 subtrees: BTreeMap<MemoKey, CachedSubtreeEntry>,
363 generation: u32,
364 pub(crate) enabled: bool,
366 pub verify: bool,
368 pub(crate) hits: u32,
369 pub(crate) misses: u32,
370 pub(crate) mismatches: u32,
371 pub(crate) subtree_hits: u32,
372 pub(crate) subtree_misses: u32,
373 pub(crate) skips: [u32; 4],
375}
376
377impl StyleMemo {
378 const MAX_ENTRIES: usize = 24576;
379 const MAX_SUBTREES: usize = 12288;
380 const MAX_FEATURE_STATES: usize = 16384;
381 pub(crate) const MAX_SUBTREE_ELEMENTS: u32 = 16384;
382
383 pub(crate) fn begin(&mut self, sheet_id: usize) {
385 let mut h = KeyHasher::new();
386 h.u64(sheet_id as u64);
387 h.u64(crate::os_lib::viewport::VIEWPORT_HINT_W.load(core::sync::atomic::Ordering::Relaxed) as u64);
388 h.u64(crate::os_lib::viewport::VIEWPORT_HINT_H.load(core::sync::atomic::Ordering::Relaxed) as u64);
389 h.u64(crate::os_lib::viewport::CONTAINER_HINT_W.load(core::sync::atomic::Ordering::Relaxed) as u64);
390 h.u64(crate::os_lib::viewport::CONTAINER_HINT_H.load(core::sync::atomic::Ordering::Relaxed) as u64);
391 h.bytes(crate::os_lib::viewport::CURRENT_TARGET_ID.lock().as_bytes());
392 h.bytes(crate::os_lib::viewport::DOCUMENT_LANG.lock().as_bytes());
393 h.u64(u64::from(crate::os_lib::viewport::PREFERS_DARK.load(core::sync::atomic::Ordering::Relaxed)));
394 let g = h.finish();
395 if g != self.global {
396 self.entries.clear();
397 self.features_states.clear();
398 self.subtrees.clear();
399 self.global = g;
400 }
401 self.generation = self.generation.wrapping_add(1).max(1);
402 self.enabled = crate::os_lib::viewport::FOCUS_WITHIN_PTRS.lock().is_empty();
403 self.hits = 0;
404 self.misses = 0;
405 self.mismatches = 0;
406 self.subtree_hits = 0;
407 self.subtree_misses = 0;
408 self.skips = [0; 4];
409 }
410
411 pub fn clear(&mut self) {
413 self.entries.clear();
414 self.features_states.clear();
415 self.subtrees.clear();
416 self.global = (0, 0);
417 }
418
419 pub(crate) fn end(&mut self) {
421 let g = self.generation;
422 self.entries.retain(|_, e| e.used_gen != 0 && g.wrapping_sub(e.used_gen) <= 3);
423 if self.entries.len() > Self::MAX_ENTRIES {
424 self.entries.retain(|_, e| e.used_gen == g);
425 }
426 self.subtrees.retain(|_, e| e.used_gen != 0 && g.wrapping_sub(e.used_gen) <= 3);
427 if self.subtrees.len() > Self::MAX_SUBTREES {
428 self.subtrees.retain(|_, e| e.used_gen == g);
429 }
430 if self.features_states.len() > Self::MAX_FEATURE_STATES {
431 self.features_states.clear();
432 }
433 }
434
435 pub(crate) fn get(&mut self, k: &MemoKey) -> Option<MemoEntry> {
436 let g = self.generation.max(1);
437 self.entries.get_mut(k).map(|e| {
438 e.used_gen = g;
439 e.clone()
440 })
441 }
442
443 pub(crate) fn put(&mut self, k: MemoKey, mut e: MemoEntry) {
444 e.used_gen = self.generation.max(1);
445 self.entries.insert(k, e);
446 }
447
448 #[inline]
449 pub(crate) fn get_state_bits(&self, features_hash: &MemoKey) -> Option<u8> {
450 self.features_states.get(features_hash).copied()
451 }
452
453 #[inline]
454 pub(crate) fn put_state_bits(&mut self, features_hash: MemoKey, bits: u8) {
455 if self.features_states.len() < Self::MAX_FEATURE_STATES {
456 self.features_states.insert(features_hash, bits);
457 }
458 }
459
460 pub(crate) fn get_subtree(&mut self, k: &MemoKey) -> Option<Rc<CachedElementSubtree>> {
461 let g = self.generation.max(1);
462 self.subtrees.get_mut(k).map(|e| {
463 e.used_gen = g;
464 e.tree.clone()
465 })
466 }
467
468 pub(crate) fn put_subtree(&mut self, k: MemoKey, tree: Rc<CachedElementSubtree>) {
469 if self.subtrees.len() < Self::MAX_SUBTREES {
470 self.subtrees.insert(
471 k,
472 CachedSubtreeEntry {
473 tree,
474 used_gen: self.generation.max(1),
475 },
476 );
477 }
478 }
479
480 pub fn stats(&self) -> (u32, u32, u32, usize, [u32; 4], bool) {
481 (self.hits, self.misses, self.mismatches, self.entries.len(), self.skips, self.enabled)
482 }
483
484 pub fn subtree_stats(&self) -> (u32, u32, usize) {
486 (self.subtree_hits, self.subtree_misses, self.subtrees.len())
487 }
488}