revue 2.71.1

A Vue-style TUI framework for Rust with CSS styling
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
//! Object pooling for memory optimization
//!
//! Provides reusable object pools to reduce allocation overhead in hot paths.
//!
//! # Example
//!
//! ```rust,ignore
//! use revue::dom::pool::{ObjectPool, BufferPool};
//!
//! // Generic object pool
//! let pool: ObjectPool<Vec<u8>> = ObjectPool::new(|| Vec::with_capacity(1024));
//! let mut buffer = pool.acquire();
//! buffer.extend_from_slice(b"Hello");
//! pool.release(buffer);
//!
//! // Buffer pool for render buffers
//! let mut buffer_pool = BufferPool::new();
//! let buf = buffer_pool.acquire(80, 24);
//! // ... use buffer ...
//! buffer_pool.release(buf);
//! ```

use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use crate::render::Buffer;
use crate::utils::lock::lock_or_recover;

/// A generic object pool for reusing allocations
///
/// Objects are created with a factory function and returned to the pool
/// when no longer needed.
pub struct ObjectPool<T> {
    /// Factory for creating new objects
    factory: Box<dyn Fn() -> T>,
    /// Pooled objects ready for reuse
    pool: RefCell<Vec<T>>,
    /// Maximum pool size
    max_size: usize,
    /// Statistics
    stats: RefCell<PoolStats>,
}

/// Statistics for pool usage
#[derive(Debug, Clone, Default)]
pub struct PoolStats {
    /// Total acquisitions
    pub acquires: usize,
    /// Cache hits (reused from pool)
    pub hits: usize,
    /// Cache misses (new allocation)
    pub misses: usize,
    /// Total releases
    pub releases: usize,
    /// Objects discarded (pool full)
    pub discards: usize,
}

impl PoolStats {
    /// Hit rate (0.0 - 1.0)
    pub fn hit_rate(&self) -> f32 {
        if self.acquires == 0 {
            0.0
        } else {
            self.hits as f32 / self.acquires as f32
        }
    }
}

impl<T> ObjectPool<T> {
    /// Create a new object pool
    pub fn new<F>(factory: F) -> Self
    where
        F: Fn() -> T + 'static,
    {
        Self::with_capacity(factory, 16)
    }

    /// Create a pool with specific capacity
    pub fn with_capacity<F>(factory: F, max_size: usize) -> Self
    where
        F: Fn() -> T + 'static,
    {
        Self {
            factory: Box::new(factory),
            pool: RefCell::new(Vec::with_capacity(max_size)),
            max_size,
            stats: RefCell::new(PoolStats::default()),
        }
    }

    /// Acquire an object from the pool
    pub fn acquire(&self) -> T {
        let mut stats = self.stats.borrow_mut();
        stats.acquires += 1;

        if let Some(obj) = self.pool.borrow_mut().pop() {
            stats.hits += 1;
            obj
        } else {
            stats.misses += 1;
            (self.factory)()
        }
    }

    /// Release an object back to the pool
    pub fn release(&self, obj: T) {
        let mut stats = self.stats.borrow_mut();
        stats.releases += 1;

        let mut pool = self.pool.borrow_mut();
        if pool.len() < self.max_size {
            pool.push(obj);
        } else {
            stats.discards += 1;
            // Object is dropped
        }
    }

    /// Get current pool size
    pub fn size(&self) -> usize {
        self.pool.borrow().len()
    }

    /// Get pool statistics
    pub fn stats(&self) -> PoolStats {
        self.stats.borrow().clone()
    }

    /// Clear the pool
    pub fn clear(&self) {
        self.pool.borrow_mut().clear();
    }

    /// Pre-warm the pool with objects
    pub fn prewarm(&self, count: usize) {
        let target = count.min(self.max_size);
        let mut pool = self.pool.borrow_mut();
        while pool.len() < target {
            pool.push((self.factory)());
        }
    }
}

/// Thread-safe object pool
pub struct SyncObjectPool<T> {
    /// Factory for creating new objects
    factory: Box<dyn Fn() -> T + Send + Sync>,
    /// Pooled objects
    pool: Mutex<Vec<T>>,
    /// Maximum pool size
    max_size: usize,
    /// Statistics
    stats: Mutex<PoolStats>,
}

