boxen 0.4.0

A Rust library for creating styled terminal boxes around text with performance optimizations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
/// Terminal size caching with TTL for improved performance
///
/// This module provides a TTL-based cache for terminal dimensions to avoid
/// expensive system calls. The cache automatically expires after a configurable
/// duration and can be invalidated by SIGWINCH signals on Unix systems.
#[cfg(feature = "terminal-cache")]
use std::cell::RefCell;
#[cfg(feature = "terminal-cache")]
use std::time::{Duration, Instant};
use terminal_size::{Height, Width, terminal_size};

/// Default cache TTL (time-to-live) in milliseconds
#[cfg(feature = "terminal-cache")]
const DEFAULT_TTL_MS: u64 = 100;

/// Cached terminal size with expiration
#[cfg(feature = "terminal-cache")]
#[derive(Debug, Clone)]
struct CachedSize {
    width: u16,
    height: u16,
    timestamp: Instant,
}

#[cfg(feature = "terminal-cache")]
impl CachedSize {
    fn new(width: u16, height: u16) -> Self {
        Self {
            width,
            height,
            timestamp: Instant::now(),
        }
    }

    fn is_expired(&self, ttl: Duration) -> bool {
        self.timestamp.elapsed() > ttl
    }
}

/// Cache statistics for monitoring performance
#[derive(Debug, Clone, Default)]
pub struct CacheStats {
    /// Number of cache hits
    pub hits: usize,
    /// Number of cache misses
    pub misses: usize,
    /// Number of cache expirations
    pub expirations: usize,
    /// Number of manual cache invalidations
    pub invalidations: usize,
}

impl CacheStats {
    /// Calculate cache hit rate as a percentage
    #[must_use]
    pub fn hit_rate(&self) -> f64 {
        let total = self.hits + self.misses;
        if total == 0 {
            0.0
        } else {
            // Allow precision loss: Cache hit rates are informational statistics
            // where slight precision loss at extreme values (>2^52 cache operations)
            // is acceptable. In practice, cache sizes are much smaller and precision
            // loss will never occur in real-world usage.
            #[allow(clippy::cast_precision_loss)]
            {
                (self.hits as f64 / total as f64) * 100.0
            }
        }
    }

    /// Reset all statistics
    pub fn reset(&mut self) {
        self.hits = 0;
        self.misses = 0;
        self.expirations = 0;
        self.invalidations = 0;
    }
}

/// Terminal size cache with TTL
#[cfg(feature = "terminal-cache")]
struct TerminalSizeCache {
    cached: Option<CachedSize>,
    ttl: Duration,
    stats: CacheStats,
}

#[cfg(feature = "terminal-cache")]
impl TerminalSizeCache {
    fn new(ttl_ms: u64) -> Self {
        Self {
            cached: None,
            ttl: Duration::from_millis(ttl_ms),
            stats: CacheStats::default(),
        }
    }

    fn get(&mut self) -> Option<(u16, u16)> {
        if let Some(ref cached) = self.cached {
            if !cached.is_expired(self.ttl) {
                self.stats.hits += 1;
                return Some((cached.width, cached.height));
            }
            self.stats.expirations += 1;
            self.cached = None;
        }
        self.stats.misses += 1;
        None
    }

    fn set(&mut self, width: u16, height: u16) {
        self.cached = Some(CachedSize::new(width, height));
    }

    fn invalidate(&mut self) {
        if self.cached.is_some() {
            self.stats.invalidations += 1;
            self.cached = None;
        }
    }

    fn set_ttl(&mut self, ttl_ms: u64) {
        self.ttl = Duration::from_millis(ttl_ms);
    }

    fn stats(&self) -> CacheStats {
        self.stats.clone()
    }

    fn clear(&mut self) {
        self.cached = None;
        self.stats.reset();
    }
}

#[cfg(feature = "terminal-cache")]
thread_local! {
    static SIZE_CACHE: RefCell<TerminalSizeCache> = RefCell::new(TerminalSizeCache::new(DEFAULT_TTL_MS));
}

