trustformers-mobile 0.1.1

Mobile deployment support for TrustformeRS (iOS, Android)
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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
//! Metrics collection and aggregation for mobile performance profiling.
//!
//! This module provides comprehensive metrics collection capabilities including
//! memory, CPU, GPU, network, and inference metrics with platform-specific
//! implementations for iOS and Android devices.

use anyhow::Result;
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use trustformers_core::errors::TrustformersError;

use crate::device_info::ThermalState;

use super::config::MobileProfilerConfig;
use super::types::{CpuMetrics, GpuMetrics, InferenceMetrics, MemoryMetrics, NetworkMetrics};

// Import libc for platform-specific system calls
#[cfg(any(target_os = "ios", target_os = "android"))]
extern crate libc;

/// Mobile metrics collector for comprehensive performance monitoring
pub struct MobileMetricsCollector {
    /// Configuration
    config: MobileProfilerConfig,
    /// Current metrics snapshot
    current_metrics: MobileMetricsSnapshot,
    /// Historical metrics data
    metrics_history: VecDeque<MobileMetricsSnapshot>,
    /// Sampling timer
    sampling_timer: Option<Instant>,
    /// Collection start time
    collection_start: Option<Instant>,
    /// Total samples collected
    total_samples: u64,
}

/// Comprehensive mobile metrics snapshot
#[derive(Debug, Clone)]
pub struct MobileMetricsSnapshot {
    /// Timestamp
    pub timestamp: u64,
    /// Memory metrics
    pub memory: MemoryMetrics,
    /// CPU metrics
    pub cpu: CpuMetrics,
    /// GPU metrics
    pub gpu: GpuMetrics,
    /// Network metrics
    pub network: NetworkMetrics,
    /// Inference metrics
    pub inference: InferenceMetrics,
    /// Thermal metrics
    pub thermal: ThermalMetrics,
    /// Battery metrics
    pub battery: BatteryMetrics,
    /// Platform-specific metrics
    pub platform: PlatformMetrics,
}

/// Thermal metrics
#[derive(Debug, Clone)]
pub struct ThermalMetrics {
    /// Current temperature in Celsius
    pub temperature_c: f32,
    /// Thermal state
    pub thermal_state: ThermalState,
    /// Throttling level (0.0 = no throttling, 1.0 = maximum throttling)
    pub throttling_level: f32,
    /// Temperature trend
    pub temperature_trend: TemperatureTrend,
    /// Heat generation rate
    pub heat_generation_rate: f32,
    /// Cooling efficiency
    pub cooling_efficiency: f32,
}

/// Temperature trend analysis
#[derive(Debug, Clone)]
pub struct TemperatureTrend {
    /// Current temperature
    pub current: f32,
    /// Previous temperature
    pub previous: f32,
    /// Rate of change (°C/min)
    pub rate_of_change: f32,
    /// Trend direction
    pub direction: TrendDirection,
}

/// Temperature trend directions
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TrendDirection {
    /// Temperature increasing
    Rising,
    /// Temperature decreasing
    Falling,
    /// Temperature stable
    Stable,
}

/// Battery metrics
#[derive(Debug, Clone)]
pub struct BatteryMetrics {
    /// Battery level percentage
    pub level_percent: u8,
    /// Charging state
    pub is_charging: bool,
    /// Power consumption in milliwatts
    pub power_consumption_mw: f32,
    /// Estimated time remaining in minutes
    pub time_remaining_min: Option<u32>,
    /// Battery health percentage
    pub health_percent: u8,
    /// Battery temperature in Celsius
    pub temperature_c: f32,
    /// Voltage
    pub voltage_v: f32,
}

/// Platform-specific metrics
#[derive(Debug, Clone, Default)]
pub struct PlatformMetrics {
    /// iOS-specific metrics
    pub ios_metrics: Option<IosMetrics>,
    /// Android-specific metrics
    pub android_metrics: Option<AndroidMetrics>,
    /// Generic mobile metrics
    pub generic_metrics: GenericMobileMetrics,
}