impl<T: Send> SyncObjectPool<T> {
    /// Create a new thread-safe pool
    pub fn new<F>(factory: F) -> Self
    where
        F: Fn() -> T + Send + Sync + 'static,
    {
        Self::with_capacity(factory, 16)
    }

    /// Create with specific capacity
    pub fn with_capacity<F>(factory: F, max_size: usize) -> Self
    where
        F: Fn() -> T + Send + Sync + 'static,
    {
        Self {
            factory: Box::new(factory),
            pool: Mutex::new(Vec::with_capacity(max_size)),
            max_size,
            stats: Mutex::new(PoolStats::default()),
        }
    }

    /// Acquire an object
    pub fn acquire(&self) -> T {
        let mut stats = lock_or_recover(&self.stats);
        stats.acquires += 1;

        if let Some(obj) = lock_or_recover(&self.pool).pop() {
            stats.hits += 1;
            obj
        } else {
            stats.misses += 1;
            (self.factory)()
        }
    }

    /// Release an object
    pub fn release(&self, obj: T) {
        let mut stats = lock_or_recover(&self.stats);
        stats.releases += 1;

        let mut pool = lock_or_recover(&self.pool);
        if pool.len() < self.max_size {
            pool.push(obj);
        } else {
            stats.discards += 1;
        }
    }

    /// Get pool statistics
    pub fn stats(&self) -> PoolStats {
        lock_or_recover(&self.stats).clone()
    }
}

/// Specialized pool for render buffers
///
/// Pools buffers by size to avoid reallocation when terminal resizes.
pub struct BufferPool {
    /// Pools organized by (width, height)
    pools: RefCell<HashMap<(u16, u16), Vec<Buffer>>>,
    /// Maximum buffers per size
    max_per_size: usize,
    /// Statistics
    stats: RefCell<PoolStats>,
}

impl Default for BufferPool {
    fn default() -> Self {
        Self::new()
    }
}

impl BufferPool {
    /// Create a new buffer pool
    pub fn new() -> Self {
        Self::with_capacity(4)
    }

    /// Create with specific capacity per size
    pub fn with_capacity(max_per_size: usize) -> Self {
        Self {
            pools: RefCell::new(HashMap::new()),
            max_per_size,
            stats: RefCell::new(PoolStats::default()),
        }
    }

    /// Acquire a buffer of the given size
    pub fn acquire(&self, width: u16, height: u16) -> Buffer {
        let mut stats = self.stats.borrow_mut();
        stats.acquires += 1;

        let key = (width, height);
        let mut pools = self.pools.borrow_mut();

        if let Some(pool) = pools.get_mut(&key) {
            if let Some(mut buf) = pool.pop() {
                stats.hits += 1;
                buf.clear();
                return buf;
            }
        }

        // Try to find a larger buffer we can use
        for ((w, h), pool) in pools.iter_mut() {
            if *w >= width && *h >= height {
                if let Some(mut buf) = pool.pop() {
                    stats.hits += 1;
                    buf.resize(width, height);
                    return buf;
                }
            }
        }

        stats.misses += 1;
        Buffer::new(width, height)
    }

    /// Release a buffer back to the pool
    pub fn release(&self, buf: Buffer) {
        let mut stats = self.stats.borrow_mut();
        stats.releases += 1;

        let key = (buf.width(), buf.height());
        let mut pools = self.pools.borrow_mut();

        let pool = pools.entry(key).or_default();
        if pool.len() < self.max_per_size {
            pool.push(buf);
        } else {
            stats.discards += 1;
        }
    }

    /// Get pool statistics
    pub fn stats(&self) -> PoolStats {
        self.stats.borrow().clone()
    }

    /// Clear all pooled buffers
    pub fn clear(&self) {
        self.pools.borrow_mut().clear();
    }

    /// Total number of pooled buffers
    pub fn total_buffered(&self) -> usize {
        self.pools.borrow().values().map(|v| v.len()).sum()
    }
}

/// String interning pool for frequently used strings
///
/// Useful for widget names, class names, and other repeated strings.
pub struct StringPool {
    /// Interned strings
    strings: RefCell<HashMap<String, Arc<str>>>,
    /// Statistics
    stats: RefCell<PoolStats>,
}

