rich_rust 0.2.1

A Rust port of Python's Rich library for beautiful terminal output
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
//! End-to-end performance regression tests for rich_rust.
//!
//! These tests establish and monitor performance baselines to prevent regressions.
//! Run with: cargo test --test e2e_performance -- --nocapture
//!
//! # Environment Variables
//!
//! - `UPDATE_PERF_BASELINE=1` - Update baselines instead of asserting against them
//! - `PERF_REGRESSION_THRESHOLD=30` - Override default regression threshold (default: 20%)
//! - `RUST_LOG=debug` - Enable detailed logging

mod common;

use common::init_test_logging;
use rich_rust::prelude::*;
use std::time::Instant;

// =============================================================================
// Configuration
// =============================================================================

/// Default regression threshold percentage (50% slower than baseline = failure)
///
/// This threshold is deliberately generous to accommodate CI/shared environments
/// where machine load varies. The goal is to catch major regressions (2x+ slowdowns)
/// while avoiding false positives from load variability.
const DEFAULT_REGRESSION_THRESHOLD: f64 = 50.0;

/// Load baselines from JSON file
fn load_baselines() -> serde_json::Value {
    let content = include_str!("perf_baselines.json");
    serde_json::from_str(content).expect("Failed to parse perf_baselines.json")
}

/// Get baseline value for a specific metric
fn get_baseline_ms(name: &str) -> Option<u64> {
    let baselines = load_baselines();
    baselines["baselines"][name].as_u64()
}

/// Get regression threshold percentage
fn get_regression_threshold() -> f64 {
    std::env::var("PERF_REGRESSION_THRESHOLD")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(DEFAULT_REGRESSION_THRESHOLD)
}

/// Check if we should update baselines instead of asserting
fn should_update_baselines() -> bool {
    std::env::var("UPDATE_PERF_BASELINE").is_ok()
}

/// Assert performance is within threshold of baseline
fn assert_perf_within_threshold(name: &str, elapsed_ms: u128) {
    let baseline = match get_baseline_ms(name) {
        Some(b) => b,
        None => {
            tracing::warn!(metric = name, "No baseline found, skipping assertion");
            return;
        }
    };

    let threshold = get_regression_threshold();
    let max_allowed = (baseline as f64 * (1.0 + threshold / 100.0)) as u128;
    let percent_of_baseline = (elapsed_ms as f64 / baseline as f64) * 100.0;

    tracing::info!(
        metric = name,
        elapsed_ms = elapsed_ms,
        baseline_ms = baseline,
        percent_of_baseline = format!("{:.1}%", percent_of_baseline),
        threshold = format!("{}%", threshold),
        "Performance measurement"
    );

    if should_update_baselines() {
        tracing::info!(
            metric = name,
            new_value = elapsed_ms,
            "Baseline update requested (UPDATE_PERF_BASELINE=1)"
        );
        return;
    }

    assert!(
        elapsed_ms <= max_allowed,
        "Performance regression detected for '{}': {}ms > {}ms ({}% of baseline, threshold: {}%)",
        name,
        elapsed_ms,
        max_allowed,
        percent_of_baseline as u64,
        threshold
    );
}

// =============================================================================
// Helper Functions
// =============================================================================

/// Create a large table for performance testing
fn create_large_table(rows: usize, cols: usize) -> Table {
    let mut table = Table::new();

    // Add columns
    for i in 0..cols {
        table = table.with_column(Column::new(format!("Column {}", i + 1)));
    }

    // Add rows
    for r in 0..rows {
        let cells: Vec<String> = (0..cols)
            .map(|c| format!("Row {} Col {}", r + 1, c + 1))
            .collect();
        table.add_row_cells(cells);
    }

    table
}

