latticearc 0.8.4

Production-ready post-quantum cryptography. Hybrid ML-KEM+X25519 by default, all 4 NIST standards (FIPS 203–206), and FIPS 140-3 backend — one crate, zero unsafe.
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
//! LatticeArc Performance Primitives
//!
//! This module provides performance monitoring, benchmarking, and metrics collection
//! for cryptographic operations. It is designed to have minimal overhead when disabled
//! and is included by default (no feature flag required).
//!
//! # Features
//!
//! - **Timing Utilities**: Measure execution times for cryptographic operations
//! - **Histogram/Percentile**: Compute latency distribution statistics
//! - **Metrics Collection**: Track operation counts, timings, and resource usage
//!
//! # Example
//!
//! ```rust,no_run
//! use latticearc::perf::{Timer, MetricsCollector};
//!
//! // Measure execution time of an operation
//! let mut timer = Timer::start();
//! // ... perform cryptographic operation ...
//! let duration = timer.stop();
//!
//! // Collect metrics over multiple operations
//! let mut collector = MetricsCollector::new();
//! collector.record_operation("keygen", duration);
//! collector.record_operation("encrypt", duration);
//!
//! // Get statistics
//! let stats = collector.get_statistics("keygen");
//! println!("Average: {:?}", stats.average);
//! println!("P99: {:?}", stats.percentile_99);
//! ```

use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// A simple high-resolution timer for measuring execution time
#[derive(Debug, Clone, Copy)]
pub struct Timer {
    start_time: Option<Instant>,
    elapsed: Duration,
}

impl Timer {
    /// Create a new timer that starts immediately
    #[inline]
    #[must_use]
    pub fn start() -> Self {
        Self { start_time: Some(Instant::now()), elapsed: Duration::ZERO }
    }

    /// Create a new timer that is not yet started
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Self { start_time: None, elapsed: Duration::ZERO }
    }

    /// Start the timer (or restart if already running)
    #[inline]
    pub fn start_now(&mut self) {
        self.start_time = Some(Instant::now());
        self.elapsed = Duration::ZERO;
    }

    /// Stop the timer and return the elapsed duration
    #[inline]
    pub fn stop(&mut self) -> Duration {
        if let Some(start) = self.start_time.take() {
            self.elapsed = start.elapsed();
        }
        self.elapsed
    }

    /// Get the current elapsed duration without stopping the timer
    #[inline]
    #[must_use]
    pub fn elapsed(&self) -> Duration {
        if let Some(start) = self.start_time { start.elapsed() } else { self.elapsed }
    }

    /// Check if the timer is currently running
    #[inline]
    #[must_use]
    pub fn is_running(&self) -> bool {
        self.start_time.is_some()
    }
}

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

/// Statistics for a set of timing measurements
#[derive(Debug, Clone)]
pub struct TimingStatistics {
    /// Number of samples
    pub count: usize,
    /// Minimum duration
    pub min: Duration,
    /// Maximum duration
    pub max: Duration,
    /// Average duration
    pub average: Duration,
    /// Median duration
    pub median: Duration,
    /// 90th percentile
    pub percentile_90: Duration,
    /// 95th percentile
    pub percentile_95: Duration,
    /// 99th percentile
    pub percentile_99: Duration,
    /// Standard deviation
    pub std_dev: Duration,
}

impl TimingStatistics {
    /// Create empty statistics
    #[must_use]
    pub fn empty() -> Self {
        Self {
            count: 0,
            min: Duration::ZERO,
            max: Duration::ZERO,
            average: Duration::ZERO,
            median: Duration::ZERO,
            percentile_90: Duration::ZERO,
            percentile_95: Duration::ZERO,
            percentile_99: Duration::ZERO,
            std_dev: Duration::ZERO,
        }
    }
}

impl Default for TimingStatistics {
    fn default() -> Self {
        Self::empty()
    }
}