/// Get terminal size with caching
///
/// This function uses a TTL-based cache to avoid expensive terminal size queries.
/// The cache expires after the configured TTL (default 100ms) and is automatically
/// invalidated on SIGWINCH signals (Unix only).
///
/// # Returns
///
/// Returns `Some((width, height))` if terminal size can be determined, `None` otherwise.
///
/// # Examples
///
/// ```
/// use ::boxen::terminal::size_cache::cached_terminal_size;
///
/// if let Some((width, height)) = cached_terminal_size() {
///     println!("Terminal: {}x{}", width, height);
/// }
/// ```
#[cfg(feature = "terminal-cache")]
#[must_use]
pub fn cached_terminal_size() -> Option<(u16, u16)> {
    SIZE_CACHE.with(|cache| {
        let mut cache = cache.borrow_mut();

        // Check cache first
        if let Some(size) = cache.get() {
            return Some(size);
        }

        // Cache miss - query terminal
        if let Some((Width(w), Height(h))) = terminal_size() {
            cache.set(w, h);
            Some((w, h))
        } else {
            None
        }
    })
}

/// Get terminal size without caching (fallback)
#[cfg(not(feature = "terminal-cache"))]
#[must_use]
pub fn cached_terminal_size() -> Option<(u16, u16)> {
    terminal_size().map(|(Width(w), Height(h))| (w, h))
}

/// Invalidate the terminal size cache
///
/// Forces the next call to `cached_terminal_size()` to query the terminal.
/// This is automatically called on SIGWINCH signals (Unix only).
///
/// # Examples
///
/// ```
/// use ::boxen::terminal::size_cache::invalidate_cache;
///
/// // Manually invalidate cache after terminal resize
/// invalidate_cache();
/// ```
#[cfg(feature = "terminal-cache")]
pub fn invalidate_cache() {
    SIZE_CACHE.with(|cache| {
        cache.borrow_mut().invalidate();
    });
}

/// Get cache statistics
///
/// Returns hit/miss/expiration/invalidation counts for monitoring cache performance.
/// Only available when the `terminal-cache` feature is enabled.
///
/// # Examples
///
/// ```
/// use ::boxen::terminal::size_cache::cache_stats;
///
/// let stats = cache_stats();
/// println!("Hit rate: {:.2}%", stats.hit_rate());
/// ```
#[cfg(feature = "terminal-cache")]
#[must_use]
pub fn cache_stats() -> CacheStats {
    SIZE_CACHE.with(|cache| cache.borrow().stats())
}

/// Clear the terminal size cache
///
/// Removes cached size and resets statistics.
/// Only available when the `terminal-cache` feature is enabled.
#[cfg(feature = "terminal-cache")]
pub fn clear_cache() {
    SIZE_CACHE.with(|cache| cache.borrow_mut().clear());
}

/// Configure cache TTL (time-to-live)
///
/// Sets the duration in milliseconds before cached values expire.
/// This will clear the existing cache.
///
/// # Arguments
///
/// * `ttl_ms` - Time-to-live in milliseconds
///
/// # Examples
///
/// ```
/// use ::boxen::terminal::size_cache::set_cache_ttl;
///
/// // Set cache to expire after 200ms
/// set_cache_ttl(200);
/// ```
#[cfg(feature = "terminal-cache")]
pub fn set_cache_ttl(ttl_ms: u64) {
    SIZE_CACHE.with(|cache| {
        cache.borrow_mut().set_ttl(ttl_ms);
    });
}