/// Generate random-ish text for testing
fn generate_text(length: usize) -> String {
    let words = [
        "the",
        "quick",
        "brown",
        "fox",
        "jumps",
        "over",
        "lazy",
        "dog",
        "Lorem",
        "ipsum",
        "dolor",
        "sit",
        "amet",
        "consectetur",
        "adipiscing",
        "elit",
        "sed",
        "do",
        "eiusmod",
        "tempor",
        "incididunt",
        "ut",
        "labore",
    ];

    let mut result = String::with_capacity(length);
    let mut word_idx = 0;

    while result.len() < length {
        if !result.is_empty() {
            result.push(' ');
        }
        result.push_str(words[word_idx % words.len()]);
        word_idx += 1;
    }

    result.truncate(length);
    result
}

/// Generate markup text with varying complexity
fn generate_markup(count: usize, nested: bool) -> String {
    let mut markup = String::new();

    for i in 0..count {
        if nested {
            markup.push_str(&format!(
                "[bold][red]Item {}[/red] with [italic]nested[/italic] styles[/bold] ",
                i + 1
            ));
        } else {
            markup.push_str(&format!("[bold]Item {}[/bold] ", i + 1));
        }
    }

    markup
}

// =============================================================================
// Table Performance Tests
// =============================================================================

#[test]
fn perf_large_table_100x10() {
    init_test_logging();
    tracing::info!("Starting performance test: large table 100x10");

    let table = create_large_table(100, 10);

    let start = Instant::now();
    let segments = table.render(200);
    let elapsed = start.elapsed();

    // Verify rendering produced output
    let output: String = segments.iter().map(|s| s.text.as_ref()).collect();
    assert!(
        output.contains("Column 1") && output.contains("Row 1 Col 1"),
        "Rendered table should include headers and cell values"
    );

    tracing::info!(
        rows = 100,
        columns = 10,
        segment_count = segments.len(),
        output_len = output.len(),
        elapsed_ms = elapsed.as_millis(),
        "Large table 100x10 rendered"
    );

    assert_perf_within_threshold("large_table_100x10_ms", elapsed.as_millis());
}

#[test]
fn perf_large_table_500x20() {
    init_test_logging();
    tracing::info!("Starting performance test: large table 500x20");

    let table = create_large_table(500, 20);

    let start = Instant::now();
    let segments = table.render(300);
    let elapsed = start.elapsed();

    let output: String = segments.iter().map(|s| s.text.as_ref()).collect();
    assert!(
        output.contains("Column 1") && output.contains("Row 1 Col 1"),
        "Rendered table should include headers and cell values"
    );

    tracing::info!(
        rows = 500,
        columns = 20,
        segment_count = segments.len(),
        elapsed_ms = elapsed.as_millis(),
        "Large table 500x20 rendered"
    );

    assert_perf_within_threshold("large_table_500x20_ms", elapsed.as_millis());
}

// =============================================================================
// Color Parsing Performance Tests
// =============================================================================

#[test]
fn perf_color_parse_10000() {
    init_test_logging();
    tracing::info!("Starting performance test: color parsing 10000 unique colors");

    // Generate unique colors to test parsing without cache hits
    let colors: Vec<String> = (0..10000)
        .map(|i| format!("#{:06x}", i % 0xFFFFFF))
        .collect();

    let start = Instant::now();
    let mut parsed_count = 0;

    for color_str in &colors {
        if Color::parse(color_str).is_ok() {
            parsed_count += 1;
        }
    }

    let elapsed = start.elapsed();

    tracing::info!(
        color_count = colors.len(),
        parsed_count = parsed_count,
        elapsed_ms = elapsed.as_millis(),
        "Color parsing complete"
    );

    assert_eq!(parsed_count, 10000, "All colors should parse successfully");
    assert_perf_within_threshold("color_parse_10000_ms", elapsed.as_millis());
}

#[test]
fn perf_color_parse_10000_cached() {
    init_test_logging();
    tracing::info!("Starting performance test: color parsing 10000 with cache hits");

    // Use a small set of colors repeatedly to test cache performance
    let base_colors = [
        "red", "green", "blue", "yellow", "cyan", "magenta", "#ff0000", "#00ff00",
    ];

    // Warm up the cache
    for color in &base_colors {
        let _ = Color::parse(color);
    }

    let start = Instant::now();
    let mut parsed_count = 0;

    for i in 0..10000 {
        let color_str = base_colors[i % base_colors.len()];
        if Color::parse(color_str).is_ok() {
            parsed_count += 1;
        }
    }

    let elapsed = start.elapsed();

    tracing::info!(
        iteration_count = 10000,
        unique_colors = base_colors.len(),
        parsed_count = parsed_count,
        elapsed_ms = elapsed.as_millis(),
        "Cached color parsing complete"
    );

    assert_eq!(parsed_count, 10000, "All colors should parse successfully");
    assert_perf_within_threshold("color_parse_10000_cached_ms", elapsed.as_millis());
}