/// Histogram for collecting and analyzing timing distributions
#[derive(Debug, Clone)]
pub struct Histogram {
    /// Samples in nanoseconds. `VecDeque` (not `Vec`) so the FIFO
    /// drop-oldest in `record` is O(1) once the buffer reaches
    /// `MAX_SAMPLES_PER_HISTOGRAM`.
    samples: VecDeque<u128>,
}

impl Histogram {
    /// Create a new empty histogram with pre-allocated capacity
    #[must_use]
    pub fn new(capacity: usize) -> Self {
        Self { samples: VecDeque::with_capacity(capacity) }
    }

    /// Create a new empty histogram
    #[must_use]
    pub fn new_default() -> Self {
        Self::new(100)
    }

    /// Cap on a single histogram's sample buffer (~1 MiB per
    /// histogram). Generous resolution for any percentile of interest;
    /// FIFO drop-oldest at this cap.
    const MAX_SAMPLES_PER_HISTOGRAM: usize = 65_536;

    /// Record a timing sample. At `MAX_SAMPLES_PER_HISTOGRAM` the
    /// oldest sample is dropped (`VecDeque::pop_front` is O(1)).
    pub fn record(&mut self, duration: Duration) {
        if self.samples.len() >= Self::MAX_SAMPLES_PER_HISTOGRAM {
            self.samples.pop_front();
        }
        self.samples.push_back(duration.as_nanos());
    }

    /// Record multiple timing samples. Same FIFO bound as `record`.
    pub fn record_batch(&mut self, durations: &[Duration]) {
        // Reserve only the headroom up to the cap. An unconditional
        // `reserve(durations.len())` would transiently allocate
        // capacity for samples that the per-element FIFO will
        // immediately drop — defeating the L8 DoS bound.
        let headroom = Self::MAX_SAMPLES_PER_HISTOGRAM.saturating_sub(self.samples.len());
        self.samples.reserve(durations.len().min(headroom));
        for &duration in durations {
            self.record(duration);
        }
    }

    /// Get the number of samples
    #[must_use]
    pub fn count(&self) -> usize {
        self.samples.len()
    }

    /// Clear all samples
    pub fn clear(&mut self) {
        self.samples.clear();
    }

