1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
mod autotest_generated {
5
    use super::*;
6

            
7
    const ALL_FACINGS: [CameraFacing; 3] = [
8
        CameraFacing::Front,
9
        CameraFacing::Back,
10
        CameraFacing::External,
11
    ];
12

            
13
    // ---- CameraConfig::new — constructor: no_panic + invariants_hold ----
14

            
15
    #[test]
16
    fn new_does_not_panic_for_any_facing() {
17
        // Constructor over every representative argument must not panic.
18
        for &facing in &ALL_FACINGS {
19
            let _ = CameraConfig::new(facing);
20
        }
21
    }
22

            
23
    #[test]
24
    fn new_sets_facing_and_leaves_everything_else_at_default() {
25
        // Documented contract: default config for the given `facing`
26
        // (backend-chosen size/fps, BGRA8). So new(f) must differ from
27
        // Default only in `facing`.
28
        let def = CameraConfig::default();
29
        for &facing in &ALL_FACINGS {
30
            let cfg = CameraConfig::new(facing);
31
            assert_eq!(cfg.facing, facing, "facing must equal the argument");
32
            assert_eq!(cfg.width, def.width);
33
            assert_eq!(cfg.height, def.height);
34
            assert_eq!(cfg.fps, def.fps);
35
            assert_eq!(cfg.output_format, def.output_format);
36
            // Absolute invariants (not just "== default"):
37
            assert_eq!(cfg.width, 0, "0 => backend default width");
38
            assert_eq!(cfg.height, 0, "0 => backend default height");
39
            assert_eq!(cfg.fps, 0, "0 => backend default fps");
40
            assert_eq!(cfg.output_format, RawImageFormat::BGRA8);
41
        }
42
    }
43

            
44
    #[test]
45
    fn new_equals_struct_update_syntax() {
46
        // new(f) must be observably identical to `{ facing: f, ..default() }`.
47
        for &facing in &ALL_FACINGS {
48
            let via_new = CameraConfig::new(facing);
49
            let via_update = CameraConfig {
50
                facing,
51
                ..CameraConfig::default()
52
            };
53
            assert_eq!(via_new, via_update);
54
        }
55
    }
56

            
57
    #[test]
58
    fn new_back_equals_full_default() {
59
        // Default facing is Back, so new(Back) must equal Default entirely.
60
        assert_eq!(
61
            CameraConfig::new(CameraFacing::Back),
62
            CameraConfig::default()
63
        );
64
    }
65

            
66
    #[test]
67
    fn new_result_is_copy_and_independent() {
68
        // CameraConfig is Copy; mutating a copy must not touch the original.
69
        let a = CameraConfig::new(CameraFacing::Front);
70
        let mut b = a;
71
        b.width = 1920;
72
        b.facing = CameraFacing::Back;
73
        assert_eq!(a.width, 0, "original must be untouched by copy mutation");
74
        assert_eq!(a.facing, CameraFacing::Front);
75
        assert_eq!(b.width, 1920);
76
        assert_eq!(b.facing, CameraFacing::Back);
77
    }
78

            
79
    #[test]
80
    fn new_differs_only_by_facing_between_variants() {
81
        // Two configs built from different facings must be unequal, and equal
82
        // once their facings are aligned (proves facing is the only variance).
83
        let front = CameraConfig::new(CameraFacing::Front);
84
        let mut back = CameraConfig::new(CameraFacing::Back);
85
        assert_ne!(front, back);
86
        back.facing = CameraFacing::Front;
87
        assert_eq!(front, back);
88
    }
89

            
90
    // ---- CameraConfig field storage: no clamping / no overflow on extremes ----
91

            
92
    #[test]
93
    fn camera_config_stores_extreme_dimensions_verbatim() {
94
        // These are POD "requested" values; the type must not clamp/saturate.
95
        let cfg = CameraConfig {
96
            width: u32::MAX,
97
            height: u32::MAX,
98
            fps: u32::MAX,
99
            ..CameraConfig::new(CameraFacing::External)
100
        };
101
        assert_eq!(cfg.width, u32::MAX);
102
        assert_eq!(cfg.height, u32::MAX);
103
        assert_eq!(cfg.fps, u32::MAX);
104
        assert_eq!(cfg.facing, CameraFacing::External);
105
    }
106

            
107
    #[test]
108
    fn camera_config_output_format_can_hold_non_default() {
109
        // new() forces BGRA8, but the struct must faithfully hold any format.
110
        let cfg = CameraConfig {
111
            output_format: RawImageFormat::RGBA8,
112
            ..CameraConfig::new(CameraFacing::Front)
113
        };
114
        assert_eq!(cfg.output_format, RawImageFormat::RGBA8);
115
        assert_ne!(cfg.output_format, RawImageFormat::BGRA8);
116
    }
117

            
118
    // ---- Default invariants ----
119

            
120
    #[test]
121
    fn camera_config_default_is_back_bgra8_zeroed() {
122
        let d = CameraConfig::default();
123
        assert_eq!(d.facing, CameraFacing::Back);
124
        assert_eq!(d.width, 0);
125
        assert_eq!(d.height, 0);
126
        assert_eq!(d.fps, 0);
127
        assert_eq!(d.output_format, RawImageFormat::BGRA8);
128
    }
129

            
130
    #[test]
131
    fn camera_config_default_is_idempotent() {
132
        assert_eq!(CameraConfig::default(), CameraConfig::default());
133
    }
134

            
135
    #[test]
136
    fn capture_stats_default_is_fully_zeroed() {
137
        let s = CaptureStats::default();
138
        assert_eq!(s.measured_fps, 0.0);
139
        assert_eq!(s.frames_delivered, 0);
140
        assert_eq!(s.frames_dropped, 0);
141
    }
142

            
143
    // ---- CaptureStats numeric / NaN adversarial (PartialEq over f32, NOT Eq) ----
144

            
145
    #[test]
146
    fn capture_stats_nan_fps_breaks_eq_reflexivity() {
147
        // measured_fps is f32; NaN != NaN, so a stats value carrying NaN must
148
        // not compare equal to itself. This confirms CaptureStats is (correctly)
149
        // PartialEq and not Eq.
150
        let s = CaptureStats {
151
            measured_fps: f32::NAN,
152
            ..CaptureStats::default()
153
        };
154
        assert_ne!(s, s, "NaN measured_fps must break PartialEq reflexivity");
155
        assert!(s.measured_fps.is_nan());
156
    }
157

            
158
    #[test]
159
    fn capture_stats_holds_infinities_and_saturated_counters() {
160
        let s = CaptureStats {
161
            measured_fps: f32::INFINITY,
162
            frames_delivered: u64::MAX,
163
            frames_dropped: u64::MAX,
164
        };
165
        assert!(s.measured_fps.is_infinite() && s.measured_fps > 0.0);
166
        assert_eq!(s.frames_delivered, u64::MAX);
167
        assert_eq!(s.frames_dropped, u64::MAX);
168

            
169
        let neg = CaptureStats {
170
            measured_fps: f32::NEG_INFINITY,
171
            ..CaptureStats::default()
172
        };
173
        assert!(neg.measured_fps.is_infinite() && neg.measured_fps < 0.0);
174
    }
175

            
176
    #[test]
177
    fn capture_stats_negative_zero_fps_equals_zero() {
178
        // IEEE: -0.0 == 0.0 for PartialEq; assert the type doesn't surprise us.
179
        let s = CaptureStats {
180
            measured_fps: -0.0,
181
            ..CaptureStats::default()
182
        };
183
        assert_eq!(s, CaptureStats::default());
184
    }
185

            
186
    // ---- CaptureStreamId round-trips its id over boundary values ----
187

            
188
    #[test]
189
    fn capture_stream_id_roundtrips_boundary_ids() {
190
        for id in [0u64, 1, 2, u64::MAX / 2, u64::MAX - 1, u64::MAX] {
191
            let s = CaptureStreamId { id };
192
            assert_eq!(s.id, id);
193
            assert_eq!(s, CaptureStreamId { id }, "Eq must hold for equal ids");
194
        }
195
    }
196

            
197
    #[test]
198
    fn capture_stream_id_distinct_ids_are_unequal_and_ordered() {
199
        let lo = CaptureStreamId { id: 0 };
200
        let hi = CaptureStreamId { id: u64::MAX };
201
        assert_ne!(lo, hi);
202
        assert!(lo < hi, "Ord must follow the inner u64");
203
    }
204

            
205
    // ---- Enum ordering / total-order / hash-eq contract (derived, but assert it) ----
206

            
207
    #[test]
208
    fn enum_ord_matches_declaration_order() {
209
        // CameraFacing: Front < Back < External.
210
        assert!(CameraFacing::Front < CameraFacing::Back);
211
        assert!(CameraFacing::Back < CameraFacing::External);
212
        // StreamState: Starting < Running < Paused < Stopped < Error.
213
        assert!(StreamState::Starting < StreamState::Running);
214
        assert!(StreamState::Running < StreamState::Paused);
215
        assert!(StreamState::Paused < StreamState::Stopped);
216
        assert!(StreamState::Stopped < StreamState::Error);
217
        // CaptureOrientation: Up < Down < Left < Right < Mirror.
218
        assert!(CaptureOrientation::Up < CaptureOrientation::Down);
219
        assert!(CaptureOrientation::Down < CaptureOrientation::Left);
220
        assert!(CaptureOrientation::Left < CaptureOrientation::Right);
221
        assert!(CaptureOrientation::Right < CaptureOrientation::Mirror);
222
        // CaptureErrorCode: PermissionDenied < DeviceUnavailable < DeviceLost
223
        //                   < Unsupported < Internal.
224
        assert!(CaptureErrorCode::PermissionDenied < CaptureErrorCode::DeviceUnavailable);
225
        assert!(CaptureErrorCode::DeviceUnavailable < CaptureErrorCode::DeviceLost);
226
        assert!(CaptureErrorCode::DeviceLost < CaptureErrorCode::Unsupported);
227
        assert!(CaptureErrorCode::Unsupported < CaptureErrorCode::Internal);
228
    }
229

            
230
    #[test]
231
    fn camera_facing_ord_is_total_and_antisymmetric() {
232
        use core::cmp::Ordering;
233
        for &a in &ALL_FACINGS {
234
            assert_eq!(a.cmp(&a), Ordering::Equal, "reflexive equality");
235
            for &b in &ALL_FACINGS {
236
                // Exactly one of <, ==, > holds (trichotomy / total order).
237
                let lt = (a < b) as u8;
238
                let eq = (a == b) as u8;
239
                let gt = (a > b) as u8;
240
                assert_eq!(lt + eq + gt, 1, "trichotomy must hold for ({a:?},{b:?})");
241
                // Antisymmetry: a < b implies !(b < a).
242
                if a < b {
243
                    assert!((b >= a), "antisymmetry violated for ({a:?},{b:?})");
244
                }
245
            }
246
        }
247
    }
248

            
249
    #[test]
250
    fn enum_hash_eq_consistency() {
251
        use std::collections::HashSet;
252
        let mut set = HashSet::new();
253
        assert!(set.insert(CameraFacing::Front));
254
        assert!(set.insert(CameraFacing::Back));
255
        assert!(set.insert(CameraFacing::External));
256
        // Re-inserting an equal value must be rejected (Hash agrees with Eq).
257
        assert!(!set.insert(CameraFacing::Front));
258
        assert_eq!(set.len(), 3);
259
        assert!(set.contains(&CameraFacing::Back));
260
    }
261

            
262
    // =====================================================================
263
    // Appended adversarial tests.
264
    //
265
    // NOTE: the module docs mention an `Nv12` output format, but it is an
266
    // explicitly deferred `RawImageFormat` addition and does not exist yet -
267
    // it is therefore un-constructible and deliberately NOT tested here.
268
    // =====================================================================
269

            
270
    const ALL_STATES: [StreamState; 5] = [
271
        StreamState::Starting,
272
        StreamState::Running,
273
        StreamState::Paused,
274
        StreamState::Stopped,
275
        StreamState::Error,
276
    ];
277

            
278
    const ALL_ORIENTATIONS: [CaptureOrientation; 5] = [
279
        CaptureOrientation::Up,
280
        CaptureOrientation::Down,
281
        CaptureOrientation::Left,
282
        CaptureOrientation::Right,
283
        CaptureOrientation::Mirror,
284
    ];
285

            
286
    const ALL_ERRORS: [CaptureErrorCode; 5] = [
287
        CaptureErrorCode::PermissionDenied,
288
        CaptureErrorCode::DeviceUnavailable,
289
        CaptureErrorCode::DeviceLost,
290
        CaptureErrorCode::Unsupported,
291
        CaptureErrorCode::Internal,
292
    ];
293

            
294
    /// Every `RawImageFormat` a `CameraConfig` could carry. `Nv12` is absent
295
    /// on purpose (see the note above).
296
    const ALL_FORMATS: [RawImageFormat; 12] = [
297
        RawImageFormat::R8,
298
        RawImageFormat::RG8,
299
        RawImageFormat::RGB8,
300
        RawImageFormat::RGBA8,
301
        RawImageFormat::R16,
302
        RawImageFormat::RG16,
303
        RawImageFormat::RGB16,
304
        RawImageFormat::RGBA16,
305
        RawImageFormat::BGR8,
306
        RawImageFormat::BGRA8,
307
        RawImageFormat::RGBF32,
308
        RawImageFormat::RGBAF32,
309
    ];
310

            
311
    // ---- Round-trip: enum -> FFI discriminant -> enum (encode == decode) ----
312
    //
313
    // These are `#[repr(C)]` fieldless enums that cross the FFI boundary, so
314
    // their discriminants ARE the wire format. A reordered / inserted variant
315
    // silently re-numbers the C ABI; these round-trips pin it down. The
316
    // `match` arms are exhaustive, so adding a variant fails to compile rather
317
    // than silently shipping an untested value.
318

            
319
    fn facing_from_discriminant(i: i32) -> Option<CameraFacing> {
320
        match i {
321
            0 => Some(CameraFacing::Front),
322
            1 => Some(CameraFacing::Back),
323
            2 => Some(CameraFacing::External),
324
            _ => None,
325
        }
326
    }
327

            
328
    fn state_from_discriminant(i: i32) -> Option<StreamState> {
329
        match i {
330
            0 => Some(StreamState::Starting),
331
            1 => Some(StreamState::Running),
332
            2 => Some(StreamState::Paused),
333
            3 => Some(StreamState::Stopped),
334
            4 => Some(StreamState::Error),
335
            _ => None,
336
        }
337
    }
338

            
339
    fn orientation_from_discriminant(i: i32) -> Option<CaptureOrientation> {
340
        match i {
341
            0 => Some(CaptureOrientation::Up),
342
            1 => Some(CaptureOrientation::Down),
343
            2 => Some(CaptureOrientation::Left),
344
            3 => Some(CaptureOrientation::Right),
345
            4 => Some(CaptureOrientation::Mirror),
346
            _ => None,
347
        }
348
    }
349

            
350
    fn error_from_discriminant(i: i32) -> Option<CaptureErrorCode> {
351
        match i {
352
            0 => Some(CaptureErrorCode::PermissionDenied),
353
            1 => Some(CaptureErrorCode::DeviceUnavailable),
354
            2 => Some(CaptureErrorCode::DeviceLost),
355
            3 => Some(CaptureErrorCode::Unsupported),
356
            4 => Some(CaptureErrorCode::Internal),
357
            _ => None,
358
        }
359
    }
360

            
361
    #[test]
362
    fn enum_discriminants_are_the_pinned_ffi_wire_values() {
363
        // If this fails, the C ABI changed: every C/Python/Kotlin caller that
364
        // passed an integer facing/state/orientation/error is now wrong.
365
        assert_eq!(CameraFacing::Front as i32, 0);
366
        assert_eq!(CameraFacing::Back as i32, 1);
367
        assert_eq!(CameraFacing::External as i32, 2);
368

            
369
        assert_eq!(StreamState::Starting as i32, 0);
370
        assert_eq!(StreamState::Running as i32, 1);
371
        assert_eq!(StreamState::Paused as i32, 2);
372
        assert_eq!(StreamState::Stopped as i32, 3);
373
        assert_eq!(StreamState::Error as i32, 4);
374

            
375
        assert_eq!(CaptureOrientation::Up as i32, 0);
376
        assert_eq!(CaptureOrientation::Down as i32, 1);
377
        assert_eq!(CaptureOrientation::Left as i32, 2);
378
        assert_eq!(CaptureOrientation::Right as i32, 3);
379
        assert_eq!(CaptureOrientation::Mirror as i32, 4);
380

            
381
        assert_eq!(CaptureErrorCode::PermissionDenied as i32, 0);
382
        assert_eq!(CaptureErrorCode::DeviceUnavailable as i32, 1);
383
        assert_eq!(CaptureErrorCode::DeviceLost as i32, 2);
384
        assert_eq!(CaptureErrorCode::Unsupported as i32, 3);
385
        assert_eq!(CaptureErrorCode::Internal as i32, 4);
386
    }
387

            
388
    #[test]
389
    fn enum_discriminant_roundtrip_is_identity() {
390
        for &f in &ALL_FACINGS {
391
            assert_eq!(facing_from_discriminant(f as i32), Some(f));
392
        }
393
        for &s in &ALL_STATES {
394
            assert_eq!(state_from_discriminant(s as i32), Some(s));
395
        }
396
        for &o in &ALL_ORIENTATIONS {
397
            assert_eq!(orientation_from_discriminant(o as i32), Some(o));
398
        }
399
        for &e in &ALL_ERRORS {
400
            assert_eq!(error_from_discriminant(e as i32), Some(e));
401
        }
402
    }
403

            
404
    #[test]
405
    fn enum_decode_rejects_out_of_range_discriminants() {
406
        // A hostile / buggy FFI caller can hand over ANY i32. Decoding must
407
        // yield None, never a bogus variant (and never wrap around).
408
        for bad in [-1i32, 3, 5, 99, i32::MIN, i32::MAX] {
409
            assert_eq!(facing_from_discriminant(bad), None, "facing {bad}");
410
        }
411
        for bad in [-1i32, 5, 6, 255, i32::MIN, i32::MAX] {
412
            assert_eq!(state_from_discriminant(bad), None, "state {bad}");
413
            assert_eq!(orientation_from_discriminant(bad), None, "orient {bad}");
414
            assert_eq!(error_from_discriminant(bad), None, "error {bad}");
415
        }
416
        // Boundary: the last valid value decodes, one past it does not.
417
        assert!(facing_from_discriminant(2).is_some());
418
        assert!(facing_from_discriminant(3).is_none());
419
        assert!(state_from_discriminant(4).is_some());
420
        assert!(state_from_discriminant(5).is_none());
421
    }
422

            
423
    #[test]
424
    fn enum_discriminant_order_agrees_with_ord() {
425
        // Ord is derived from declaration order, which is also the FFI
426
        // numbering; the two must not drift apart.
427
        for &a in &ALL_STATES {
428
            for &b in &ALL_STATES {
429
                assert_eq!(
430
                    a < b,
431
                    (a as i32) < (b as i32),
432
                    "Ord and discriminant disagree for ({a:?}, {b:?})"
433
                );
434
            }
435
        }
436
    }
437

            
438
    // ---- Round-trip: struct -> fields -> struct (decompose == recompose) ----
439

            
440
    #[test]
441
    fn camera_config_field_roundtrip_is_identity_over_full_cross_product() {
442
        // Every facing x every format, with adversarial extents: taking a
443
        // config apart and rebuilding it must reproduce it exactly.
444
        for &facing in &ALL_FACINGS {
445
            for &output_format in &ALL_FORMATS {
446
                for &(width, height, fps) in &[
447
                    (0u32, 0u32, 0u32),
448
                    (1, 1, 1),
449
                    (1920, 1080, 60),
450
                    (u32::MAX, u32::MAX, u32::MAX),
451
                    (u32::MAX, 0, 1),
452
                ] {
453
                    let cfg = CameraConfig {
454
                        facing,
455
                        width,
456
                        height,
457
                        fps,
458
                        output_format,
459
                    };
460
                    let rebuilt = CameraConfig {
461
                        facing: cfg.facing,
462
                        width: cfg.width,
463
                        height: cfg.height,
464
                        fps: cfg.fps,
465
                        output_format: cfg.output_format,
466
                    };
467
                    assert_eq!(cfg, rebuilt);
468
                    // ...and the fields survived verbatim - no clamping.
469
                    assert_eq!(rebuilt.width, width);
470
                    assert_eq!(rebuilt.height, height);
471
                    assert_eq!(rebuilt.fps, fps);
472
                    assert_eq!(rebuilt.facing, facing);
473
                    assert_eq!(rebuilt.output_format, output_format);
474
                }
475
            }
476
        }
477
    }
478

            
479
    #[test]
480
    fn camera_config_does_not_confuse_width_and_height() {
481
        // Guards against a transposed-field bug in any future manual PartialEq
482
        // or FFI struct layout: a config is NOT equal to its transpose.
483
        let a = CameraConfig {
484
            width: 1920,
485
            height: 1080,
486
            ..CameraConfig::default()
487
        };
488
        let transposed = CameraConfig {
489
            width: 1080,
490
            height: 1920,
491
            ..CameraConfig::default()
492
        };
493
        assert_ne!(a, transposed, "width/height must be distinguishable");
494
        // A square config IS its own transpose - sanity check on the above.
495
        let square = CameraConfig {
496
            width: 512,
497
            height: 512,
498
            ..CameraConfig::default()
499
        };
500
        let square2 = CameraConfig {
501
            width: 512,
502
            height: 512,
503
            ..CameraConfig::default()
504
        };
505
        assert_eq!(square, square2);
506
    }
507

            
508
    #[test]
509
    fn camera_config_eq_is_sensitive_to_every_field() {
510
        // Flipping any single field must break equality - i.e. no field is
511
        // accidentally excluded from the derived PartialEq.
512
        let base = CameraConfig::default();
513
        assert_ne!(
514
            base,
515
            CameraConfig {
516
                facing: CameraFacing::Front,
517
                ..base
518
            }
519
        );
520
        assert_ne!(base, CameraConfig { width: 1, ..base });
521
        assert_ne!(base, CameraConfig { height: 1, ..base });
522
        assert_ne!(base, CameraConfig { fps: 1, ..base });
523
        assert_ne!(
524
            base,
525
            CameraConfig {
526
                output_format: RawImageFormat::RGBA8,
527
                ..base
528
            }
529
        );
530
    }
531

            
532
    #[test]
533
    fn capture_stats_eq_is_sensitive_to_every_field() {
534
        let base = CaptureStats::default();
535
        assert_ne!(
536
            base,
537
            CaptureStats {
538
                measured_fps: 1.0,
539
                ..base
540
            }
541
        );
542
        assert_ne!(
543
            base,
544
            CaptureStats {
545
                frames_delivered: 1,
546
                ..base
547
            }
548
        );
549
        assert_ne!(
550
            base,
551
            CaptureStats {
552
                frames_dropped: 1,
553
                ..base
554
            }
555
        );
556
    }
557

            
558
    #[test]
559
    // These types are Copy; calling .clone() explicitly is the point of the
560
    // test (Clone must agree with Copy), so the lint is deliberately waived.
561
    #[allow(clippy::clone_on_copy)]
562
    fn clone_is_identity_for_all_pod_types_at_extremes() {
563
        let cfg = CameraConfig {
564
            facing: CameraFacing::External,
565
            width: u32::MAX,
566
            height: u32::MAX,
567
            fps: u32::MAX,
568
            output_format: RawImageFormat::RGBAF32,
569
        };
570
        assert_eq!(cfg.clone(), cfg);
571

            
572
        let id = CaptureStreamId { id: u64::MAX };
573
        assert_eq!(id.clone(), id);
574

            
575
        // NaN is excluded here on purpose: clone of NaN cannot compare equal
576
        // (see capture_stats_nan_fps_breaks_eq_reflexivity); assert bit
577
        // equality instead, which IS reflexive.
578
        let nan_stats = CaptureStats {
579
            measured_fps: f32::NAN,
580
            frames_delivered: u64::MAX,
581
            frames_dropped: u64::MAX,
582
        };
583
        let cloned = nan_stats.clone();
584
        assert_eq!(
585
            cloned.measured_fps.to_bits(),
586
            nan_stats.measured_fps.to_bits(),
587
            "clone must preserve the exact NaN bit pattern"
588
        );
589
        assert_eq!(cloned.frames_delivered, u64::MAX);
590
        assert_eq!(cloned.frames_dropped, u64::MAX);
591
    }
592

            
593
    // ---- Numeric: NaN ordering, saturation, overflow, precision limits ----
594

            
595
    #[test]
596
    fn capture_stats_nan_fps_makes_partial_cmp_none() {
597
        // CaptureStats is only PartialEq (no Ord) precisely because of the f32.
598
        // A NaN fps must yield an *incomparable* float, not a silent ordering.
599
        let nan = f32::NAN;
600
        assert!(nan.partial_cmp(&0.0).is_none());
601
        assert!(nan.partial_cmp(&nan).is_none());
602

            
603
        let s = CaptureStats {
604
            measured_fps: nan,
605
            ..CaptureStats::default()
606
        };
607
        // A NaN-carrying stats value can never be *found* by equality search,
608
        // so consumers must not rely on `contains` / dedup for it.
609
        let haystack = [s, CaptureStats::default()];
610
        assert!(!haystack.contains(&s), "NaN stats is unfindable by Eq");
611
        assert!(haystack.contains(&CaptureStats::default()));
612
    }
613

            
614
    #[test]
615
    fn measured_fps_to_integer_cast_saturates_instead_of_wrapping() {
616
        // HUD code casting measured_fps to an integer must not hit UB or wrap.
617
        // Rust `as` casts are saturating: NaN -> 0, +inf -> MAX, negative -> 0.
618
        let cases: [(f32, u32); 6] = [
619
            (f32::NAN, 0),
620
            (f32::INFINITY, u32::MAX),
621
            (f32::NEG_INFINITY, 0),
622
            (-1.0, 0),
623
            (-0.0, 0),
624
            (f32::MAX, u32::MAX),
625
        ];
626
        for (fps, expected) in cases {
627
            let s = CaptureStats {
628
                measured_fps: fps,
629
                ..CaptureStats::default()
630
            };
631
            assert_eq!(
632
                s.measured_fps as u32, expected,
633
                "cast of {fps} must saturate to {expected}"
634
            );
635
        }
636
        // Ordinary value is unchanged (truncates toward zero).
637
        let ok = CaptureStats {
638
            measured_fps: 59.94,
639
            ..CaptureStats::default()
640
        };
641
        assert_eq!(ok.measured_fps as u32, 59);
642
    }
643

            
644
    #[test]
645
    fn frame_counters_overflow_only_via_checked_arithmetic() {
646
        // `frames_delivered + frames_dropped` is the obvious "total frames"
647
        // consumers will compute - at the saturated boundary it overflows.
648
        let s = CaptureStats {
649
            measured_fps: 30.0,
650
            frames_delivered: u64::MAX,
651
            frames_dropped: 1,
652
        };
653
        assert_eq!(
654
            s.frames_delivered.checked_add(s.frames_dropped),
655
            None,
656
            "total-frames overflows u64; consumers must saturate/check"
657
        );
658
        assert_eq!(
659
            s.frames_delivered.saturating_add(s.frames_dropped),
660
            u64::MAX,
661
            "saturating_add is the safe path"
662
        );
663
        // One below the boundary is fine.
664
        let ok = CaptureStats {
665
            frames_delivered: u64::MAX - 1,
666
            frames_dropped: 1,
667
            ..CaptureStats::default()
668
        };
669
        assert_eq!(
670
            ok.frames_delivered.checked_add(ok.frames_dropped),
671
            Some(u64::MAX)
672
        );
673
    }
674

            
675
    #[test]
676
    fn drop_rate_over_zeroed_stats_must_be_guarded() {
677
        // Default stats have delivered == dropped == 0, so the natural drop
678
        // rate `dropped / (delivered + dropped)` divides by zero: integer
679
        // division would PANIC, float division yields NaN. Assert both, so the
680
        // hazard is pinned rather than discovered in a HUD at runtime.
681
        let s = CaptureStats::default();
682
        let total = s.frames_delivered + s.frames_dropped;
683
        assert_eq!(total, 0);
684
        assert_eq!(
685
            s.frames_dropped.checked_div(total),
686
            None,
687
            "integer drop-rate on zeroed stats must be checked, not raw `/`"
688
        );
689
        let rate = s.frames_dropped as f64 / total as f64;
690
        assert!(rate.is_nan(), "float drop-rate on zeroed stats is NaN");
691

            
692
        // With traffic, the rate is well-defined.
693
        let live = CaptureStats {
694
            measured_fps: 30.0,
695
            frames_delivered: 75,
696
            frames_dropped: 25,
697
        };
698
        let total = live.frames_delivered + live.frames_dropped;
699
        assert_eq!(live.frames_dropped.checked_div(total), Some(0));
700
        assert!(((live.frames_dropped as f64 / total as f64) - 0.25).abs() < 1e-12);
701
    }
702

            
703
    #[test]
704
    fn config_pixel_count_overflows_u32_at_extreme_dimensions() {
705
        // width * height is the natural buffer-size computation. At the
706
        // documented-legal extremes it overflows u32 and must be widened.
707
        let cfg = CameraConfig {
708
            width: u32::MAX,
709
            height: u32::MAX,
710
            ..CameraConfig::default()
711
        };
712
        assert_eq!(
713
            cfg.width.checked_mul(cfg.height),
714
            None,
715
            "u32 pixel count overflows; widen to u64 before multiplying"
716
        );
717
        assert_eq!(
718
            u64::from(cfg.width) * u64::from(cfg.height),
719
            (u64::from(u32::MAX)) * (u64::from(u32::MAX)),
720
            "u64 widening is the safe path"
721
        );
722
        // A realistic size does not overflow.
723
        let hd = CameraConfig {
724
            width: 1920,
725
            height: 1080,
726
            ..CameraConfig::default()
727
        };
728
        assert_eq!(hd.width.checked_mul(hd.height), Some(2_073_600));
729
    }
730

            
731
    #[test]
732
    fn fps_u32_to_f32_roundtrip_is_lossy_above_2_pow_24() {
733
        // The config's requested `fps` is u32 while the reported `measured_fps`
734
        // is f32. Comparing them via a cast is exact only below 2^24.
735
        let exact: u32 = 1 << 24; // 16_777_216
736
        assert_eq!(exact as f32 as u32, exact, "2^24 round-trips exactly");
737

            
738
        let lossy: u32 = (1 << 24) + 1; // 16_777_217
739
        assert_ne!(
740
            lossy as f32 as u32, lossy,
741
            "2^24+1 must NOT round-trip through f32 - precision is lost"
742
        );
743
        assert_eq!(lossy as f32 as u32, exact, "it rounds down to 2^24");
744

            
745
        // Realistic fps values are far below the boundary and are exact.
746
        for fps in [0u32, 1, 24, 30, 60, 120, 240] {
747
            let cfg = CameraConfig {
748
                fps,
749
                ..CameraConfig::default()
750
            };
751
            assert_eq!(cfg.fps as f32 as u32, fps, "fps {fps} must be exact");
752
        }
753
    }
754

            
755
    #[test]
756
    fn frames_delivered_u64_to_f32_roundtrip_is_lossy_at_the_boundary() {
757
        // Same hazard on the counter side: a HUD computing fps as
758
        // frames_delivered as f32 / secs loses counts past 2^24.
759
        let s = CaptureStats {
760
            frames_delivered: (1 << 24) + 1,
761
            ..CaptureStats::default()
762
        };
763
        assert_ne!(s.frames_delivered as f32 as u64, s.frames_delivered);
764
        // u64::MAX -> f32 rounds UP past u64::MAX, and the cast back saturates.
765
        let sat = CaptureStats {
766
            frames_delivered: u64::MAX,
767
            ..CaptureStats::default()
768
        };
769
        assert_eq!(
770
            sat.frames_delivered as f32 as u64,
771
            u64::MAX,
772
            "saturating cast clamps rather than wrapping to 0"
773
        );
774
    }
775

            
776
    // ---- Predicates / invariants over the whole variant space ----
777

            
778
    #[test]
779
    fn all_enum_variants_are_pairwise_distinct_and_hash_consistently() {
780
        use std::collections::HashSet;
781
        assert_eq!(
782
            ALL_STATES.iter().collect::<HashSet<_>>().len(),
783
            ALL_STATES.len(),
784
            "StreamState variants must be pairwise distinct"
785
        );
786
        assert_eq!(
787
            ALL_ORIENTATIONS.iter().collect::<HashSet<_>>().len(),
788
            ALL_ORIENTATIONS.len(),
789
            "CaptureOrientation variants must be pairwise distinct"
790
        );
791
        assert_eq!(
792
            ALL_ERRORS.iter().collect::<HashSet<_>>().len(),
793
            ALL_ERRORS.len(),
794
            "CaptureErrorCode variants must be pairwise distinct"
795
        );
796
        assert_eq!(
797
            ALL_FORMATS.iter().collect::<HashSet<_>>().len(),
798
            ALL_FORMATS.len(),
799
            "RawImageFormat variants must be pairwise distinct"
800
        );
801
    }
802

            
803
    #[test]
804
    fn ord_is_a_total_order_for_every_camera_enum() {
805
        use core::cmp::Ordering;
806
        // Trichotomy + antisymmetry + transitivity, exhaustively over the
807
        // (small) variant spaces. CameraFacing is already covered above.
808
        macro_rules! assert_total_order {
809
            ($set:expr) => {{
810
                for &a in $set {
811
                    assert_eq!(a.cmp(&a), Ordering::Equal);
812
                    for &b in $set {
813
                        let lt = (a < b) as u8;
814
                        let eq = (a == b) as u8;
815
                        let gt = (a > b) as u8;
816
                        assert_eq!(lt + eq + gt, 1, "trichotomy ({a:?}, {b:?})");
817
                        if a < b {
818
                            assert!(!(b < a), "antisymmetry ({a:?}, {b:?})");
819
                        }
820
                        for &c in $set {
821
                            if a < b && b < c {
822
                                assert!(a < c, "transitivity ({a:?}, {b:?}, {c:?})");
823
                            }
824
                        }
825
                    }
826
                }
827
            }};
828
        }
829
        assert_total_order!(&ALL_STATES);
830
        assert_total_order!(&ALL_ORIENTATIONS);
831
        assert_total_order!(&ALL_ERRORS);
832
    }
833

            
834
    #[test]
835
    fn capture_stream_id_hash_eq_and_copy_independence() {
836
        use std::collections::HashSet;
837
        let mut set = HashSet::new();
838
        for id in [0u64, 1, u64::MAX / 2, u64::MAX] {
839
            assert!(set.insert(CaptureStreamId { id }), "id {id} is new");
840
        }
841
        assert_eq!(set.len(), 4);
842
        // Re-inserting an equal id must be rejected (Hash agrees with Eq).
843
        assert!(!set.insert(CaptureStreamId { id: u64::MAX }));
844
        assert!(set.contains(&CaptureStreamId { id: 0 }));
845

            
846
        // Copy: mutating the copy must not disturb the original.
847
        let a = CaptureStreamId { id: 7 };
848
        let mut b = a;
849
        b.id = 9;
850
        assert_eq!(a.id, 7);
851
        assert_eq!(b.id, 9);
852
    }
853

            
854
    #[test]
855
    fn capture_stats_copy_is_independent() {
856
        let a = CaptureStats {
857
            measured_fps: 30.0,
858
            frames_delivered: 100,
859
            frames_dropped: 2,
860
        };
861
        let mut b = a;
862
        b.measured_fps = 0.0;
863
        b.frames_delivered = 0;
864
        b.frames_dropped = 0;
865
        assert_eq!(a.measured_fps, 30.0, "original must survive copy mutation");
866
        assert_eq!(a.frames_delivered, 100);
867
        assert_eq!(a.frames_dropped, 2);
868
        assert_eq!(b, CaptureStats::default());
869
    }
870

            
871
    #[test]
872
    fn debug_formatting_never_panics_on_extreme_or_nan_values() {
873
        // Debug is what a crash report / HUD log prints; it must survive the
874
        // adversarial values above.
875
        let stats = CaptureStats {
876
            measured_fps: f32::NAN,
877
            frames_delivered: u64::MAX,
878
            frames_dropped: u64::MAX,
879
        };
880
        assert!(!format!("{stats:?}").is_empty());
881
        assert!(!format!(
882
            "{:?}",
883
            CaptureStats {
884
                measured_fps: f32::NEG_INFINITY,
885
                ..CaptureStats::default()
886
            }
887
        )
888
        .is_empty());
889

            
890
        let cfg = CameraConfig {
891
            facing: CameraFacing::External,
892
            width: u32::MAX,
893
            height: u32::MAX,
894
            fps: u32::MAX,
895
            output_format: RawImageFormat::RGBAF32,
896
        };
897
        let s = format!("{cfg:?}");
898
        assert!(s.contains("External"), "Debug must name the facing: {s}");
899
        assert!(s.contains("4294967295"), "Debug must show raw extents: {s}");
900

            
901
        assert!(!format!("{:?}", CaptureStreamId { id: u64::MAX }).is_empty());
902
        for &st in &ALL_STATES {
903
            assert!(!format!("{st:?}").is_empty());
904
        }
905
        for &o in &ALL_ORIENTATIONS {
906
            assert!(!format!("{o:?}").is_empty());
907
        }
908
        for &e in &ALL_ERRORS {
909
            assert!(!format!("{e:?}").is_empty());
910
        }
911
    }
912

            
913
    #[test]
914
    fn repr_c_layout_invariants_hold_for_the_ffi_pod_types() {
915
        use core::mem::{align_of, size_of};
916
        // Single-field #[repr(C)] newtype: must be exactly its payload, so it
917
        // can be passed across the FFI as a bare u64.
918
        assert_eq!(size_of::<CaptureStreamId>(), size_of::<u64>());
919
        assert_eq!(align_of::<CaptureStreamId>(), align_of::<u64>());
920

            
921
        // No exact byte sizes asserted for the aggregates: u64 alignment (and
922
        // therefore trailing padding) differs on 32-bit targets. Assert the
923
        // portable invariants instead - big enough for the payload, and a
924
        // whole number of alignment units (a valid array element).
925
        assert!(size_of::<CaptureStats>() >= size_of::<f32>() + 2 * size_of::<u64>());
926
        assert_eq!(size_of::<CaptureStats>() % align_of::<CaptureStats>(), 0);
927

            
928
        assert!(size_of::<CameraConfig>() >= 3 * size_of::<u32>());
929
        assert_eq!(size_of::<CameraConfig>() % align_of::<CameraConfig>(), 0);
930

            
931
        // Fieldless repr(C) enums are C ints - never zero-sized, never huge.
932
        assert_eq!(size_of::<CameraFacing>(), size_of::<StreamState>());
933
        assert_eq!(size_of::<StreamState>(), size_of::<CaptureOrientation>());
934
        assert_eq!(
935
            size_of::<CaptureOrientation>(),
936
            size_of::<CaptureErrorCode>()
937
        );
938
        assert!(size_of::<CameraFacing>() > 0);
939
    }
940
}