1use crate::error::MarkdownError;
41use crate::extensions::Heading;
42use crate::markdown::{
43 process_markdown, process_markdown_with_toc, MarkdownOptions,
44};
45use log::debug;
46use std::collections::hash_map::DefaultHasher;
47use std::collections::HashMap;
48use std::hash::{Hash, Hasher};
49use std::sync::{Mutex, MutexGuard};
50
51pub const DEFAULT_CAPACITY: usize = 1000;
53
54#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
56pub struct CacheStats {
57 pub hits: u64,
59 pub misses: u64,
61}
62
63#[derive(Clone, Copy, PartialEq, Eq, Hash)]
66enum Variant {
67 Html,
68 Toc,
69}
70
71struct Entry {
72 content: String,
73 html: String,
74 toc: Vec<Heading>,
75 last_used: u64,
76}
77
78#[derive(Default)]
79struct Inner {
80 entries: HashMap<(Variant, u64), Entry>,
81 tick: u64,
82 stats: CacheStats,
83}
84
85impl Inner {
86 fn lookup(
87 &mut self,
88 key: (Variant, u64),
89 content: &str,
90 ) -> Option<(String, Vec<Heading>)> {
91 self.tick += 1;
92 let tick = self.tick;
93 let found = match self.entries.get_mut(&key) {
94 Some(e) if e.content == content => {
95 e.last_used = tick;
96 Some((e.html.clone(), e.toc.clone()))
97 }
98 _ => None,
99 };
100 if found.is_some() {
101 self.stats.hits += 1;
102 } else {
103 self.stats.misses += 1;
104 }
105 found
106 }
107
108 fn insert(
109 &mut self,
110 key: (Variant, u64),
111 entry: Entry,
112 cap: usize,
113 ) {
114 if !self.entries.contains_key(&key) && self.entries.len() >= cap
115 {
116 self.evict_lru();
117 }
118 self.entries.insert(key, entry);
119 }
120
121 fn evict_lru(&mut self) {
122 let oldest = self
123 .entries
124 .iter()
125 .min_by_key(|(_, e)| e.last_used)
126 .map(|(k, _)| *k);
127 if let Some(k) = oldest {
128 let _ = self.entries.remove(&k);
129 }
130 }
131}
132
133pub struct CachingProcessor<'a> {
149 options: MarkdownOptions<'a>,
150 capacity: usize,
151 inner: Mutex<Inner>,
152}
153
154impl<'a> CachingProcessor<'a> {
155 pub fn new(options: MarkdownOptions<'a>) -> Self {
157 Self::with_capacity(options, DEFAULT_CAPACITY)
158 }
159
160 pub fn with_capacity(
163 options: MarkdownOptions<'a>,
164 capacity: usize,
165 ) -> Self {
166 Self {
167 options,
168 capacity,
169 inner: Mutex::new(Inner::default()),
170 }
171 }
172
173 pub fn options(&self) -> &MarkdownOptions<'a> {
175 &self.options
176 }
177
178 pub fn capacity(&self) -> usize {
180 self.capacity
181 }
182
183 pub fn len(&self) -> usize {
185 self.lock().entries.len()
186 }
187
188 pub fn is_empty(&self) -> bool {
190 self.len() == 0
191 }
192
193 pub fn stats(&self) -> CacheStats {
197 self.lock().stats
198 }
199
200 pub fn clear(&self) {
202 *self.lock() = Inner::default();
203 }
204
205 pub fn process(
211 &self,
212 content: &str,
213 ) -> Result<String, MarkdownError> {
214 self.cached(Variant::Html, content, |c, o| {
215 process_markdown(c, o).map(|html| (html, Vec::new()))
216 })
217 .map(|(html, _)| html)
218 }
219
220 pub fn process_with_toc(
226 &self,
227 content: &str,
228 ) -> Result<(String, Vec<Heading>), MarkdownError> {
229 self.cached(Variant::Toc, content, process_markdown_with_toc)
230 }
231
232 fn cached<F>(
233 &self,
234 variant: Variant,
235 content: &str,
236 render: F,
237 ) -> Result<(String, Vec<Heading>), MarkdownError>
238 where
239 F: FnOnce(
240 &str,
241 &MarkdownOptions<'a>,
242 )
243 -> Result<(String, Vec<Heading>), MarkdownError>,
244 {
245 let key = (variant, hash_content(content));
246 if let Some(hit) = self.lock().lookup(key, content) {
247 debug!("mdx-gen cache hit ({} bytes)", content.len());
248 return Ok(hit);
249 }
250 debug!("mdx-gen cache miss ({} bytes)", content.len());
251 let (html, toc) = render(content, &self.options)?;
252 if self.capacity > 0 {
253 let (content, cached_html, cached_toc) =
254 (content.to_owned(), html.clone(), toc.clone());
255 let mut inner = self.lock();
256 let entry = Entry {
257 content,
258 html: cached_html,
259 toc: cached_toc,
260 last_used: inner.tick,
261 };
262 inner.insert(key, entry, self.capacity);
263 }
264 Ok((html, toc))
265 }
266
267 fn lock(&self) -> MutexGuard<'_, Inner> {
268 self.inner
269 .lock()
270 .unwrap_or_else(std::sync::PoisonError::into_inner)
271 }
272}
273
274impl std::fmt::Debug for CachingProcessor<'_> {
275 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
276 f.debug_struct("CachingProcessor")
277 .field("options", &self.options)
278 .field("capacity", &self.capacity)
279 .field("len", &self.len())
280 .field("stats", &self.stats())
281 .finish()
282 }
283}
284
285fn hash_content(content: &str) -> u64 {
286 let mut h = DefaultHasher::new();
287 content.hash(&mut h);
288 h.finish()
289}
290
291#[cfg(test)]
292mod tests {
293 use super::*;
294
295 #[test]
296 fn capacity_bound_evicts_least_recently_used() {
297 let p = CachingProcessor::with_capacity(
298 MarkdownOptions::default(),
299 2,
300 );
301 p.process("a").unwrap();
302 p.process("b").unwrap();
303 p.process("a").unwrap(); p.process("c").unwrap(); assert_eq!(p.len(), 2);
306 let before = p.stats();
307 p.process("a").unwrap();
308 assert_eq!(p.stats().hits, before.hits + 1, "a survived");
309 p.process("b").unwrap();
310 assert_eq!(
311 p.stats().misses,
312 before.misses + 1,
313 "b was evicted"
314 );
315 }
316
317 #[test]
318 fn colliding_key_with_different_content_is_a_miss() {
319 let p = CachingProcessor::new(MarkdownOptions::default());
320 let key = (Variant::Html, hash_content("# one"));
321 p.lock().insert(
322 key,
323 Entry {
324 content: "# other".into(),
325 html: "<p>stale</p>".into(),
326 toc: Vec::new(),
327 last_used: 0,
328 },
329 10,
330 );
331 assert!(p.lock().lookup(key, "# one").is_none());
332 }
333
334 #[test]
335 fn zero_capacity_never_stores() {
336 let p = CachingProcessor::with_capacity(
337 MarkdownOptions::default(),
338 0,
339 );
340 p.process("# x").unwrap();
341 p.process("# x").unwrap();
342 assert!(p.is_empty());
343 assert_eq!(p.stats(), CacheStats { hits: 0, misses: 2 });
344 }
345}