    /// Calculate statistics for the collected samples
    // Statistical calculations require float casting and modular arithmetic
    // that cannot overflow on timing sample values (nanosecond durations).
    #[expect(
        clippy::arithmetic_side_effects,
        reason = "arithmetic bounded by callsite invariants; overflow impossible at this site"
    )]
    #[expect(
        clippy::cast_precision_loss,
        reason = "precision loss is intentional in this measurement/heuristic path"
    )]
    #[must_use]
    pub fn calculate_statistics(&self) -> TimingStatistics {
        if self.samples.is_empty() {
            return TimingStatistics::empty();
        }

        let mut sorted: Vec<u128> = self.samples.iter().copied().collect();
        sorted.sort_unstable();

        let count = sorted.len();
        let min = Duration::from_nanos(
            sorted.first().copied().and_then(|x| u64::try_from(x).ok()).unwrap_or(0),
        );
        let max = Duration::from_nanos(
            sorted
                .get(count.saturating_sub(1))
                .copied()
                .and_then(|x| u64::try_from(x).ok())
                .unwrap_or(0),
        );
        let sum: u128 = sorted.iter().sum();
        let average = if count > 0 {
            Duration::from_nanos(
                u64::try_from(sum / u128::try_from(count).unwrap_or(1)).unwrap_or(0),
            )
        } else {
            Duration::ZERO
        };

        // Calculate median
        let median = if count.is_multiple_of(2) {
            let half_count = count / 2;
            let mid_left = sorted.get(half_count.saturating_sub(1)).copied().unwrap_or(0);
            let mid_right = sorted.get(half_count).copied().unwrap_or(0);
            Duration::from_nanos(u64::try_from((mid_left + mid_right) / 2).unwrap_or(0))
        } else {
            let half_count = count / 2;
            Duration::from_nanos(
                u64::try_from(sorted.get(half_count).copied().unwrap_or(0)).unwrap_or(0),
            )
        };

        // Calculate percentiles
        let percentile_90 = Self::percentile(&sorted, 90.0);
        let percentile_95 = Self::percentile(&sorted, 95.0);
        let percentile_99 = Self::percentile(&sorted, 99.0);

        // Calculate standard deviation
        let mean = average.as_nanos() as f64;
        let variance = if count > 0 {
            sorted
                .iter()
                .map(|&x| {
                    let x_f64 = x as f64;
                    let diff = x_f64 - mean;
                    diff * diff
                })
                .sum::<f64>()
                / count as f64
        } else {
            0.0
        };
        // `f64::to_bits()` returns the IEEE-754 bit pattern, not the
        // numeric value; `as u64` is the correct cast for a non-negative
        // finite f64 → integer ns.
        #[expect(
            clippy::cast_possible_truncation,
            clippy::cast_sign_loss,
            reason = "f64-to-u64 cast on variance.sqrt(): a Duration std-dev exceeding u64 nanoseconds (~584 years) cannot occur on real timing samples; sign-loss is sound because variance is non-negative"
        )]
        let std_dev = Duration::from_nanos(variance.sqrt() as u64);

        TimingStatistics {
            count,
            min,
            max,
            average,
            median,
            percentile_90,
            percentile_95,
            percentile_99,
            std_dev,
        }
    }

    /// Calculate a specific percentile using **nearest-rank without
    /// interpolation** (truncate the float index to `usize`). This is
    /// what NIST SP 800-22 §1.1.5 calls "rounded percentile" and what
    /// numpy's `interpolation='lower'` reports. It is NOT the R-7 /
    /// linear-interpolation form most stats packages report by default.
    /// Concrete example: with `sorted = [a, b]`, `p99` returns `a`, not
    /// `b`, because `0.99 * 1 = 0.99` truncates to index `0`. Acceptable
    /// for the usage here (perf-monitoring, where exact tail-shape
    /// resolution requires more samples than nearest-rank-vs-interp
    /// affects).
    // Float ↔ integer casting for percentile index computation on sample arrays
    #[expect(
        clippy::cast_possible_truncation,
        reason = "truncation guarded by callsite preconditions"
    )]
    #[expect(
        clippy::cast_precision_loss,
        reason = "precision loss is intentional in this measurement/heuristic path"
    )]
    #[expect(clippy::cast_sign_loss, reason = "sign loss is intentional in this conversion path")]
    fn percentile(sorted: &[u128], percentile: f64) -> Duration {
        if sorted.is_empty() {
            return Duration::ZERO;
        }

        let len = sorted.len();
        let float_index = (percentile / 100.0) * (len.saturating_sub(1) as f64);
        let index = float_index as usize;
        let safe_index = index.min(len.saturating_sub(1));
        Duration::from_nanos(
            sorted.get(safe_index).copied().and_then(|x| u64::try_from(x).ok()).unwrap_or(0),
        )
    }

    /// Merge another histogram into this one. Honours the per-histogram
    /// sample cap: if the combined count exceeds
    /// `MAX_SAMPLES_PER_HISTOGRAM`, oldest samples are dropped (FIFO),
    /// preserving the moving-window invariant of `record`.
    pub fn merge(&mut self, other: &Histogram) {
        self.samples.extend(other.samples.iter().copied());
        while self.samples.len() > Self::MAX_SAMPLES_PER_HISTOGRAM {
            self.samples.pop_front();
        }
    }
}

/// Histograms and per-operation counters held under a single mutex
/// so observers always see a consistent (samples, count) pair for
/// any operation name. Splitting these into two mutexes opens an
/// interleave where another thread reads `count = N` after the
/// histogram has accepted sample `N+1` but before the counter has
/// been incremented.
#[derive(Default)]
struct MetricsState {
    histograms: HashMap<String, Histogram>,
    operation_counts: HashMap<String, usize>,
}

/// A thread-safe collector for performance metrics
pub struct MetricsCollector {
    state: Arc<Mutex<MetricsState>>,
}