/// iOS-specific metrics
#[derive(Debug, Clone)]
pub struct IosMetrics {
    /// Metal performance metrics
    pub metal_performance: MetalPerformanceMetrics,
    /// Core ML metrics
    pub coreml_metrics: CoreMLMetrics,
    /// iOS memory pressure
    pub memory_pressure: MemoryPressureLevel,
    /// Thermal pressure
    pub thermal_pressure: ThermalPressureLevel,
}

/// Android-specific metrics
#[derive(Debug, Clone)]
pub struct AndroidMetrics {
    /// Dalvik/ART metrics
    pub runtime_metrics: AndroidRuntimeMetrics,
    /// Android GPU metrics
    pub gpu_vendor_metrics: AndroidGpuMetrics,
    /// System service metrics
    pub system_services: AndroidSystemMetrics,
}

/// Generic mobile metrics
#[derive(Debug, Clone)]
pub struct GenericMobileMetrics {
    /// Screen brightness
    pub screen_brightness: f32,
    /// Device orientation
    pub orientation: DeviceOrientation,
    /// Network type
    pub network_type: NetworkType,
    /// Location services usage
    pub location_services_active: bool,
}

/// Metal performance metrics (iOS)
#[derive(Debug, Clone)]
pub struct MetalPerformanceMetrics {
    /// GPU utilization
    pub gpu_utilization: f32,
    /// Command buffer execution time
    pub command_buffer_time_ms: f32,
    /// Render encoder time
    pub render_encoder_time_ms: f32,
    /// Compute encoder time
    pub compute_encoder_time_ms: f32,
}

/// Core ML metrics (iOS)
#[derive(Debug, Clone)]
pub struct CoreMLMetrics {
    /// Model prediction time
    pub prediction_time_ms: f32,
    /// Model loading time
    pub model_load_time_ms: f32,
    /// Compute unit used
    pub compute_unit: CoreMLComputeUnit,
    /// Memory usage
    pub memory_usage_mb: f32,
}

/// Core ML compute units
#[derive(Debug, Clone, Copy)]
pub enum CoreMLComputeUnit {
    /// CPU only
    CPUOnly,
    /// CPU and GPU
    CPUAndGPU,
    /// CPU and Neural Engine
    CPUAndNeuralEngine,
    /// All compute units
    All,
}

/// Memory pressure levels (iOS)
#[derive(Debug, Clone, Copy)]
pub enum MemoryPressureLevel {
    /// Normal memory usage
    Normal,
    /// Warning level
    Warning,
    /// Urgent level
    Urgent,
    /// Critical level
    Critical,
}

/// Thermal pressure levels (iOS)
#[derive(Debug, Clone, Copy)]
pub enum ThermalPressureLevel {
    /// Nominal thermal state
    Nominal,
    /// Fair thermal state
    Fair,
    /// Serious thermal state
    Serious,
    /// Critical thermal state
    Critical,
}

/// Android runtime metrics
#[derive(Debug, Clone)]
pub struct AndroidRuntimeMetrics {
    /// Garbage collection count
    pub gc_count: u32,
    /// Garbage collection time
    pub gc_time_ms: f32,
    /// Heap utilization
    pub heap_utilization: f32,
    /// Method compilation time
    pub compilation_time_ms: f32,
}

/// Android GPU metrics
#[derive(Debug, Clone)]
pub struct AndroidGpuMetrics {
    /// GPU frequency
    pub frequency_mhz: u32,
    /// GPU busy percentage
    pub busy_percent: f32,
    /// GPU memory usage
    pub memory_usage_mb: f32,
    /// GPU power consumption
    pub power_mw: f32,
}

