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
//! Performance profiler for Revue applications
//!
//! Tracks render times, layout calculations, memory usage,
//! and provides performance insights.
//!
//! # Example
//!
//! ```rust,ignore
//! use revue::utils::profiler::{Profiler, profile};
//!
//! // Profile a section of code
//! let result = profile("render_widget", || {
//!     expensive_render_operation()
//! });
//!
//! // Get profiling report
//! let report = Profiler::global().report();
//! println!("{}", report);
//! ```

use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::{Arc, OnceLock, RwLock};
use std::time::{Duration, Instant};

// =============================================================================
// Timing Entry
// =============================================================================

/// A timing measurement
#[derive(Debug, Clone)]
pub struct Timing {
    /// Operation name
    pub name: String,
    /// Duration
    pub duration: Duration,
    /// Start time
    pub start: Instant,
    /// Parent operation (if nested)
    pub parent: Option<String>,
}

impl Timing {
    /// Create a new timing
    pub fn new(name: impl Into<String>, duration: Duration, start: Instant) -> Self {
        Self {
            name: name.into(),
            duration,
            start,
            parent: None,
        }
    }

    /// Set parent operation
    pub fn with_parent(mut self, parent: impl Into<String>) -> Self {
        self.parent = Some(parent.into());
        self
    }
}

// =============================================================================
// Statistics
// =============================================================================

/// Statistics for a profiled operation
#[derive(Debug, Clone, Default)]
pub struct Stats {
    /// Number of calls
    pub count: u64,
    /// Total duration
    pub total: Duration,
    /// Minimum duration
    pub min: Option<Duration>,
    /// Maximum duration
    pub max: Option<Duration>,
    /// Last duration
    pub last: Duration,
}

impl Stats {
    /// Create new stats
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a timing
    pub fn record(&mut self, duration: Duration) {
        self.count += 1;
        self.total += duration;
        self.last = duration;

        match self.min {
            Some(m) if duration < m => self.min = Some(duration),
            None => self.min = Some(duration),
            _ => {}
        }

        match self.max {
            Some(m) if duration > m => self.max = Some(duration),
            None => self.max = Some(duration),
            _ => {}
        }
    }

    /// Get average duration
    pub fn average(&self) -> Duration {
        if self.count == 0 {
            Duration::ZERO
        } else {
            self.total / self.count as u32
        }
    }

    /// Get average duration in milliseconds
    pub fn avg_ms(&self) -> f64 {
        self.average().as_secs_f64() * 1000.0
    }

    /// Get total duration in milliseconds
    pub fn total_ms(&self) -> f64 {
        self.total.as_secs_f64() * 1000.0
    }

    /// Get min duration in milliseconds
    pub fn min_ms(&self) -> f64 {
        self.min.map(|d| d.as_secs_f64() * 1000.0).unwrap_or(0.0)
    }

    /// Get max duration in milliseconds
    pub fn max_ms(&self) -> f64 {
        self.max.map(|d| d.as_secs_f64() * 1000.0).unwrap_or(0.0)
    }
}

// =============================================================================
// Profile Guard (RAII)
// =============================================================================

/// RAII guard that records timing when dropped
pub struct ProfileGuard {
    name: String,
    start: Instant,
    profiler: Arc<RwLock<ProfilerInner>>,
}

impl ProfileGuard {
    fn new(name: impl Into<String>, profiler: Arc<RwLock<ProfilerInner>>) -> Self {
        Self {
            name: name.into(),
            start: Instant::now(),
            profiler,
        }
    }
}

impl Drop for ProfileGuard {
    fn drop(&mut self) {
        let duration = self.start.elapsed();
        if let Ok(mut p) = self.profiler.write() {
            p.record(&self.name, duration);
        }
    }
}

// =============================================================================
// Profiler Inner
// =============================================================================

#[derive(Debug, Default)]
struct ProfilerInner {
    /// Statistics by operation name
    stats: HashMap<String, Stats>,
    /// Recent timings (ring buffer)
    recent: Vec<Timing>,
    /// Maximum recent entries
    max_recent: usize,
    /// Is profiling enabled
    enabled: bool,
    /// Current profile stack (for nesting)
    stack: Vec<String>,
}

impl ProfilerInner {
    fn new() -> Self {
        Self {
            stats: HashMap::new(),
            recent: Vec::new(),
            max_recent: 100,
            enabled: true,
            stack: Vec::new(),
        }
    }

    fn record(&mut self, name: &str, duration: Duration) {
        if !self.enabled {
            return;
        }

        // Update stats
        let stats = self.stats.entry(name.to_string()).or_default();
        stats.record(duration);

        // Add to recent
        let mut timing = Timing::new(name, duration, Instant::now());
        if let Some(parent) = self.stack.last() {
            timing = timing.with_parent(parent.clone());
        }
        self.recent.push(timing);

        // Trim if needed
        if self.recent.len() > self.max_recent {
            self.recent.remove(0);
        }
    }

    fn reset(&mut self) {
        self.stats.clear();
        self.recent.clear();
    }
}

// =============================================================================
// Profiler
// =============================================================================

/// Performance profiler
///
/// Tracks timing measurements for various operations.
#[derive(Debug, Clone)]
pub struct Profiler {
    inner: Arc<RwLock<ProfilerInner>>,
}

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

impl Profiler {
    /// Create a new profiler
    pub fn new() -> Self {
        Self {
            inner: Arc::new(RwLock::new(ProfilerInner::new())),
        }
    }