impl MetricsCollector {
    /// Cap on distinct operation names. Bounds memory against callers
    /// (or attackers) that pass per-request / arbitrary labels. New
    /// names beyond this cap are dropped with a `tracing::warn`.
    const MAX_DISTINCT_OPERATIONS: usize = 1024;

    /// Create a new metrics collector
    #[must_use]
    pub fn new() -> Self {
        Self { state: Arc::new(Mutex::new(MetricsState::default())) }
    }

    /// Record a single operation timing
    pub fn record_operation(&self, name: &str, duration: Duration) {
        // Single lock acquisition keeps the histogram update and the
        // counter increment atomic w.r.t. other observers.
        match self.state.lock() {
            Ok(mut state) => {
                let MetricsState { histograms, operation_counts } = &mut *state;

                let histogram_accepted = if let Some(h) = histograms.get_mut(name) {
                    h.record(duration);
                    true
                } else if histograms.len() < Self::MAX_DISTINCT_OPERATIONS {
                    let mut h = Histogram::new_default();
                    h.record(duration);
                    histograms.insert(name.to_string(), h);
                    true
                } else {
                    tracing::warn!(
                        operation = name,
                        cap = Self::MAX_DISTINCT_OPERATIONS,
                        "perf::MetricsCollector: distinct-operation cap reached; metric dropped"
                    );
                    false
                };

                if histogram_accepted {
                    if let Some(c) = operation_counts.get_mut(name) {
                        *c = c.saturating_add(1);
                    } else {
                        // Histogram accepted (existing OR newly inserted under
                        // the same cap), so the counter half is also under cap.
                        operation_counts.insert(name.to_string(), 1);
                    }
                }
            }
            Err(_) => {
                tracing::warn!(
                    operation = name,
                    "perf::MetricsCollector: state mutex poisoned; metric dropped"
                );
            }
        }
    }

    /// Get statistics for a specific operation
    pub fn get_statistics(&self, name: &str) -> TimingStatistics {
        if let Ok(state) = self.state.lock() {
            state
                .histograms
                .get(name)
                .map(Histogram::calculate_statistics)
                .unwrap_or_else(TimingStatistics::empty)
        } else {
            TimingStatistics::empty()
        }
    }

    /// Get the total count for a specific operation
    #[must_use]
    pub fn get_count(&self, name: &str) -> usize {
        if let Ok(state) = self.state.lock() {
            *state.operation_counts.get(name).unwrap_or(&0)
        } else {
            0
        }
    }

    /// Get all operation names
    #[must_use]
    pub fn operation_names(&self) -> Vec<String> {
        if let Ok(state) = self.state.lock() {
            state.histograms.keys().cloned().collect()
        } else {
            Vec::new()
        }
    }

    /// Get all statistics
    #[must_use]
    pub fn get_all_statistics(&self) -> HashMap<String, TimingStatistics> {
        if let Ok(state) = self.state.lock() {
            state
                .histograms
                .iter()
                .map(|(name, h)| (name.clone(), h.calculate_statistics()))
                .collect()
        } else {
            HashMap::new()
        }
    }

    /// Clear all collected metrics
    pub fn clear(&self) {
        if let Ok(mut state) = self.state.lock() {
            state.histograms.clear();
            state.operation_counts.clear();
        }
    }

    /// Create a clone of the collector that shares the same underlying data
    #[must_use]
    pub fn clone_collector(&self) -> Self {
        Self { state: Arc::clone(&self.state) }
    }
}

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

impl Clone for MetricsCollector {
    fn clone(&self) -> Self {
        self.clone_collector()
    }
}

/// RAII-style timer that automatically records to a metrics collector
pub struct ScopedTimer<'a> {
    timer: Timer,
    collector: Option<&'a MetricsCollector>,
    operation_name: Option<&'a str>,
}

impl<'a> ScopedTimer<'a> {
    /// Create a new scoped timer that records to the collector when dropped
    #[must_use]
    pub fn new(collector: &'a MetricsCollector, operation_name: &'a str) -> Self {
        Self {
            timer: Timer::start(),
            collector: Some(collector),
            operation_name: Some(operation_name),
        }
    }