/// Android system metrics
#[derive(Debug, Clone)]
pub struct AndroidSystemMetrics {
    /// System server CPU usage
    pub system_server_cpu: f32,
    /// Window manager CPU usage
    pub window_manager_cpu: f32,
    /// Surface flinger CPU usage
    pub surface_flinger_cpu: f32,
    /// Media server CPU usage
    pub media_server_cpu: f32,
}

/// Device orientation
#[derive(Debug, Clone, Copy)]
pub enum DeviceOrientation {
    /// Portrait
    Portrait,
    /// Landscape left
    LandscapeLeft,
    /// Landscape right
    LandscapeRight,
    /// Portrait upside down
    PortraitUpsideDown,
    /// Face up
    FaceUp,
    /// Face down
    FaceDown,
}

/// Network type
#[derive(Debug, Clone, Copy)]
pub enum NetworkType {
    /// WiFi connection
    WiFi,
    /// Cellular connection
    Cellular,
    /// Ethernet connection
    Ethernet,
    /// No connection
    None,
    /// Unknown connection type
    Unknown,
}

impl MobileMetricsCollector {
    /// Create new metrics collector
    pub fn new(config: MobileProfilerConfig) -> Result<Self> {
        Ok(Self {
            config,
            current_metrics: MobileMetricsSnapshot::default(),
            metrics_history: VecDeque::new(),
            sampling_timer: None,
            collection_start: None,
            total_samples: 0,
        })
    }

    /// Start metrics collection
    pub fn start_collection(&mut self) -> Result<()> {
        self.sampling_timer = Some(Instant::now());
        self.collection_start = Some(Instant::now());
        self.collect_metrics()?;
        Ok(())
    }

    /// Stop metrics collection
    pub fn stop_collection(&mut self) -> Result<()> {
        self.sampling_timer = None;
        Ok(())
    }

    /// Get current metrics snapshot
    pub fn get_current_snapshot(&self) -> Result<MobileMetricsSnapshot> {
        Ok(self.current_metrics.clone())
    }

    /// Get all historical snapshots
    pub fn get_all_snapshots(&self) -> Vec<MobileMetricsSnapshot> {
        self.metrics_history.iter().cloned().collect()
    }

    /// Get collection statistics
    pub fn get_collection_stats(&self) -> CollectionStatistics {
        let duration = self.collection_start.map(|start| start.elapsed()).unwrap_or_default();

        CollectionStatistics {
            total_samples: self.total_samples,
            collection_duration: duration,
            average_sampling_rate: if duration.as_secs() > 0 {
                self.total_samples as f64 / duration.as_secs() as f64
            } else {
                0.0
            },
            history_size: self.metrics_history.len(),
            current_memory_usage_mb: self.estimate_memory_usage(),
        }
    }

    /// Force metrics collection
    pub fn collect_metrics(&mut self) -> Result<()> {
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_err(|e| TrustformersError::other(format!("Time error: {}", e)))?
            .as_millis() as u64;

        let memory = self.collect_memory_metrics()?;
        let cpu = self.collect_cpu_metrics()?;
        let gpu = self.collect_gpu_metrics()?;
        let network = self.collect_network_metrics()?;
        let inference = self.collect_inference_metrics()?;
        let thermal = self.collect_thermal_metrics()?;
        let battery = self.collect_battery_metrics()?;
        let platform = self.collect_platform_metrics()?;

        let snapshot = MobileMetricsSnapshot {
            timestamp,
            memory,
            cpu,
            gpu,
            network,
            inference,
            thermal,
            battery,
            platform,
        };

        self.current_metrics = snapshot.clone();
        self.metrics_history.push_back(snapshot);
        self.total_samples += 1;

        // Maintain history size limit
        if self.metrics_history.len() > self.config.sampling.max_samples {
            self.metrics_history.pop_front();
        }

        Ok(())
    }

    /// Collect memory metrics
    fn collect_memory_metrics(&self) -> Result<MemoryMetrics> {
        #[cfg(target_os = "ios")]
        {
            self.collect_ios_memory_metrics()
        }
        #[cfg(target_os = "android")]
        {
            self.collect_android_memory_metrics()
        }
        #[cfg(not(any(target_os = "ios", target_os = "android")))]
        {
            Ok(MemoryMetrics::default())
        }
    }

