Skip to main content

atmos/os_lib/web_engine/
inline_style_cache.rs

1//! インライン `<style>` ブロック単位の 128 ビットハッシュ・差分パースキャッシュ(TODO P5b)。
2//!
3//! 従来は毎回 DOM から全 `<style>` テキストを 1 本の巨大文字列へ連結して文字列比較を行い、
4//! 1 つの `<style>` が追加・変更(あるいは空の `<style>` が増減)するたびに
5//! 全 `<style>` ブロックを先頭からまとめて再パースしていた。
6//!
7//! 本モジュールは、非空 `<style>` 要素を個別のブロックとしてゼロコピー(可能時)で収集し、
8//! - 空・空白のみの `<style>` 要素は無視して不要なキャッシュ無効化を防ぐ
9//! - ブロック列全体の 128 ビットハッシュ比較により O(1) で再パース要否を判定する
10//! - 不一致時もブロック単位のパースメモ (`InlineStyleParseMemo`) により、変更された
11//!   `<style>` ブロックのみを差分パースし、`@layer` 順序も正確に引き継いで結合する。
12
13extern crate alloc;
14
15use alloc::borrow::Cow;
16use alloc::collections::BTreeMap;
17use alloc::string::String;
18use alloc::vec::Vec;
19use crate::os_lib::css::StyleSheet;
20use crate::os_lib::dom::{Node, NodeType};
21
22/// 128 ビット FNV-1a ハッシュ(2 本の独立乗数)。
23#[inline]
24fn fnv_step(a: &mut u64, b: &mut u64, x: u8) {
25    *a = (*a ^ x as u64).wrapping_mul(0x0000_0100_0000_01b3);
26    *b = (b.rotate_left(5) ^ x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
27}
28
29#[inline]
30fn fnv_u64(a: &mut u64, b: &mut u64, v: u64) {
31    for i in 0..8 {
32        fnv_step(a, b, (v >> (i * 8)) as u8);
33    }
34}
35
36pub fn fnv_hash128(s: &str) -> (u64, u64) {
37    let mut a: u64 = 0xcbf2_9ce4_8422_2325;
38    let mut b: u64 = 0x6c62_272e_07bb_0142;
39    for &x in s.as_bytes() {
40        fnv_step(&mut a, &mut b, x);
41    }
42    fnv_u64(&mut a, &mut b, s.len() as u64);
43    (a, b)
44}
45
46pub fn hash_layers(layers: &[String]) -> (u64, u64) {
47    let mut a: u64 = 0xcbf2_9ce4_8422_2325;
48    let mut b: u64 = 0x6c62_272e_07bb_0142;
49    fnv_u64(&mut a, &mut b, layers.len() as u64);
50    for l in layers {
51        for &x in l.as_bytes() {
52            fnv_step(&mut a, &mut b, x);
53        }
54        fnv_u64(&mut a, &mut b, l.len() as u64);
55    }
56    (a, b)
57}
58
59#[inline]
60pub fn mix_hashes(h1: (u64, u64), h2: (u64, u64)) -> (u64, u64) {
61    let mut a = 0xcbf2_9ce4_8422_2325;
62    let mut b = 0x6c62_272e_07bb_0142;
63    fnv_u64(&mut a, &mut b, h1.0);
64    fnv_u64(&mut a, &mut b, h1.1);
65    fnv_u64(&mut a, &mut b, h2.0);
66    fnv_u64(&mut a, &mut b, h2.1);
67    (a, b)
68}
69
70/// 収集された 1 個分の非空インライン `<style>` ブロック。
71pub struct CollectedStyleBlock<'a> {
72    pub text: Cow<'a, str>,
73    pub hash: (u64, u64),
74}
75
76/// DOM 上の全 `<style>` ブロックをブロック単位に集めた結果。
77pub struct InlineStyleBlockCollection<'a> {
78    pub blocks: Vec<CollectedStyleBlock<'a>>,
79    pub combined_hash: (u64, u64),
80    pub total_bytes: usize,
81}
82
83/// DOM ツリーを走査し、非空 `<style>` 要素の内容をブロックごとに収集して 128 ビットハッシュを算出する。
84/// 空白・空文字のみの `<style>` 要素はスキップされるため、`combined_hash` を変化させない。
85pub fn collect_style_blocks<'a>(root: &'a Node) -> InlineStyleBlockCollection<'a> {
86    fn walk<'n>(node: &'n Node, blocks: &mut Vec<CollectedStyleBlock<'n>>, total_bytes: &mut usize) {
87        if let NodeType::Element { tag_name, .. } = &node.node_type {
88            if tag_name == "style" {
89                let mut single: Option<&'n str> = None;
90                let mut combined: Option<String> = None;
91                for child in &node.children {
92                    if let NodeType::Text(t) = &child.node_type {
93                        if let Some(ref mut buf) = combined {
94                            buf.push('\n');
95                            buf.push_str(t);
96                        } else if let Some(prev) = single {
97                            let mut buf = String::with_capacity(prev.len() + 1 + t.len());
98                            buf.push_str(prev);
99                            buf.push('\n');
100                            buf.push_str(t);
101                            combined = Some(buf);
102                        } else {
103                            single = Some(t.as_str());
104                        }
105                    }
106                }
107                let text_cow: Option<Cow<'n, str>> = match (combined, single) {
108                    (Some(buf), _) => Some(Cow::Owned(buf)),
109                    (None, Some(s)) => Some(Cow::Borrowed(s)),
110                    (None, None) => None,
111                };
112                if let Some(text) = text_cow {
113                    if !text.trim().is_empty() {
114                        *total_bytes += text.len() + 1;
115                        let hash = fnv_hash128(text.as_ref());
116                        blocks.push(CollectedStyleBlock { text, hash });
117                    }
118                }
119                return;
120            }
121        }
122        for child in &node.children {
123            walk(child, blocks, total_bytes);
124        }
125    }
126
127    let mut blocks = Vec::new();
128    let mut total_bytes = 0usize;
129    walk(root, &mut blocks, &mut total_bytes);
130
131    let mut a: u64 = 0xcbf2_9ce4_8422_2325;
132    let mut b: u64 = 0x6c62_272e_07bb_0142;
133    fnv_u64(&mut a, &mut b, blocks.len() as u64);
134    for blk in &blocks {
135        fnv_u64(&mut a, &mut b, blk.hash.0);
136        fnv_u64(&mut a, &mut b, blk.hash.1);
137    }
138
139    InlineStyleBlockCollection {
140        blocks,
141        combined_hash: (a, b),
142        total_bytes,
143    }
144}
145
146/// `<style>` ブロックごとのパース結果キャッシュ。
147#[derive(Default)]
148pub struct InlineStyleParseMemo {
149    entries: BTreeMap<(u64, u64), (StyleSheet, Vec<String>)>,
150    pub hits: u32,
151    pub misses: u32,
152}
153
154impl InlineStyleParseMemo {
155    const MAX_ENTRIES: usize = 256;
156
157    pub fn clear(&mut self) {
158        self.entries.clear();
159        self.hits = 0;
160        self.misses = 0;
161    }
162
163    pub fn len(&self) -> usize {
164        self.entries.len()
165    }
166
167    /// 収集された各インライン `<style>` ブロックを順に解決・結合して 1 つの `StyleSheet` にまとめる。
168    /// 既にキャッシュ済みのブロックはパースを省略し、変更・追加されたブロックのみパースする。
169    pub fn resolve_blocks(
170        &mut self,
171        blocks: &[CollectedStyleBlock<'_>],
172        ext_layers: &[String],
173    ) -> StyleSheet {
174        let mut out = StyleSheet {
175            rules: Vec::new(),
176            keyframes: Vec::new(),
177            counter_styles: Vec::new(),
178            font_faces: Vec::new(),
179        };
180        let mut layers: Vec<String> = ext_layers.to_vec();
181
182        for blk in blocks {
183            let key = mix_hashes(blk.hash, hash_layers(&layers));
184            if let Some((cached_sheet, next_layers)) = self.entries.get(&key) {
185                self.hits += 1;
186                out.rules.extend(cached_sheet.rules.iter().cloned());
187                out.keyframes.extend(cached_sheet.keyframes.iter().cloned());
188                out.counter_styles.extend(cached_sheet.counter_styles.iter().cloned());
189                out.font_faces.extend(cached_sheet.font_faces.iter().cloned());
190                if next_layers.len() != layers.len() || *next_layers != layers {
191                    layers = next_layers.clone();
192                }
193            } else {
194                self.misses += 1;
195                // 【2026-11-18 TODO R2 (b) ②】大きい `<style>`(5MB など)の解析の途中でも止める確かめを呼ぶ
196                // (呼び出し元は `parse_and_layout` の中で、錠を持っていない)。このタブだけ止める合図なら、
197                // 途中までの結果を表に入れずにやめる(呼び出し側が合図を見てレイアウトをやめる)。
198                let parsed = crate::os_lib::css::parse_css_with_layers_poll(blk.text.as_ref(), &mut layers, &mut kill_check);
199                if kill_aborting() {
200                    break;
201                }
202                if self.entries.len() >= Self::MAX_ENTRIES {
203                    self.entries.clear();
204                }
205                self.entries.insert(key, (parsed.clone(), layers.clone()));
206                out.rules.extend(parsed.rules);
207                out.keyframes.extend(parsed.keyframes);
208                out.counter_styles.extend(parsed.counter_styles);
209                out.font_faces.extend(parsed.font_faces);
210            }
211        }
212        out
213    }
214}
215
216/// CSS の解析の止める確かめ(`window_mgr::layout_check`。2026-11-18、TODO R2 (b) ②)。ホストの試験では何もしない。
217fn kill_check() -> bool {
218    #[cfg(target_os = "none")]
219    return crate::kernel::window_mgr::layout_check();
220    #[cfg(not(target_os = "none"))]
221    false
222}
223
224/// このタブだけ止める合図が立っているか(`window_mgr::layout_aborting`)。ホストの試験では偽。
225fn kill_aborting() -> bool {
226    #[cfg(target_os = "none")]
227    return crate::kernel::window_mgr::layout_aborting();
228    #[cfg(not(target_os = "none"))]
229    false
230}