// =============================================================================
// Text Wrapping Performance Tests
// =============================================================================

#[test]
fn perf_text_wrap_10000_chars() {
    init_test_logging();
    tracing::info!("Starting performance test: text wrap 10000 chars");

    let text_content = generate_text(10000);
    let text = Text::new(&text_content);

    let start = Instant::now();
    let wrapped = text.wrap(80);
    let elapsed = start.elapsed();

    tracing::info!(
        input_chars = text_content.len(),
        output_lines = wrapped.len(),
        elapsed_ms = elapsed.as_millis(),
        "Text wrapping complete"
    );

    assert!(
        !wrapped.is_empty() && wrapped.iter().all(|line| line.cell_len() <= 80),
        "Wrapped lines should be non-empty and respect the width constraint"
    );
    assert_perf_within_threshold("text_wrap_10000_chars_ms", elapsed.as_millis());
}

#[test]
fn perf_text_wrap_50000_chars() {
    init_test_logging();
    tracing::info!("Starting performance test: text wrap 50000 chars");

    let text_content = generate_text(50000);
    let text = Text::new(&text_content);

    let start = Instant::now();
    let wrapped = text.wrap(80);
    let elapsed = start.elapsed();

    tracing::info!(
        input_chars = text_content.len(),
        output_lines = wrapped.len(),
        elapsed_ms = elapsed.as_millis(),
        "Large text wrapping complete"
    );

    assert!(
        !wrapped.is_empty() && wrapped.iter().all(|line| line.cell_len() <= 80),
        "Wrapped lines should be non-empty and respect the width constraint"
    );
    assert_perf_within_threshold("text_wrap_50000_chars_ms", elapsed.as_millis());
}

// =============================================================================
// Markup Parsing Performance Tests
// =============================================================================

#[test]
fn perf_markup_parse_simple_1000() {
    init_test_logging();
    tracing::info!("Starting performance test: markup parse 1000 simple items");

    let markup = generate_markup(1000, false);

    let start = Instant::now();
    let result = rich_rust::markup::render(&markup);
    let elapsed = start.elapsed();

    let text = result.expect("Markup should parse successfully");

    tracing::info!(
        markup_len = markup.len(),
        result_chars = text.plain().len(),
        elapsed_ms = elapsed.as_millis(),
        "Simple markup parsing complete"
    );

    assert_perf_within_threshold("markup_parse_simple_1000_ms", elapsed.as_millis());
}

#[test]
fn perf_markup_parse_nested_1000() {
    init_test_logging();
    tracing::info!("Starting performance test: markup parse 1000 nested items");

    let markup = generate_markup(1000, true);

    let start = Instant::now();
    let result = rich_rust::markup::render(&markup);
    let elapsed = start.elapsed();

    let text = result.expect("Nested markup should parse successfully");

    tracing::info!(
        markup_len = markup.len(),
        result_chars = text.plain().len(),
        elapsed_ms = elapsed.as_millis(),
        "Nested markup parsing complete"
    );

    assert_perf_within_threshold("markup_parse_nested_1000_ms", elapsed.as_millis());
}

// =============================================================================
// Segment Operations Performance Tests
// =============================================================================

