1use std::{
2 collections::HashMap,
3 collections::hash_map::DefaultHasher,
4 hash::{BuildHasher, Hash, Hasher},
5};
6
7use sui_core::{FontHandle, Size};
8
9use crate::{
10 font::FaceCacheKey,
11 model::{TextDocument, TextLayout, TextLayoutId, TextParagraphStyle, TextStyle},
12 style::{FontFeatures, FontStretch, FontStyle},
13};
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16struct SizeCacheKey {
17 width_bits: u32,
18 height_bits: u32,
19}
20
21impl From<Size> for SizeCacheKey {
22 fn from(value: Size) -> Self {
23 Self {
24 width_bits: value.width.to_bits(),
25 height_bits: value.height.to_bits(),
26 }
27 }
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31struct TextStyleCacheKey {
32 font_handle: Option<u64>,
33 font_families_hash: u64,
34 font_size_bits: u32,
35 line_height_bits: u32,
36 weight: u16,
37 style: FontStyle,
38 stretch: FontStretch,
39 features_hash: u64,
42}
43
44impl TextStyleCacheKey {
45 fn new(style: &TextStyle) -> Self {
46 Self {
47 font_handle: style.font.map(FontHandle::get),
48 font_families_hash: hash_value(&style.font_families),
49 font_size_bits: style.font_size.to_bits(),
50 line_height_bits: style.line_height.to_bits(),
51 weight: style.weight.value(),
52 style: style.style,
53 stretch: style.stretch,
54 features_hash: hash_features(&style.features),
55 }
56 }
57}
58
59fn hash_features(features: &FontFeatures) -> u64 {
60 hash_value(features)
61}
62
63fn hash_value(value: &impl Hash) -> u64 {
64 let mut hasher = DefaultHasher::new();
65 value.hash(&mut hasher);
66 hasher.finish()
67}
68
69#[derive(Debug, Clone, PartialEq, Eq, Hash)]
70struct TextSpanCacheKey {
71 text: String,
72 style: TextStyleCacheKey,
73 face: FaceCacheKey,
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, Hash)]
77struct TextParagraphCacheKey {
78 style: TextParagraphStyle,
79 spans: Vec<TextSpanCacheKey>,
80}
81
82#[derive(Debug, Clone, PartialEq, Eq, Hash)]
83pub(crate) struct TextLayoutCacheKey {
84 paragraphs: Vec<TextParagraphCacheKey>,
85 box_size: Option<SizeCacheKey>,
86}
87
88impl TextLayoutCacheKey {
89 pub(crate) fn stable_layout_id(
90 document: &TextDocument,
91 span_face_keys: &[FaceCacheKey],
92 box_size: Option<Size>,
93 ) -> TextLayoutId {
94 let mut state = DefaultHasher::new();
95 Self::hash_document_into(&mut state, document, span_face_keys, box_size);
96 TextLayoutId::new(state.finish())
97 }
98
99 pub(crate) fn new(
100 document: &TextDocument,
101 span_face_keys: &[FaceCacheKey],
102 box_size: Option<Size>,
103 ) -> Self {
104 let mut span_index = 0;
105 let paragraphs = document
106 .paragraphs
107 .iter()
108 .map(|paragraph| TextParagraphCacheKey {
109 style: paragraph.style.clone(),
110 spans: paragraph
111 .spans
112 .iter()
113 .map(|span| {
114 let face = span_face_keys[span_index];
115 span_index += 1;
116 TextSpanCacheKey {
117 text: span.text.clone(),
118 style: TextStyleCacheKey::new(&span.style),
119 face,
120 }
121 })
122 .collect(),
123 })
124 .collect();
125 debug_assert_eq!(span_index, span_face_keys.len());
126
127 Self {
128 paragraphs,
129 box_size: box_size.map(SizeCacheKey::from),
130 }
131 }
132
133 fn hash_document<S: BuildHasher>(
134 hasher: &S,
135 document: &TextDocument,
136 span_face_keys: &[FaceCacheKey],
137 box_size: Option<Size>,
138 ) -> u64 {
139 let mut state = hasher.build_hasher();
140 Self::hash_document_into(&mut state, document, span_face_keys, box_size);
141 state.finish()
142 }
143
144 fn hash_document_into<H: Hasher>(
145 state: &mut H,
146 document: &TextDocument,
147 span_face_keys: &[FaceCacheKey],
148 box_size: Option<Size>,
149 ) {
150 document.paragraphs.len().hash(state);
151 let mut span_index = 0;
152 for paragraph in &document.paragraphs {
153 paragraph.style.hash(state);
154 paragraph.spans.len().hash(state);
155 for span in ¶graph.spans {
156 span.text.hash(state);
157 TextStyleCacheKey::new(&span.style).hash(state);
158 span_face_keys[span_index].hash(state);
159 span_index += 1;
160 }
161 }
162 debug_assert_eq!(span_index, span_face_keys.len());
163 box_size.map(SizeCacheKey::from).hash(state);
164 }
165
166 fn matches_document(
167 &self,
168 document: &TextDocument,
169 span_face_keys: &[FaceCacheKey],
170 box_size: Option<Size>,
171 ) -> bool {
172 if self.box_size != box_size.map(SizeCacheKey::from) {
173 return false;
174 }
175 if self.paragraphs.len() != document.paragraphs.len() {
176 return false;
177 }
178
179 let mut span_index = 0;
180 for (cached_paragraph, paragraph) in self.paragraphs.iter().zip(&document.paragraphs) {
181 if cached_paragraph.style != paragraph.style {
182 return false;
183 }
184 if cached_paragraph.spans.len() != paragraph.spans.len() {
185 return false;
186 }
187
188 for (cached_span, span) in cached_paragraph.spans.iter().zip(¶graph.spans) {
189 if cached_span.text != span.text
190 || cached_span.style != TextStyleCacheKey::new(&span.style)
191 || cached_span.face != span_face_keys[span_index]
192 {
193 return false;
194 }
195 span_index += 1;
196 }
197 }
198
199 span_index == span_face_keys.len()
200 }
201}
202
203#[derive(Debug, Default)]
204pub(crate) struct TextLayoutCache {
205 entries: HashMap<u64, Vec<TextLayoutCacheEntry>>,
206 entry_count: usize,
207 hits: usize,
208 misses: usize,
209}
210
211#[derive(Debug, Clone)]
212struct TextLayoutCacheEntry {
213 key: TextLayoutCacheKey,
214 layout: TextLayout,
215}
216
217#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
218pub struct TextLayoutCacheSnapshot {
219 pub entries: usize,
220 pub hits: usize,
221 pub misses: usize,
222}
223
224impl TextLayoutCacheSnapshot {
225 pub const fn requests(self) -> usize {
226 self.hits + self.misses
227 }
228
229 pub fn hit_rate(self) -> f64 {
230 let requests = self.requests();
231 if requests == 0 {
232 0.0
233 } else {
234 self.hits as f64 / requests as f64
235 }
236 }
237}
238
239impl TextLayoutCache {
240 pub(crate) fn snapshot(&self) -> TextLayoutCacheSnapshot {
241 TextLayoutCacheSnapshot {
242 entries: self.entry_count,
243 hits: self.hits,
244 misses: self.misses,
245 }
246 }
247
248 pub(crate) fn get(
249 &mut self,
250 document: &TextDocument,
251 span_face_keys: &[FaceCacheKey],
252 box_size: Option<Size>,
253 ) -> Option<TextLayout> {
254 let hash = TextLayoutCacheKey::hash_document(
255 self.entries.hasher(),
256 document,
257 span_face_keys,
258 box_size,
259 );
260 let cached = self
261 .entries
262 .get(&hash)
263 .and_then(|bucket| {
264 bucket.iter().find(|entry| {
265 entry
266 .key
267 .matches_document(document, span_face_keys, box_size)
268 })
269 })
270 .map(|entry| entry.layout.clone());
271 if cached.is_some() {
272 self.hits += 1;
273 } else {
274 self.misses += 1;
275 }
276 cached
277 }
278
279 pub(crate) fn insert(
280 &mut self,
281 document: &TextDocument,
282 span_face_keys: &[FaceCacheKey],
283 box_size: Option<Size>,
284 layout: TextLayout,
285 ) {
286 let hash = TextLayoutCacheKey::hash_document(
287 self.entries.hasher(),
288 document,
289 span_face_keys,
290 box_size,
291 );
292 let key = TextLayoutCacheKey::new(document, span_face_keys, box_size);
293 let bucket = self.entries.entry(hash).or_default();
294 if let Some(existing) = bucket.iter_mut().find(|entry| entry.key == key) {
295 existing.layout = layout;
296 return;
297 }
298
299 bucket.push(TextLayoutCacheEntry { key, layout });
300 self.entry_count += 1;
301 }
302}