    #[cfg(target_os = "ios")]
    fn collect_ios_memory_metrics(&self) -> Result<MemoryMetrics> {
        // iOS-specific memory collection using mach system calls
        // This is a simplified implementation
        Ok(MemoryMetrics {
            heap_used_mb: 128.0,
            heap_free_mb: 256.0,
            heap_total_mb: 384.0,
            native_used_mb: 64.0,
            graphics_used_mb: 32.0,
            code_used_mb: 16.0,
            stack_used_mb: 8.0,
            other_used_mb: 24.0,
            available_mb: 1024.0,
        })
    }

    #[cfg(target_os = "android")]
    fn collect_android_memory_metrics(&self) -> Result<MemoryMetrics> {
        // Android-specific memory collection using ActivityManager
        Ok(MemoryMetrics {
            heap_used_mb: 96.0,
            heap_free_mb: 128.0,
            heap_total_mb: 224.0,
            native_used_mb: 48.0,
            graphics_used_mb: 64.0,
            code_used_mb: 12.0,
            stack_used_mb: 4.0,
            other_used_mb: 16.0,
            available_mb: 512.0,
        })
    }

    /// Collect CPU metrics
    fn collect_cpu_metrics(&self) -> Result<CpuMetrics> {
        #[cfg(target_os = "ios")]
        {
            self.collect_ios_cpu_metrics()
        }
        #[cfg(target_os = "android")]
        {
            self.collect_android_cpu_metrics()
        }
        #[cfg(not(any(target_os = "ios", target_os = "android")))]
        {
            Ok(CpuMetrics::default())
        }
    }

    #[cfg(target_os = "ios")]
    fn collect_ios_cpu_metrics(&self) -> Result<CpuMetrics> {
        // iOS-specific CPU metrics using host_processor_info
        Ok(CpuMetrics {
            usage_percent: 30.0,
            user_percent: 20.0,
            system_percent: 10.0,
            idle_percent: 70.0,
            frequency_mhz: 3200,
            temperature_c: 38.0,
            throttling_level: 0.1,
        })
    }

    #[cfg(target_os = "android")]
    fn collect_android_cpu_metrics(&self) -> Result<CpuMetrics> {
        // Android-specific CPU metrics from /proc/stat
        Ok(CpuMetrics {
            usage_percent: 35.0,
            user_percent: 25.0,
            system_percent: 10.0,
            idle_percent: 65.0,
            frequency_mhz: 2800,
            temperature_c: 40.0,
            throttling_level: 0.15,
        })
    }

    /// Collect GPU metrics
    fn collect_gpu_metrics(&self) -> Result<GpuMetrics> {
        Ok(GpuMetrics::default()) // Simplified implementation
    }

    /// Collect network metrics
    fn collect_network_metrics(&self) -> Result<NetworkMetrics> {
        Ok(NetworkMetrics::default()) // Simplified implementation
    }

    /// Collect inference metrics
    fn collect_inference_metrics(&self) -> Result<InferenceMetrics> {
        Ok(InferenceMetrics::default()) // Simplified implementation
    }

    /// Collect thermal metrics
    fn collect_thermal_metrics(&self) -> Result<ThermalMetrics> {
        Ok(ThermalMetrics::default()) // Simplified implementation
    }

    /// Collect battery metrics
    fn collect_battery_metrics(&self) -> Result<BatteryMetrics> {
        Ok(BatteryMetrics::default()) // Simplified implementation
    }

    /// Collect platform-specific metrics
    fn collect_platform_metrics(&self) -> Result<PlatformMetrics> {
        Ok(PlatformMetrics::default()) // Simplified implementation
    }