impl Default for StringPool {
    fn default() -> Self {
        Self::new()
    }
}

impl StringPool {
    /// Create a new string pool
    pub fn new() -> Self {
        Self {
            strings: RefCell::new(HashMap::new()),
            stats: RefCell::new(PoolStats::default()),
        }
    }

    /// Intern a string
    pub fn intern(&self, s: impl AsRef<str>) -> Arc<str> {
        let s = s.as_ref();
        let mut stats = self.stats.borrow_mut();
        stats.acquires += 1;

        let mut strings = self.strings.borrow_mut();
        if let Some(interned) = strings.get(s) {
            stats.hits += 1;
            interned.clone()
        } else {
            stats.misses += 1;
            let interned: Arc<str> = s.into();
            strings.insert(s.to_owned(), interned.clone());
            interned
        }
    }

    /// Check if a string is interned
    pub fn contains(&self, s: &str) -> bool {
        self.strings.borrow().contains_key(s)
    }

    /// Number of interned strings
    pub fn len(&self) -> usize {
        self.strings.borrow().len()
    }

    /// Check if empty
    pub fn is_empty(&self) -> bool {
        self.strings.borrow().is_empty()
    }

    /// Get statistics
    pub fn stats(&self) -> PoolStats {
        self.stats.borrow().clone()
    }

    /// Clear all interned strings
    pub fn clear(&self) {
        self.strings.borrow_mut().clear();
    }
}

/// Thread-safe string pool
pub struct SyncStringPool {
    /// Interned strings
    strings: Mutex<HashMap<String, Arc<str>>>,
    /// Statistics
    stats: Mutex<PoolStats>,
}

impl Default for SyncStringPool {
    fn default() -> Self {
        Self::new()
    }
}

impl SyncStringPool {
    /// Create a new thread-safe string pool
    pub fn new() -> Self {
        Self {
            strings: Mutex::new(HashMap::new()),
            stats: Mutex::new(PoolStats::default()),
        }
    }

    /// Intern a string
    pub fn intern(&self, s: impl AsRef<str>) -> Arc<str> {
        let s = s.as_ref();
        let mut stats = lock_or_recover(&self.stats);
        stats.acquires += 1;

        let mut strings = lock_or_recover(&self.strings);
        if let Some(interned) = strings.get(s) {
            stats.hits += 1;
            interned.clone()
        } else {
            stats.misses += 1;
            let interned: Arc<str> = s.into();
            strings.insert(s.to_owned(), interned.clone());
            interned
        }
    }

    /// Get statistics
    pub fn stats(&self) -> PoolStats {
        lock_or_recover(&self.stats).clone()
    }
}

/// Pool for reusing vectors
pub struct VecPool<T> {
    /// Pool of empty vectors with reserved capacity
    pool: RefCell<Vec<Vec<T>>>,
    /// Default capacity for new vectors
    default_capacity: usize,
    /// Maximum pool size
    max_size: usize,
    /// Statistics
    stats: RefCell<PoolStats>,
}

impl<T> VecPool<T> {
    /// Create a new vector pool
    pub fn new(default_capacity: usize) -> Self {
        Self::with_max_size(default_capacity, 16)
    }

    /// Create with specific max size
    pub fn with_max_size(default_capacity: usize, max_size: usize) -> Self {
        Self {
            pool: RefCell::new(Vec::with_capacity(max_size)),
            default_capacity,
            max_size,
            stats: RefCell::new(PoolStats::default()),
        }
    }

    /// Acquire a vector
    pub fn acquire(&self) -> Vec<T> {
        let mut stats = self.stats.borrow_mut();
        stats.acquires += 1;

        if let Some(vec) = self.pool.borrow_mut().pop() {
            stats.hits += 1;
            vec
        } else {
            stats.misses += 1;
            Vec::with_capacity(self.default_capacity)
        }
    }

    /// Release a vector back to the pool
    pub fn release(&self, mut vec: Vec<T>) {
        let mut stats = self.stats.borrow_mut();
        stats.releases += 1;

        vec.clear();

        let mut pool = self.pool.borrow_mut();
        if pool.len() < self.max_size {
            pool.push(vec);
        } else {
            stats.discards += 1;
        }
    }