    /// Create a new scoped timer without a collector (timing only)
    #[must_use]
    pub fn timing_only() -> Self {
        Self { timer: Timer::start(), collector: None, operation_name: None }
    }

    /// Stop the timer and get the elapsed duration
    #[must_use]
    pub fn stop(mut self) -> Duration {
        let duration = self.timer.stop();
        if let (Some(collector), Some(name)) = (self.collector, self.operation_name) {
            collector.record_operation(name, duration);
        }
        duration
    }

    /// Get the current elapsed duration without stopping
    #[must_use]
    pub fn elapsed(&self) -> Duration {
        self.timer.elapsed()
    }
}

impl<'a> Drop for ScopedTimer<'a> {
    fn drop(&mut self) {
        if let (Some(collector), Some(name)) = (self.collector, self.operation_name)
            && self.timer.is_running()
        {
            let duration = self.timer.stop();
            collector.record_operation(name, duration);
        }
    }
}

/// Benchmark helper for running an operation multiple times
pub fn benchmark<F>(iterations: usize, operation: F) -> TimingStatistics
where
    F: Fn(),
{
    let mut histogram = Histogram::new(iterations);

    // Warm-up phase
    for _ in 0..10.min(iterations / 10) {
        operation();
    }

    // Benchmark phase
    for _ in 0..iterations {
        let mut timer = Timer::start();
        operation();
        histogram.record(timer.stop());
    }

    histogram.calculate_statistics()
}