    /// Estimate current memory usage of the collector
    fn estimate_memory_usage(&self) -> f32 {
        let snapshot_size = std::mem::size_of::<MobileMetricsSnapshot>();
        let total_size = snapshot_size * self.metrics_history.len();
        total_size as f32 / (1024.0 * 1024.0) // Convert to MB
    }
}

/// Collection statistics
#[derive(Debug, Clone)]
pub struct CollectionStatistics {
    /// Total samples collected
    pub total_samples: u64,
    /// Total collection duration
    pub collection_duration: Duration,
    /// Average sampling rate (samples/second)
    pub average_sampling_rate: f64,
    /// Current history size
    pub history_size: usize,
    /// Estimated memory usage in MB
    pub current_memory_usage_mb: f32,
}

/// Default implementations
impl Default for MobileMetricsSnapshot {
    fn default() -> Self {
        Self {
            timestamp: 0,
            memory: MemoryMetrics::default(),
            cpu: CpuMetrics::default(),
            gpu: GpuMetrics::default(),
            network: NetworkMetrics::default(),
            inference: InferenceMetrics::default(),
            thermal: ThermalMetrics::default(),
            battery: BatteryMetrics::default(),
            platform: PlatformMetrics::default(),
        }
    }
}

impl Default for ThermalMetrics {
    fn default() -> Self {
        Self {
            temperature_c: 25.0,
            thermal_state: ThermalState::Nominal,
            throttling_level: 0.0,
            temperature_trend: TemperatureTrend::default(),
            heat_generation_rate: 0.0,
            cooling_efficiency: 1.0,
        }
    }
}

impl Default for TemperatureTrend {
    fn default() -> Self {
        Self {
            current: 25.0,
            previous: 25.0,
            rate_of_change: 0.0,
            direction: TrendDirection::Stable,
        }
    }
}

impl Default for BatteryMetrics {
    fn default() -> Self {
        Self {
            level_percent: 100,
            is_charging: false,
            power_consumption_mw: 0.0,
            time_remaining_min: None,
            health_percent: 100,
            temperature_c: 25.0,
            voltage_v: 3.7,
        }
    }
}

