latticearc 0.7.1

Production-ready post-quantum cryptography. Hybrid ML-KEM+X25519 by default, all 4 NIST standards (FIPS 203–206), post-quantum TLS, 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
//! 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;
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: Vec<u128>, // stored as nanoseconds
}

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

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

    /// Record a timing sample
    pub fn record(&mut self, duration: Duration) {
        self.samples.push(duration.as_nanos());
    }

    /// Record multiple timing samples
    pub fn record_batch(&mut self, durations: &[Duration]) {
        self.samples.reserve(durations.len());
        for &duration in durations {
            self.samples.push(duration.as_nanos());
        }
    }

    /// 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).
    #[allow(clippy::arithmetic_side_effects)]
    #[allow(clippy::cast_possible_truncation)]
    #[allow(clippy::cast_precision_loss)]
    #[allow(clippy::cast_sign_loss)]
    #[allow(clippy::cast_lossless)]
    #[must_use]
    pub fn calculate_statistics(&self) -> TimingStatistics {
        if self.samples.is_empty() {
            return TimingStatistics::empty();
        }

        let mut sorted = self.samples.clone();
        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
        };
        let std_dev = Duration::from_nanos(variance.sqrt().to_bits());

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

    /// Calculate a specific percentile
    // Float ↔ integer casting for percentile index computation on sample arrays
    #[allow(clippy::cast_possible_truncation)]
    #[allow(clippy::cast_precision_loss)]
    #[allow(clippy::cast_sign_loss)]
    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
    pub fn merge(&mut self, other: &Histogram) {
        self.samples.extend_from_slice(&other.samples);
    }
}

/// A thread-safe collector for performance metrics
pub struct MetricsCollector {
    histograms: Arc<Mutex<HashMap<String, Histogram>>>,
    operation_counts: Arc<Mutex<HashMap<String, usize>>>,
}

impl MetricsCollector {
    /// Create a new metrics collector
    #[must_use]
    pub fn new() -> Self {
        Self {
            histograms: Arc::new(Mutex::new(HashMap::new())),
            operation_counts: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    /// Record a single operation timing
    #[allow(clippy::arithmetic_side_effects)] // Histogram bucket indexing on bounded duration values
    pub fn record_operation(&self, name: &str, duration: Duration) {
        if let Ok(mut histograms) = self.histograms.lock() {
            histograms
                .entry(name.to_string())
                .or_insert_with(Histogram::new_default)
                .record(duration);
        }

        if let Ok(mut counts) = self.operation_counts.lock() {
            let current_count = counts.entry(name.to_string()).or_insert(0);
            *current_count = current_count.saturating_add(1);
        }
    }

    /// Get statistics for a specific operation
    pub fn get_statistics(&self, name: &str) -> TimingStatistics {
        if let Ok(histograms) = self.histograms.lock() {
            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(counts) = self.operation_counts.lock() {
            *counts.get(name).unwrap_or(&0)
        } else {
            0
        }
    }

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

    /// Get all statistics
    #[must_use]
    pub fn get_all_statistics(&self) -> HashMap<String, TimingStatistics> {
        if let Ok(histograms) = self.histograms.lock() {
            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 histograms) = self.histograms.lock() {
            histograms.clear();
        }

        if let Ok(mut counts) = self.operation_counts.lock() {
            counts.clear();
        }
    }

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

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());
    }
}