Skip to main content

vtcode_commons/
cached_style_parser.rs

1//! Cached Style Parser for Performance Optimization
2//!
3//! Single implementation shared by `vtcode-core::utils::CachedStyleParser`
4//! and `vtcode-ui::tui::utils::CachedStyleParser`, which re-export it.
5//!
6//! This module provides caching for frequently parsed anstyle strings to avoid
7//! repeated parsing overhead, especially useful for theme parsing and
8//! frequently used style configurations.
9//!
10//! Uses [`LrMap`] (left-right concurrent map) for lock-free reads on the hot
11//! path while still allowing safe concurrent inserts on cache miss.
12
13use crate::lr_map::LrMap;
14use anstyle::Style as AnsiStyle;
15use anyhow::{Context, Result};
16
17/// Thread-safe cached parser for Git and LS_COLORS style strings
18pub struct CachedStyleParser {
19    git_cache: LrMap<String, AnsiStyle>,
20    ls_colors_cache: LrMap<String, AnsiStyle>,
21}
22
23impl CachedStyleParser {
24    /// Create a new cached style parser
25    pub fn new() -> Self {
26        Self {
27            git_cache: LrMap::new(),
28            ls_colors_cache: LrMap::new(),
29        }
30    }
31
32    /// Parse and cache a Git-style color string (e.g., "bold red blue")
33    pub fn parse_git_style(&self, input: &str) -> Result<AnsiStyle> {
34        if let Some(cached) = self.git_cache.get(input) {
35            return Ok(cached);
36        }
37
38        let result =
39            anstyle_git::parse(input).map_err(|e| anyhow::anyhow!("Failed to parse Git style '{input}': {e:?}"))?;
40
41        self.git_cache.insert(input.to_string(), result);
42        Ok(result)
43    }
44
45    /// Parse and cache an LS_COLORS-style string (e.g., "01;34")
46    pub fn parse_ls_colors(&self, input: &str) -> Result<AnsiStyle> {
47        if let Some(cached) = self.ls_colors_cache.get(input) {
48            return Ok(cached);
49        }
50
51        let result = anstyle_ls::parse(input).ok_or_else(|| anyhow::anyhow!("Failed to parse LS_COLORS '{input}'"))?;
52
53        self.ls_colors_cache.insert(input.to_string(), result);
54        Ok(result)
55    }
56
57    /// Parse using Git syntax first, then LS_COLORS as fallback, with caching
58    pub fn parse_flexible(&self, input: &str) -> Result<AnsiStyle> {
59        match self.parse_git_style(input) {
60            Ok(style) => Ok(style),
61            Err(_) => self
62                .parse_ls_colors(input)
63                .with_context(|| format!("Could not parse style string: '{input}'")),
64        }
65    }
66
67    /// Clear all cached styles
68    #[cfg(test)]
69    fn clear_cache(&self) {
70        self.git_cache.clear();
71        self.ls_colors_cache.clear();
72    }
73
74    /// Get cache statistics
75    #[cfg(test)]
76    fn cache_stats(&self) -> (usize, usize) {
77        (self.git_cache.len(), self.ls_colors_cache.len())
78    }
79}
80
81impl Default for CachedStyleParser {
82    fn default() -> Self {
83        Self::new()
84    }
85}
86
87#[cfg(test)]
88mod tests {
89    use super::*;
90
91    #[test]
92    fn test_parse_git_style() {
93        let parser = CachedStyleParser::new();
94        let result = parser.parse_git_style("bold red").unwrap();
95
96        assert!(result.get_effects().contains(anstyle::Effects::BOLD));
97    }
98
99    #[test]
100    fn test_parse_ls_colors() {
101        let parser = CachedStyleParser::new();
102        let result = parser.parse_ls_colors("34").unwrap(); // Blue
103
104        assert!(result.get_fg_color().is_some());
105    }
106
107    #[test]
108    fn test_parse_flexible_git_first() {
109        let parser = CachedStyleParser::new();
110        let result = parser.parse_flexible("bold green").unwrap();
111
112        assert!(result.get_effects().contains(anstyle::Effects::BOLD));
113    }
114
115    #[test]
116    fn test_parse_flexible_ls_fallback() {
117        let parser = CachedStyleParser::new();
118        let result = parser.parse_flexible("01;34").unwrap(); // Bold blue in ANSI codes
119
120        assert!(result.get_effects().contains(anstyle::Effects::BOLD));
121    }
122
123    #[test]
124    fn test_caching_behavior() {
125        let parser = CachedStyleParser::new();
126
127        // Parse same string twice - should use cache on second call
128        let _result1 = parser.parse_git_style("red").unwrap();
129        let _result2 = parser.parse_git_style("red").unwrap();
130
131        let (git_count, _) = parser.cache_stats();
132        assert_eq!(git_count, 1); // Only one cached entry for "red"
133    }
134
135    #[test]
136    fn test_cache_clear() {
137        let parser = CachedStyleParser::new();
138        let _result = parser.parse_git_style("blue").unwrap();
139
140        assert_eq!(parser.cache_stats().0, 1); // One cached entry
141
142        parser.clear_cache();
143
144        assert_eq!(parser.cache_stats().0, 0); // Cache cleared
145    }
146
147    #[test]
148    fn test_multiple_cache_entries() {
149        let parser = CachedStyleParser::new();
150        let _result1 = parser.parse_git_style("bold red").unwrap();
151        let _result2 = parser.parse_git_style("italic green").unwrap();
152        let _result3 = parser.parse_ls_colors("34").unwrap();
153
154        let (git_count, ls_count) = parser.cache_stats();
155        assert_eq!(git_count, 2); // Two Git style entries
156        assert_eq!(ls_count, 1); // One LS_COLORS entry
157    }
158}