impl Default for GenericMobileMetrics {
    fn default() -> Self {
        Self {
            screen_brightness: 0.5,
            orientation: DeviceOrientation::Portrait,
            network_type: NetworkType::WiFi,
            location_services_active: false,
        }
    }
}

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

    fn lcg_f32(state: &mut u64) -> f32 {
        *state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
        (*state % 1000) as f32 / 1000.0
    }

    #[test]
    fn test_mobile_metrics_collector_new() {
        let config = MobileProfilerConfig::default();
        let collector = MobileMetricsCollector::new(config);
        assert!(collector.is_ok());
    }

    #[test]
    fn test_mobile_metrics_collector_initial_total_samples() {
        let config = MobileProfilerConfig::default();
        let collector = MobileMetricsCollector::new(config)
            .unwrap_or_else(|_| panic!("collector creation failed"));
        let stats = collector.get_collection_stats();
        assert_eq!(stats.total_samples, 0);
    }

    #[test]
    fn test_mobile_metrics_collector_initial_history_empty() {
        let config = MobileProfilerConfig::default();
        let collector = MobileMetricsCollector::new(config)
            .unwrap_or_else(|_| panic!("collector creation failed"));
        let snapshots = collector.get_all_snapshots();
        assert!(snapshots.is_empty());
    }

    #[test]
    fn test_collect_metrics_increments_samples() {
        let config = MobileProfilerConfig::default();
        let mut collector = MobileMetricsCollector::new(config)
            .unwrap_or_else(|_| panic!("collector creation failed"));
        let result = collector.collect_metrics();
        assert!(result.is_ok());
        let stats = collector.get_collection_stats();
        assert_eq!(stats.total_samples, 1);
    }

    #[test]
    fn test_collect_metrics_multiple_accumulates() {
        let config = MobileProfilerConfig::default();
        let mut collector = MobileMetricsCollector::new(config)
            .unwrap_or_else(|_| panic!("collector creation failed"));
        for _ in 0..5 {
            let _ = collector.collect_metrics();
        }
        let stats = collector.get_collection_stats();
        assert_eq!(stats.total_samples, 5);
    }

    #[test]
    fn test_get_current_snapshot_ok() {
        let config = MobileProfilerConfig::default();
        let mut collector = MobileMetricsCollector::new(config)
            .unwrap_or_else(|_| panic!("collector creation failed"));
        let _ = collector.collect_metrics();
        let snapshot = collector.get_current_snapshot();
        assert!(snapshot.is_ok());
    }

    #[test]
    fn test_stop_collection_ok() {
        let config = MobileProfilerConfig::default();
        let mut collector = MobileMetricsCollector::new(config)
            .unwrap_or_else(|_| panic!("collector creation failed"));
        let result = collector.stop_collection();
        assert!(result.is_ok());
    }

    #[test]
    fn test_collection_statistics_fields() {
        let config = MobileProfilerConfig::default();
        let mut collector = MobileMetricsCollector::new(config)
            .unwrap_or_else(|_| panic!("collector creation failed"));
        let _ = collector.collect_metrics();
        let stats = collector.get_collection_stats();
        assert_eq!(stats.history_size, 1);
        assert!(stats.current_memory_usage_mb >= 0.0);
    }

    #[test]
    fn test_thermal_metrics_default() {
        let thermal = ThermalMetrics::default();
        assert_eq!(thermal.temperature_c, 25.0);
        assert_eq!(thermal.throttling_level, 0.0);
        assert_eq!(thermal.cooling_efficiency, 1.0);
    }

    #[test]
    fn test_temperature_trend_default() {
        let trend = TemperatureTrend::default();
        assert_eq!(trend.current, 25.0);
        assert_eq!(trend.previous, 25.0);
        assert_eq!(trend.rate_of_change, 0.0);
        assert!(matches!(trend.direction, TrendDirection::Stable));
    }

    #[test]
    fn test_trend_direction_variants() {
        let rising = TrendDirection::Rising;
        let falling = TrendDirection::Falling;
        let stable = TrendDirection::Stable;
        assert_eq!(rising, TrendDirection::Rising);
        assert_eq!(falling, TrendDirection::Falling);
        assert_eq!(stable, TrendDirection::Stable);
    }

    #[test]
    fn test_battery_metrics_default() {
        let battery = BatteryMetrics::default();
        assert_eq!(battery.level_percent, 100);
        assert!(!battery.is_charging);
        assert_eq!(battery.power_consumption_mw, 0.0);
        assert!(battery.time_remaining_min.is_none());
        assert_eq!(battery.health_percent, 100);
        assert_eq!(battery.voltage_v, 3.7);
    }

    #[test]
    fn test_battery_metrics_construction() {
        let mut s = 42u64;
        let battery = BatteryMetrics {
            level_percent: 75,
            is_charging: true,
            power_consumption_mw: lcg_f32(&mut s) * 5000.0,
            time_remaining_min: Some(120),
            health_percent: 95,
            temperature_c: 30.0,
            voltage_v: 3.8,
        };
        assert_eq!(battery.level_percent, 75);
        assert!(battery.is_charging);
        assert_eq!(battery.time_remaining_min, Some(120));
    }

    #[test]
    fn test_platform_metrics_default() {
        let platform = PlatformMetrics::default();
        assert!(platform.ios_metrics.is_none());
        assert!(platform.android_metrics.is_none());
    }

    #[test]
    fn test_generic_mobile_metrics_default() {
        let generic = GenericMobileMetrics::default();
        assert_eq!(generic.screen_brightness, 0.5);
        assert!(!generic.location_services_active);
        assert!(matches!(generic.orientation, DeviceOrientation::Portrait));
        assert!(matches!(generic.network_type, NetworkType::WiFi));
    }

    #[test]
    fn test_device_orientation_variants() {
        let _portrait = DeviceOrientation::Portrait;
        let _ll = DeviceOrientation::LandscapeLeft;
        let _lr = DeviceOrientation::LandscapeRight;
        let _upside = DeviceOrientation::PortraitUpsideDown;
        let _face_up = DeviceOrientation::FaceUp;
        let _face_down = DeviceOrientation::FaceDown;
    }

    #[test]
    fn test_network_type_variants() {
        let _wifi = NetworkType::WiFi;
        let _cell = NetworkType::Cellular;
        let _eth = NetworkType::Ethernet;
        let _none = NetworkType::None;
        let _unk = NetworkType::Unknown;
    }

    #[test]
    fn test_memory_pressure_level_variants() {
        let _normal = MemoryPressureLevel::Normal;
        let _warning = MemoryPressureLevel::Warning;
        let _urgent = MemoryPressureLevel::Urgent;
        let _critical = MemoryPressureLevel::Critical;
    }

    #[test]
    fn test_thermal_pressure_level_variants() {
        let _nominal = ThermalPressureLevel::Nominal;
        let _fair = ThermalPressureLevel::Fair;
        let _serious = ThermalPressureLevel::Serious;
        let _critical = ThermalPressureLevel::Critical;
    }

    #[test]
    fn test_coreml_compute_unit_variants() {
        let _cpu_only = CoreMLComputeUnit::CPUOnly;
        let _cpu_gpu = CoreMLComputeUnit::CPUAndGPU;
        let _cpu_ne = CoreMLComputeUnit::CPUAndNeuralEngine;
        let _all = CoreMLComputeUnit::All;
    }

    #[test]
    fn test_mobile_metrics_snapshot_default_timestamp_zero() {
        let snapshot = MobileMetricsSnapshot::default();
        assert_eq!(snapshot.timestamp, 0);
    }

    #[test]
    fn test_history_size_limited_by_config() {
        let mut config = MobileProfilerConfig::default();
        config.sampling.max_samples = 3;
        let mut collector = MobileMetricsCollector::new(config)
            .unwrap_or_else(|_| panic!("collector creation failed"));
        for _ in 0..10 {
            let _ = collector.collect_metrics();
        }
        let stats = collector.get_collection_stats();
        assert!(stats.history_size <= 3);
        // total_samples keeps counting even when history is bounded
        assert_eq!(stats.total_samples, 10);
    }

    #[test]
    fn test_thermal_metrics_construction_with_lcg() {
        let mut s = 99u64;
        let thermal = ThermalMetrics {
            temperature_c: lcg_f32(&mut s) * 80.0,
            thermal_state: crate::device_info::ThermalState::Nominal,
            throttling_level: lcg_f32(&mut s),
            temperature_trend: TemperatureTrend::default(),
            heat_generation_rate: lcg_f32(&mut s) * 10.0,
            cooling_efficiency: lcg_f32(&mut s),
        };
        assert!(thermal.temperature_c >= 0.0);
        assert!(thermal.throttling_level >= 0.0 && thermal.throttling_level <= 1.0);
    }

    #[test]
    fn test_android_runtime_metrics_fields() {
        let runtime = AndroidRuntimeMetrics {
            gc_count: 5,
            gc_time_ms: 12.3,
            heap_utilization: 0.7,
            compilation_time_ms: 45.0,
        };
        assert_eq!(runtime.gc_count, 5);
        assert_eq!(runtime.gc_time_ms, 12.3);
    }

    #[test]
    fn test_android_gpu_metrics_fields() {
        let gpu = AndroidGpuMetrics {
            frequency_mhz: 800,
            busy_percent: 45.0,
            memory_usage_mb: 128.0,
            power_mw: 500.0,
        };
        assert_eq!(gpu.frequency_mhz, 800);
        assert_eq!(gpu.busy_percent, 45.0);
    }
}