#[test]
fn perf_segment_merge_10000() {
    init_test_logging();
    tracing::info!("Starting performance test: segment merge 10000");

    // Create many segments
    let style = Style::new().bold();
    let segments: Vec<Segment> = (0..10000)
        .map(|i| Segment::new(format!("Seg{} ", i), Some(style.clone())))
        .collect();

    let start = Instant::now();

    // Merge consecutive segments with same style
    let mut simplified: Vec<Segment> = Vec::new();
    for seg in segments {
        if let Some(last) = simplified.last_mut()
            && last.style == seg.style
        {
            last.text.to_mut().push_str(&seg.text);
            continue;
        }
        simplified.push(seg);
    }

    let elapsed = start.elapsed();

    tracing::info!(
        input_count = 10000,
        merged_count = simplified.len(),
        elapsed_ms = elapsed.as_millis(),
        "Segment merging complete"
    );

    assert_perf_within_threshold("segment_merge_10000_ms", elapsed.as_millis());
}

// =============================================================================
// Style Operations Performance Tests
// =============================================================================

#[test]
fn perf_style_combine_10000() {
    init_test_logging();
    tracing::info!("Starting performance test: style combine 10000");

    let base_styles = [
        Style::new().bold(),
        Style::new().italic(),
        Style::new().underline(),
        Style::new().color(Color::parse("red").unwrap()),
        Style::new().bgcolor(Color::parse("blue").unwrap()),
    ];

    let start = Instant::now();
    let mut result = Style::default();

    for i in 0..10000 {
        let style = &base_styles[i % base_styles.len()];
        result = result.combine(style);
    }

    let elapsed = start.elapsed();

    tracing::info!(
        iterations = 10000,
        final_bold = result.attributes.contains(Attributes::BOLD),
        elapsed_ms = elapsed.as_millis(),
        "Style combining complete"
    );

    assert_perf_within_threshold("style_combine_10000_ms", elapsed.as_millis());
}

// =============================================================================
// Memory Stress Test
// =============================================================================

#[test]
fn perf_memory_stress_large_document() {
    init_test_logging();
    tracing::info!("Starting performance test: memory stress with large document");

    // Create a large document with multiple elements
    let _console = Console::new(); // For future use
    let width = 120;

    // Multiple tables
    let mut all_segments: Vec<Segment> = Vec::new();

    for table_num in 0..10 {
        let table = create_large_table(50, 5).title(format!("Table {}", table_num + 1));

        all_segments.extend(table.render(width));
    }

    // Multiple panels
    for _ in 0..10 {
        let content = format!("Panel content {}", "X".repeat(100));
        let panel = Panel::from_text(&content).width(50).expand(false);
        let segments: Vec<Segment> = panel
            .render(80)
            .into_iter()
            .map(|s| s.into_owned())
            .collect();
        all_segments.extend(segments);
    }

    // Multiple rules
    for rule_num in 0..30 {
        let title = format!("Section {}", rule_num + 1);
        let rule = Rule::with_title(title); // Takes ownership
        all_segments.extend(rule.render(width));
    }

    let total_text_len: usize = all_segments.iter().map(|s| s.text.len()).sum();

    tracing::info!(
        segment_count = all_segments.len(),
        total_text_bytes = total_text_len,
        tables = 10,
        panels = 20,
        rules = 30,
        "Large document rendering complete"
    );

    // Verify reasonable bounds
    assert!(
        all_segments.len() < 1_000_000,
        "Segment count should be bounded"
    );
    assert!(total_text_len < 10_000_000, "Total text should be bounded");
}

// =============================================================================
// Baseline Summary Test
// =============================================================================

#[test]
fn perf_print_baseline_summary() {
    init_test_logging();

    let baselines = load_baselines();
    let threshold = get_regression_threshold();

    tracing::info!(
        version = baselines["version"].as_str().unwrap_or("unknown"),
        regression_threshold = format!("{}%", threshold),
        "Performance baseline configuration"
    );

    if let Some(baseline_map) = baselines["baselines"].as_object() {
        for (name, value) in baseline_map {
            let metric_name: &str = name.as_str();
            let baseline_val: u64 = value.as_u64().unwrap_or(0);
            let max_allowed: u64 = (baseline_val as f64 * (1.0 + threshold / 100.0)) as u64;
            tracing::info!(
                metric = metric_name,
                baseline_ms = baseline_val,
                max_allowed_ms = max_allowed,
                "Baseline"
            );
        }
    }
}