/// Helper to time a single operation
pub fn time_operation<F>(operation: F) -> Duration
where
    F: FnOnce(),
{
    let mut timer = Timer::start();
    operation();
    timer.stop()
}

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

    #[test]
    fn test_timer_basic_is_correct() {
        let mut timer = Timer::new();
        assert!(!timer.is_running());

        timer.start_now();
        assert!(timer.is_running());

        std::thread::sleep(Duration::from_millis(10));
        let elapsed = timer.stop();
        assert!(!timer.is_running());
        assert!(elapsed >= Duration::from_millis(10));
    }

    #[test]
    fn test_timer_elapsed_while_running_is_correct() {
        let timer = Timer::start();
        std::thread::sleep(Duration::from_millis(5));
        let elapsed = timer.elapsed();
        assert!(elapsed >= Duration::from_millis(5));
        assert!(timer.is_running());
    }

    #[test]
    fn test_histogram_basic_is_correct() {
        let mut histogram = Histogram::new(10);
        histogram.record(Duration::from_millis(10));
        histogram.record(Duration::from_millis(20));
        histogram.record(Duration::from_millis(30));

        assert_eq!(histogram.count(), 3);

        let stats = histogram.calculate_statistics();
        assert_eq!(stats.count, 3);
        assert_eq!(stats.min, Duration::from_millis(10));
        assert_eq!(stats.max, Duration::from_millis(30));
        assert_eq!(stats.median, Duration::from_millis(20));
    }

    #[test]
    fn test_histogram_empty_has_zero_count_succeeds() {
        let histogram = Histogram::new(10);
        let stats = histogram.calculate_statistics();
        assert_eq!(stats.count, 0);
        assert_eq!(stats.min, Duration::ZERO);
    }

    #[test]
    fn test_histogram_merge_is_correct() {
        let mut hist1 = Histogram::new(5);
        hist1.record(Duration::from_millis(10));
        hist1.record(Duration::from_millis(20));

        let mut hist2 = Histogram::new(5);
        hist2.record(Duration::from_millis(30));
        hist2.record(Duration::from_millis(40));

        hist1.merge(&hist2);
        assert_eq!(hist1.count(), 4);

        let stats = hist1.calculate_statistics();
        assert_eq!(stats.min, Duration::from_millis(10));
        assert_eq!(stats.max, Duration::from_millis(40));
    }

    #[test]
    fn test_metrics_collector_is_correct() {
        let collector = MetricsCollector::new();

        collector.record_operation("test", Duration::from_millis(10));
        collector.record_operation("test", Duration::from_millis(20));
        collector.record_operation("other", Duration::from_millis(30));

        assert_eq!(collector.get_count("test"), 2);
        assert_eq!(collector.get_count("other"), 1);

        let stats = collector.get_statistics("test");
        assert_eq!(stats.count, 2);
        assert_eq!(stats.min, Duration::from_millis(10));
        assert_eq!(stats.max, Duration::from_millis(20));
    }

    #[test]
    fn test_metrics_collector_clone_is_correct() {
        let collector1 = MetricsCollector::new();
        let collector2 = collector1.clone();

        collector1.record_operation("test", Duration::from_millis(10));
        assert_eq!(collector2.get_count("test"), 1);
    }

    #[test]
    fn test_benchmark_is_correct() {
        let stats = benchmark(100, || {
            // Simple operation
            let _ = 1 + 1;
        });

        assert_eq!(stats.count, 100);
        assert!(stats.average > Duration::ZERO);
        assert!(stats.min <= stats.average);
        assert!(stats.max >= stats.average);
    }

    #[test]
    fn test_time_operation_returns_elapsed_duration_succeeds() {
        let duration = time_operation(|| {
            std::thread::sleep(Duration::from_millis(5));
        });

        assert!(duration >= Duration::from_millis(5));
    }

    #[test]
    fn test_scoped_timer_basic_is_correct() {
        let collector = MetricsCollector::new();

        {
            let _timer = ScopedTimer::new(&collector, "test_operation");
            std::thread::sleep(Duration::from_millis(5));
        }

        assert_eq!(collector.get_count("test_operation"), 1);
        let stats = collector.get_statistics("test_operation");
        assert!(stats.average >= Duration::from_millis(5));
    }

    #[test]
    fn test_scoped_timer_timing_only_returns_elapsed_duration_succeeds() {
        let timer = ScopedTimer::timing_only();
        std::thread::sleep(Duration::from_millis(5));
        let elapsed = timer.elapsed();
        assert!(elapsed >= Duration::from_millis(5));
    }

    #[test]
    fn test_percentile_calculation_is_correct() {
        let mut histogram = Histogram::new(100);

        // Add samples from 0 to 99 nanoseconds
        for i in 0..100 {
            histogram.record(Duration::from_nanos(i));
        }

        let stats = histogram.calculate_statistics();

        // P50 should be close to 50ns
        assert!(stats.median.as_nanos() >= 45 && stats.median.as_nanos() <= 55);

        // P90 should be close to 90ns
        assert!(stats.percentile_90.as_nanos() >= 85 && stats.percentile_90.as_nanos() <= 95);

        // P99 should be close to 99ns
        assert!(stats.percentile_99.as_nanos() >= 95 && stats.percentile_99.as_nanos() <= 99);
    }

    #[test]
    fn test_timing_statistics_default_has_zero_values_succeeds() {
        let stats = TimingStatistics::default();
        assert_eq!(stats.count, 0);
        assert_eq!(stats.min, Duration::ZERO);
        assert_eq!(stats.max, Duration::ZERO);
    }

    #[test]
    fn test_histogram_clear_succeeds() {
        let mut histogram = Histogram::new(10);
        histogram.record(Duration::from_millis(10));
        histogram.record(Duration::from_millis(20));

        assert_eq!(histogram.count(), 2);

        histogram.clear();
        assert_eq!(histogram.count(), 0);
    }

    #[test]
    fn test_metrics_collector_clear_succeeds() {
        let collector = MetricsCollector::new();
        collector.record_operation("test", Duration::from_millis(10));
        collector.record_operation("other", Duration::from_millis(20));

        assert_eq!(collector.get_count("test"), 1);
        assert_eq!(collector.get_count("other"), 1);

        collector.clear();

        assert_eq!(collector.get_count("test"), 0);
        assert_eq!(collector.get_count("other"), 0);
        assert!(collector.operation_names().is_empty());
    }
}