pub struct WidthCache { /* private fields */ }Expand description
LRU cache for text width measurements.
This cache stores the computed display width (in terminal cells) for text strings, using an LRU eviction policy when capacity is reached.
§Performance
- Uses FxHash for fast hashing
- O(1) lookup and insertion
- Automatic LRU eviction
- Keys are stored as 64-bit hashes (not full strings) to minimize memory
§Hash Collisions
The cache uses a 64-bit hash as the lookup key rather than storing the
full string. This trades theoretical correctness for memory efficiency.
With FxHash, collision probability is ~1 in 2^64, making this safe for
practical use. If you require guaranteed correctness, use contains()
to verify presence before trusting cached values.
§Thread Safety
WidthCache is not thread-safe. For concurrent use, wrap in a mutex
or use thread-local caches.
Implementations§
Source§impl WidthCache
impl WidthCache
Sourcepub fn new(capacity: usize) -> Self
pub fn new(capacity: usize) -> Self
Create a new cache with the specified capacity.
If capacity is zero, defaults to 1.
Sourcepub fn with_default_capacity() -> Self
pub fn with_default_capacity() -> Self
Create a new cache with the default capacity (4096 entries).
Sourcepub fn get_or_compute(&mut self, text: &str) -> usize
pub fn get_or_compute(&mut self, text: &str) -> usize
Get cached width or compute and cache it.
If the text is in the cache, returns the cached width.
Otherwise, computes the width using display_width and caches it.
Sourcepub fn get_or_compute_with<F>(&mut self, text: &str, compute: F) -> usize
pub fn get_or_compute_with<F>(&mut self, text: &str, compute: F) -> usize
Get cached width or compute using a custom function.
This allows using custom width calculation functions for testing or specialized terminal behavior.
Sourcepub fn get(&mut self, text: &str) -> Option<usize>
pub fn get(&mut self, text: &str) -> Option<usize>
Get the cached width for a text string without computing.
Returns None if the text is not in the cache.
Note: This does update the LRU order.
Sourcepub fn peek(&self, text: &str) -> Option<usize>
pub fn peek(&self, text: &str) -> Option<usize>
Peek at the cached width without updating LRU order.
Sourcepub fn preload(&mut self, text: &str)
pub fn preload(&mut self, text: &str)
Pre-populate the cache with a text string.
This is useful for warming up the cache with known strings.
Sourcepub fn preload_many<'a>(&mut self, texts: impl IntoIterator<Item = &'a str>)
pub fn preload_many<'a>(&mut self, texts: impl IntoIterator<Item = &'a str>)
Pre-populate the cache with multiple strings.
Sourcepub fn reset_stats(&mut self)
pub fn reset_stats(&mut self)
Reset statistics.
Sourcepub fn stats(&self) -> CacheStats
pub fn stats(&self) -> CacheStats
Get cache statistics.