    /// Get statistics
    pub fn stats(&self) -> PoolStats {
        self.stats.borrow().clone()
    }

    /// Clear the pool
    pub fn clear(&self) {
        self.pool.borrow_mut().clear();
    }

    /// Pre-warm the pool
    pub fn prewarm(&self, count: usize) {
        let target = count.min(self.max_size);
        let mut pool = self.pool.borrow_mut();
        while pool.len() < target {
            pool.push(Vec::with_capacity(self.default_capacity));
        }
    }
}

/// RAII guard for pooled objects
///
/// Automatically returns the object to the pool when dropped.
pub struct Pooled<'a, T> {
    /// The pooled object
    value: Option<T>,
    /// Reference to the pool
    pool: &'a ObjectPool<T>,
}

impl<'a, T> Pooled<'a, T> {
    /// Create a new pooled guard
    pub fn new(pool: &'a ObjectPool<T>) -> Self {
        Self {
            value: Some(pool.acquire()),
            pool,
        }
    }

    /// Take the value, preventing automatic release
    pub fn take(mut self) -> T {
        self.value.take().unwrap_or_else(|| {
            panic!("Pooled value already taken - this is a bug in Pooled implementation")
        })
    }
}

impl<T> std::ops::Deref for Pooled<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        // value is always Some until take() is called, which consumes self
        self.value.as_ref().unwrap_or_else(|| {
            panic!("Pooled value is None - deref called after take(), this is a bug")
        })
    }
}

impl<T> std::ops::DerefMut for Pooled<'_, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        // value is always Some until take() is called, which consumes self
        self.value.as_mut().unwrap_or_else(|| {
            panic!("Pooled value is None - deref_mut called after take(), this is a bug")
        })
    }
}

impl<T> Drop for Pooled<'_, T> {
    fn drop(&mut self) {
        if let Some(value) = self.value.take() {
            self.pool.release(value);
        }
    }
}

/// Create an object pool
pub fn object_pool<T, F>(factory: F) -> ObjectPool<T>
where
    F: Fn() -> T + 'static,
{
    ObjectPool::new(factory)
}

/// Create a buffer pool
pub fn buffer_pool() -> BufferPool {
    BufferPool::new()
}

/// Create a string pool
pub fn string_pool() -> StringPool {
    StringPool::new()
}