    /// Get the global profiler instance
    pub fn global() -> &'static Profiler {
        static INSTANCE: OnceLock<Profiler> = OnceLock::new();
        INSTANCE.get_or_init(Profiler::new)
    }

    /// Enable profiling
    pub fn enable(&self) {
        if let Ok(mut inner) = self.inner.write() {
            inner.enabled = true;
        }
    }

    /// Disable profiling
    pub fn disable(&self) {
        if let Ok(mut inner) = self.inner.write() {
            inner.enabled = false;
        }
    }

    /// Check if profiling is enabled
    pub fn is_enabled(&self) -> bool {
        self.inner.read().map(|i| i.enabled).unwrap_or(false)
    }

    /// Start a profiled section (returns guard that records on drop)
    pub fn start(&self, name: impl Into<String>) -> ProfileGuard {
        ProfileGuard::new(name, self.inner.clone())
    }

    /// Profile a closure
    pub fn profile<T, F: FnOnce() -> T>(&self, name: &str, f: F) -> T {
        let _guard = self.start(name);
        f()
    }

    /// Record a timing directly
    pub fn record(&self, name: &str, duration: Duration) {
        if let Ok(mut inner) = self.inner.write() {
            inner.record(name, duration);
        }
    }

    /// Get statistics for an operation
    pub fn stats(&self, name: &str) -> Option<Stats> {
        self.inner.read().ok()?.stats.get(name).cloned()
    }

    /// Get all statistics
    pub fn all_stats(&self) -> HashMap<String, Stats> {
        self.inner
            .read()
            .map(|i| i.stats.clone())
            .unwrap_or_default()
    }

    /// Reset all statistics
    pub fn reset(&self) {
        if let Ok(mut inner) = self.inner.write() {
            inner.reset();
        }
    }

    /// Generate a text report
    pub fn report(&self) -> String {
        let stats = self.all_stats();
        if stats.is_empty() {
            return "No profiling data collected.".to_string();
        }

        let mut output = String::new();
        output.push_str("Performance Report\n");
        output.push_str("==================\n\n");

        // Sort by total time descending
        let mut entries: Vec<_> = stats.into_iter().collect();
        entries.sort_by(|a, b| b.1.total.cmp(&a.1.total));

        output.push_str(&format!(
            "{:<30} {:>8} {:>10} {:>10} {:>10} {:>10}\n",
            "Operation", "Calls", "Total(ms)", "Avg(ms)", "Min(ms)", "Max(ms)"
        ));
        output.push_str(&"-".repeat(80));
        output.push('\n');

        for (name, stat) in entries {
            output.push_str(&format!(
                "{:<30} {:>8} {:>10.2} {:>10.3} {:>10.3} {:>10.3}\n",
                if name.len() > 30 {
                    format!("{}...", &name[..27])
                } else {
                    name.clone()
                },
                stat.count,
                stat.total_ms(),
                stat.avg_ms(),
                stat.min_ms(),
                stat.max_ms(),
            ));
        }

        output
    }

    /// Generate a compact summary
    pub fn summary(&self) -> String {
        let stats = self.all_stats();
        if stats.is_empty() {
            return String::new();
        }

        let total_time: Duration = stats.values().map(|s| s.total).sum();
        let total_calls: u64 = stats.values().map(|s| s.count).sum();

        format!(
            "{} operations, {} calls, {:.2}ms total",
            stats.len(),
            total_calls,
            total_time.as_secs_f64() * 1000.0
        )
    }
}

// =============================================================================
// Convenience Functions
// =============================================================================

/// Profile a section of code using the global profiler
pub fn profile<T, F: FnOnce() -> T>(name: &str, f: F) -> T {
    Profiler::global().profile(name, f)
}

/// Start a profiled section using the global profiler
pub fn start_profile(name: impl Into<String>) -> ProfileGuard {
    Profiler::global().start(name)
}

/// Get the global profiler report
pub fn profiler_report() -> String {
    Profiler::global().report()
}

// =============================================================================
// Scoped Profiler (Thread-local)
// =============================================================================

thread_local! {
    static THREAD_PROFILER: RefCell<Profiler> = RefCell::new(Profiler::new());
}

/// Get thread-local profiler
pub fn thread_profiler() -> Profiler {
    THREAD_PROFILER.with(|p| p.borrow().clone())
}

// =============================================================================
// Flame Graph Data
// =============================================================================

/// Node in a flame graph
#[derive(Debug, Clone)]
pub struct FlameNode {
    /// Operation name
    pub name: String,
    /// Self time (excluding children)
    pub self_time: Duration,
    /// Total time (including children)
    pub total_time: Duration,
    /// Child nodes
    pub children: Vec<FlameNode>,
}

impl FlameNode {
    /// Create a new flame node
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            self_time: Duration::ZERO,
            total_time: Duration::ZERO,
            children: Vec::new(),
        }
    }

    /// Add time
    pub fn add_time(&mut self, duration: Duration) {
        self.total_time += duration;
        self.self_time += duration;
    }

    /// Add child
    pub fn add_child(&mut self, child: FlameNode) {
        // Subtract child time from self time
        self.self_time = self.self_time.saturating_sub(child.total_time);
        self.children.push(child);
    }

    /// Format as text (for terminal display)
    pub fn format_text(&self, depth: usize) -> String {
        let mut output = String::new();
        let indent = "  ".repeat(depth);
        let percent = if self.total_time.as_nanos() > 0 {
            (self.self_time.as_nanos() as f64 / self.total_time.as_nanos() as f64) * 100.0
        } else {
            100.0
        };

        output.push_str(&format!(
            "{}{} ({:.2}ms / {:.1}%)\n",
            indent,
            self.name,
            self.total_time.as_secs_f64() * 1000.0,
            percent,
        ));

        for child in &self.children {
            output.push_str(&child.format_text(depth + 1));
        }

        output
    }
}

// =============================================================================
// Tests
// =============================================================================