/// Setup SIGWINCH handler to invalidate cache on terminal resize (Unix only)
///
/// This function sets up a signal handler that automatically invalidates the
/// terminal size cache when the terminal is resized. This ensures the cache
/// always reflects the current terminal dimensions.
///
/// # Platform Support
///
/// This function is only available on Unix platforms (Linux, macOS, BSD, etc.).
/// On other platforms, it's a no-op.
///
/// # Examples
///
/// ```no_run
/// use ::boxen::terminal::size_cache::setup_sigwinch_handler;
///
/// // Setup handler at application startup
/// setup_sigwinch_handler();
/// ```
#[cfg(all(feature = "terminal-cache", unix))]
pub fn setup_sigwinch_handler() {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};

    static HANDLER_INSTALLED: AtomicBool = AtomicBool::new(false);

    // Only install handler once
    if HANDLER_INSTALLED.swap(true, Ordering::SeqCst) {
        return;
    }

    let term = Arc::new(AtomicBool::new(false));
    signal_hook::flag::register(signal_hook::consts::SIGWINCH, Arc::clone(&term))
        .expect("Failed to register SIGWINCH handler");

    // Spawn background thread to handle signals
    std::thread::spawn(move || {
        loop {
            if term.load(Ordering::Relaxed) {
                invalidate_cache();
                term.store(false, Ordering::Relaxed);
            }
            std::thread::sleep(Duration::from_millis(10));
        }
    });
}

/// Setup SIGWINCH handler to invalidate cache on terminal resize (Unix only)
///
/// This function sets up a signal handler that automatically invalidates the
/// terminal size cache when the terminal is resized. This ensures the cache
/// always reflects the current terminal dimensions.
///
/// # Platform Support
///
/// This function is only available on Unix platforms (Linux, macOS, BSD, etc.).
/// On other platforms, it's a no-op.
///
/// # Examples
///
/// ```no_run
/// use ::boxen::terminal::size_cache::setup_sigwinch_handler;
///
/// // Setup handler at application startup
/// setup_sigwinch_handler();
/// ```
#[cfg(all(feature = "terminal-cache", not(unix)))]
pub fn setup_sigwinch_handler() {
    // No-op on non-Unix platforms
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_basic_terminal_size() {
        let size = cached_terminal_size();
        // May be None in CI environments without a terminal
        if let Some((w, h)) = size {
            assert!(w > 0);
            assert!(h > 0);
        }
    }

    #[cfg(feature = "terminal-cache")]
    #[test]
    fn test_cache_hit() {
        clear_cache();

        // First call - cache miss
        let _ = cached_terminal_size();
        let stats1 = cache_stats();
        assert_eq!(stats1.misses, 1);

        // Second call - cache hit (if terminal exists)
        let _ = cached_terminal_size();
        let stats2 = cache_stats();
        if cached_terminal_size().is_some() {
            assert_eq!(stats2.hits, 1);
        }
    }

    #[cfg(feature = "terminal-cache")]
    #[test]
    fn test_cache_invalidation() {
        clear_cache();

        let _ = cached_terminal_size();
        invalidate_cache();

        let stats = cache_stats();
        if cached_terminal_size().is_some() {
            assert_eq!(stats.invalidations, 1);
        }
    }

    #[cfg(feature = "terminal-cache")]
    #[test]
    fn test_cache_clear() {
        clear_cache();

        let _ = cached_terminal_size();
        clear_cache();

        let stats = cache_stats();
        assert_eq!(stats.hits, 0);
        assert_eq!(stats.misses, 0);
    }

    #[cfg(feature = "terminal-cache")]
    #[test]
    fn test_set_ttl() {
        set_cache_ttl(50);
        clear_cache();

        // First call
        let _ = cached_terminal_size();

        // Wait for expiration
        std::thread::sleep(Duration::from_millis(60));

        // Should be expired
        let _ = cached_terminal_size();
        let stats = cache_stats();
        if cached_terminal_size().is_some() {
            assert!(stats.expirations > 0);
        }
    }

    #[cfg(feature = "terminal-cache")]
    #[test]
    fn test_cache_stats() {
        clear_cache();

        for _ in 0..10 {
            let _ = cached_terminal_size();
        }

        let stats = cache_stats();
        if cached_terminal_size().is_some() {
            assert!(stats.hits > 0);
            assert_eq!(stats.misses, 1);
            assert!(stats.hit_rate() > 80.0);
        }
    }
}