/// Create a vector pool
pub fn vec_pool<T>(capacity: usize) -> VecPool<T> {
    VecPool::new(capacity)
}

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

    #[test]
    fn test_object_pool_basic() {
        let pool: ObjectPool<Vec<u8>> = ObjectPool::new(|| Vec::with_capacity(64));

        // First acquire creates new
        let mut v1 = pool.acquire();
        assert!(v1.capacity() >= 64);
        v1.push(1);
        v1.push(2);

        // Release back to pool
        pool.release(v1);
        assert_eq!(pool.size(), 1);

        // Second acquire reuses
        let v2 = pool.acquire();
        assert!(v2.capacity() >= 64);
        // Note: contents are NOT cleared by default - caller should clear if needed
        assert_eq!(pool.size(), 0);

        let stats = pool.stats();
        assert_eq!(stats.acquires, 2);
        assert_eq!(stats.misses, 1);
        assert_eq!(stats.hits, 1);
    }

    #[test]
    fn test_object_pool_max_size() {
        let pool: ObjectPool<u32> = ObjectPool::with_capacity(|| 0, 2);

        pool.release(1);
        pool.release(2);
        pool.release(3); // Should be discarded

        assert_eq!(pool.size(), 2);
        assert_eq!(pool.stats().discards, 1);
    }

    #[test]
    fn test_object_pool_prewarm() {
        let pool: ObjectPool<String> = ObjectPool::with_capacity(|| String::with_capacity(32), 10);
        pool.prewarm(5);

        assert_eq!(pool.size(), 5);

        // Acquiring should use pre-warmed objects
        let _ = pool.acquire();
        assert_eq!(pool.size(), 4);
    }

    #[test]
    fn test_buffer_pool_basic() {
        let pool = BufferPool::new();

        let buf = pool.acquire(80, 24);
        assert_eq!(buf.width(), 80);
        assert_eq!(buf.height(), 24);

        pool.release(buf);
        assert_eq!(pool.total_buffered(), 1);

        // Acquire same size
        let buf2 = pool.acquire(80, 24);
        assert_eq!(buf2.width(), 80);
        assert_eq!(pool.stats().hits, 1);
    }

    #[test]
    fn test_buffer_pool_resize() {
        let pool = BufferPool::new();

        // Release a large buffer
        let buf = Buffer::new(160, 48);
        pool.release(buf);

        // Acquire a smaller buffer - should resize the larger one
        let buf2 = pool.acquire(80, 24);
        assert_eq!(buf2.width(), 80);
        assert_eq!(buf2.height(), 24);
        assert_eq!(pool.stats().hits, 1);
    }

    #[test]
    fn test_string_pool_basic() {
        let pool = StringPool::new();

        let s1 = pool.intern("hello");
        let s2 = pool.intern("hello");
        let s3 = pool.intern("world");

        // Same string should return same Arc
        assert!(Arc::ptr_eq(&s1, &s2));
        assert!(!Arc::ptr_eq(&s1, &s3));

        assert_eq!(pool.len(), 2);
        assert_eq!(pool.stats().hits, 1);
        assert_eq!(pool.stats().misses, 2);
    }

    #[test]
    fn test_vec_pool_basic() {
        let pool: VecPool<i32> = VecPool::new(16);

        let mut v = pool.acquire();
        assert!(v.capacity() >= 16);
        v.push(1);
        v.push(2);

        pool.release(v);

        // Acquire should return cleared vector
        let v2 = pool.acquire();
        assert!(v2.is_empty());
        assert!(v2.capacity() >= 16);
    }

    #[test]
    fn test_pooled_guard() {
        let pool: ObjectPool<String> = ObjectPool::new(|| String::with_capacity(32));

        {
            let mut s = Pooled::new(&pool);
            s.push_str("hello");
            assert_eq!(&*s, "hello");
        } // Dropped, returned to pool

        assert_eq!(pool.size(), 1);
    }

    #[test]
    fn test_pooled_take() {
        let pool: ObjectPool<String> = ObjectPool::new(|| String::with_capacity(32));

        let s = {
            let mut pooled = Pooled::new(&pool);
            pooled.push_str("hello");
            pooled.take() // Take ownership
        };

        assert_eq!(s, "hello");
        assert_eq!(pool.size(), 0); // Not returned to pool
    }

    #[test]
    fn test_sync_object_pool() {
        use std::thread;

        let pool: Arc<SyncObjectPool<Vec<u8>>> =
            Arc::new(SyncObjectPool::new(|| Vec::with_capacity(64)));

        let handles: Vec<_> = (0..4)
            .map(|_| {
                let pool = pool.clone();
                thread::spawn(move || {
                    for _ in 0..10 {
                        let v = pool.acquire();
                        pool.release(v);
                    }
                })
            })
            .collect();

        for h in handles {
            h.join().unwrap();
        }

        let stats = pool.stats();
        assert_eq!(stats.acquires, 40);
        assert_eq!(stats.releases, 40);
    }

    #[test]
    fn test_sync_string_pool() {
        use std::thread;

        let pool: Arc<SyncStringPool> = Arc::new(SyncStringPool::new());

        let handles: Vec<_> = (0..4)
            .map(|i| {
                let pool = pool.clone();
                thread::spawn(move || {
                    for j in 0..10 {
                        let _ = pool.intern(format!("string-{}-{}", i, j));
                    }
                })
            })
            .collect();

        for h in handles {
            h.join().unwrap();
        }

        let stats = pool.stats();
        assert_eq!(stats.acquires, 40);
    }

    #[test]
    fn test_pool_stats_hit_rate() {
        let pool: ObjectPool<u32> = ObjectPool::new(|| 0);

        pool.release(1);
        let _ = pool.acquire();
        let _ = pool.acquire();

        let stats = pool.stats();
        assert_eq!(stats.hits, 1);
        assert_eq!(stats.misses, 1);
        assert!((stats.hit_rate() - 0.5).abs() < 0.01);
    }
}