1
#[allow(unused_imports)]
2
pub use super::*;
3

            
4
#[cfg(test)]
5
#[allow(clippy::float_cmp)] // exact-value assertions on interpolation results
6
mod tests {
7
    use super::*;
8

            
9
15
    fn tick(n: u64) -> Instant {
10
15
        Instant::Tick(SystemTick::new(n))
11
15
    }
12
19
    fn tick_dur(n: u64) -> Duration {
13
19
        Duration::Tick(SystemTickDiff { tick_diff: n })
14
19
    }
15
10
    fn sys_dur(secs: u64, nanos: u32) -> Duration {
16
10
        Duration::System(SystemTimeDiff { secs, nanos })
17
10
    }
18

            
19
    /// The property the parallel E2E runner depends on: a `tick_ms` on one
20
    /// thread must not shift any other thread's clock. This is what allows a
21
    /// scenario that ticks to run in parallel with every other scenario
22
    /// instead of being serialised behind a process-global offset.
23
    #[test]
24
    #[cfg(feature = "std")]
25
1
    fn test_clock_offset_is_per_thread_not_process_global() {
26
1
        reset_test_clock();
27
1
        assert_eq!(test_clock_offset_ms(), 0);
28

            
29
1
        let (tx, rx) = std::sync::mpsc::channel();
30
1
        let (go_tx, go_rx) = std::sync::mpsc::channel::<()>();
31
1
        let other = std::thread::spawn(move || {
32
            // Observed AFTER the main thread has advanced its own clock by 5 s.
33
1
            go_rx.recv().expect("handshake");
34
1
            let seen_after_main_ticked = test_clock_offset_ms();
35
1
            let _ = advance_test_clock_ms(7);
36
1
            tx.send((seen_after_main_ticked, test_clock_offset_ms()))
37
1
                .expect("send");
38
1
        });
39

            
40
1
        assert_eq!(advance_test_clock_ms(5_000), 5_000);
41
1
        go_tx.send(()).expect("handshake");
42
1
        let (other_before, other_after) = rx.recv().expect("recv");
43
1
        other.join().expect("join");
44

            
45
1
        assert_eq!(
46
            other_before, 0,
47
            "a tick on the main thread leaked into another thread's clock"
48
        );
49
1
        assert_eq!(other_after, 7, "the other thread must own its own offset");
50
1
        assert_eq!(
51
1
            test_clock_offset_ms(),
52
            5_000,
53
            "another thread's tick leaked into the main thread's clock"
54
        );
55

            
56
        // And a reset really is a reset (worker threads are reused).
57
1
        reset_test_clock();
58
1
        assert_eq!(test_clock_offset_ms(), 0);
59
1
    }
60

            
61
    /// A frozen clock must advance ONLY by what a scenario asks for.
62
    ///
63
    /// Offsetting alone left `Instant::now()` as `StdInstant::now() + offset`, so
64
    /// real time still flowed: elapsed time was what the scenario asked for PLUS
65
    /// whatever the machine happened to spend. Under the 8-wide E2E runner that
66
    /// second term is large and varies per run — enough to flip an assertion on a
67
    /// blinking caret's phase while the same scenario passes in isolation.
68
    #[test]
69
    #[cfg(feature = "std")]
70
1
    fn a_frozen_clock_advances_only_by_what_the_scenario_asks_for() {
71
1
        reset_test_clock();
72
1
        assert!(!test_clock_is_frozen());
73

            
74
1
        freeze_test_clock();
75
1
        assert!(test_clock_is_frozen());
76

            
77
1
        let t0 = Instant::now();
78
        // Burn REAL time. A frozen clock must not notice.
79
1
        std::thread::sleep(core::time::Duration::from_millis(25));
80
1
        let t1 = Instant::now();
81
1
        assert_eq!(
82
1
            t1.duration_since(&t0),
83
            Duration::System(SystemTimeDiff { secs: 0, nanos: 0 }),
84
            "real time leaked into a frozen clock",
85
        );
86

            
87
        // Only an explicit advance moves it, and by exactly that much.
88
1
        let _ = advance_test_clock_ms(500);
89
1
        let t2 = Instant::now();
90
1
        assert_eq!(
91
1
            t2.duration_since(&t0),
92
            Duration::System(SystemTimeDiff {
93
                secs: 0,
94
                nanos: 500_000_000
95
            }),
96
            "a 500 ms tick must read back as exactly 500 ms",
97
        );
98

            
99
        // Freezing is idempotent: it must not re-base and lose the offset.
100
1
        freeze_test_clock();
101
1
        assert_eq!(
102
1
            Instant::now().duration_since(&t0),
103
            Duration::System(SystemTimeDiff {
104
                secs: 0,
105
                nanos: 500_000_000
106
            }),
107
            "re-freezing re-based the clock and discarded elapsed virtual time",
108
        );
109

            
110
        // A reset must unfreeze, or the next scenario on this reused worker
111
        // thread would start with time stopped.
112
1
        reset_test_clock();
113
1
        assert!(!test_clock_is_frozen());
114
1
        let r0 = Instant::now();
115
1
        std::thread::sleep(core::time::Duration::from_millis(15));
116
1
        assert!(
117
1
            Instant::now().duration_since(&r0)
118
1
                > Duration::System(SystemTimeDiff { secs: 0, nanos: 0 }),
119
            "reset_test_clock left the clock frozen",
120
        );
121
1
    }
122

            
123
    #[test]
124
1
    fn linear_interpolate_zero_interval_is_one_not_nan() {
125
1
        let t = tick(5);
126
1
        let v = t.linear_interpolate(tick(5), tick(5));
127
1
        assert!(v.is_finite());
128
1
        assert_eq!(v, 1.0);
129
1
    }
130

            
131
    #[test]
132
1
    fn linear_interpolate_midpoint() {
133
1
        let v = tick(5).linear_interpolate(tick(0), tick(10));
134
1
        assert!((v - 0.5).abs() < 1e-6);
135
1
    }
136

            
137
    #[test]
138
1
    fn duration_since_saturates_on_negative() {
139
        // earlier is actually later -> saturate to zero, no panic.
140
1
        let d = tick(1).duration_since(&tick(10));
141
1
        assert_eq!(d, tick_dur(0));
142
1
    }
143

            
144
    /// Cross-unit comparison must answer TRUTHFULLY, not saturate to `false`.
145
    ///
146
    /// The saturating version made a unit mismatch a permanent silent "not yet":
147
    /// every interval constant in the engine is a `Duration::System`, so a Tick
148
    /// elapsed value compared against one never expired and the UI simply stopped
149
    /// animating, with nothing to catch.
150
    #[test]
151
1
    fn duration_compare_is_unit_aware_across_ticks_and_wall_clock() {
152
        // 5 ticks at 60Hz is ~83ms, i.e. LESS than one second.
153
1
        let five_ticks = tick_dur(5);
154
1
        let one_second = sys_dur(1, 0);
155
1
        assert!(five_ticks.smaller_than(&one_second));
156
1
        assert!(!five_ticks.greater_than(&one_second));
157
1
        assert!(one_second.greater_than(&five_ticks));
158
1
        assert!(!one_second.smaller_than(&five_ticks));
159

            
160
        // 120 ticks is two seconds, i.e. MORE than one second.
161
1
        assert!(tick_dur(120).greater_than(&one_second));
162
1
        assert!(one_second.smaller_than(&tick_dur(120)));
163

            
164
        // Exactly 60 ticks IS one second: neither greater nor smaller.
165
1
        assert!(!tick_dur(60).greater_than(&one_second));
166
1
        assert!(!tick_dur(60).smaller_than(&one_second));
167
1
        assert!(!one_second.greater_than(&tick_dur(60)));
168
1
        assert!(!one_second.smaller_than(&tick_dur(60)));
169
1
    }
170

            
171
    /// `Duration::max()` is `System`, and it must still dominate every tick count
172
    /// — including `u64::MAX` ticks, which is a bigger *number* but a smaller
173
    /// span.
174
    #[test]
175
1
    fn duration_compare_across_units_at_the_extremes() {
176
1
        assert!(Duration::max().greater_than(&tick_dur(u64::MAX)));
177
1
        assert!(tick_dur(u64::MAX).smaller_than(&Duration::max()));
178
1
        assert!(!tick_dur(0).greater_than(&sys_dur(0, 0)));
179
1
        assert!(!sys_dur(0, 0).greater_than(&tick_dur(0)));
180
        // One nanosecond beats zero ticks.
181
1
        assert!(sys_dur(0, 1).greater_than(&tick_dur(0)));
182
1
    }
183

            
184
    #[test]
185
1
    fn add_optional_duration_converts_across_units() {
186
1
        let inst = tick(100);
187
        // A System duration on a Tick instant advances by WHOLE ticks: 1s = 60.
188
1
        assert_eq!(inst.add_optional_duration(Some(&sys_dur(1, 0))), tick(160));
189
        // Sub-frame durations advance nothing — one frame is the resolution.
190
1
        assert_eq!(inst.add_optional_duration(Some(&sys_dur(0, 1))), tick(100));
191
        // Matching kinds add and saturate.
192
1
        assert_eq!(inst.add_optional_duration(Some(&tick_dur(5))), tick(105));
193
        // Saturating add: near-max tick doesn't overflow-panic.
194
1
        let big = tick(u64::MAX);
195
1
        assert_eq!(
196
1
            big.add_optional_duration(Some(&tick_dur(10))),
197
1
            tick(u64::MAX)
198
        );
199
        // ...and the cross-unit arm saturates too.
200
1
        assert_eq!(
201
1
            big.add_optional_duration(Some(&Duration::max())),
202
1
            tick(u64::MAX)
203
        );
204
1
    }
205

            
206
    #[test]
207
1
    fn millis_saturates_on_overflow() {
208
1
        let huge = SystemTimeDiff {
209
1
            secs: u64::MAX,
210
1
            nanos: 0,
211
1
        };
212
1
        assert_eq!(huge.millis(), u64::MAX);
213
1
        let normal = SystemTimeDiff {
214
1
            secs: 2,
215
1
            nanos: 500_000_000,
216
1
        };
217
1
        assert_eq!(normal.millis(), 2500);
218
1
    }
219

            
220
    /// Cross-unit division goes through the canonical scale. Returning `0.0` (the
221
    /// old behaviour) reads downstream as "this animation is at 0% progress",
222
    /// i.e. a frozen animation that never reports an error.
223
    #[test]
224
1
    fn duration_div_is_unit_aware() {
225
        // 30 ticks is half a second.
226
1
        assert!((tick_dur(30).div(&sys_dur(1, 0)) - 0.5).abs() < 1e-6);
227
        // ...and one second is two lots of 30 ticks.
228
1
        assert!((sys_dur(1, 0).div(&tick_dur(30)) - 2.0).abs() < 1e-6);
229
        // Matching Tick kinds divide normally.
230
1
        assert!((tick_dur(5).div(&tick_dur(10)) - 0.5).abs() < 1e-6);
231
        // Matching System kinds divide normally.
232
1
        assert!((sys_dur(1, 0).div(&sys_dur(2, 0)) - 0.5).abs() < 1e-6);
233
1
    }
234

            
235
    // Exercises the `unsafe` pointer work in `std_instant_clone` (`&*ptr`) and
236
    // the `ManuallyDrop::drop` guard in `InstantPtr::drop`: build an InstantPtr,
237
    // clone it (goes through the FFI clone callback + raw-ptr deref), then let
238
    // both drop. Under Miri this asserts the clone/drop path is UB-free and the
239
    // owned `Box` is freed exactly once per value (no double-free).
240
    #[cfg(feature = "std")]
241
    #[test]
242
1
    fn instant_ptr_clone_and_drop_no_ub() {
243
1
        let base = StdInstant::now();
244
1
        let a: InstantPtr = base.into();
245
1
        let b = a.clone();
246
        // The clone must observe the same underlying instant.
247
1
        assert_eq!(a, b);
248
        // Both `a` and `b` own independent Boxes; dropping both must not
249
        // double-free (each has run_destructor == true).
250
1
        drop(a);
251
1
        drop(b);
252
1
    }
253
}
254

            
255
#[cfg(test)]
256
#[allow(clippy::float_cmp)] // exact-value assertions on ratios / interpolation results
257
mod autotest_generated {
258
    use super::*;
259

            
260
    // ---- helpers -----------------------------------------------------------
261

            
262
    fn tick(n: u64) -> Instant {
263
        Instant::Tick(SystemTick::new(n))
264
    }
265
    fn tick_dur(n: u64) -> Duration {
266
        Duration::Tick(SystemTickDiff { tick_diff: n })
267
    }
268
    fn sys_dur(secs: u64, nanos: u32) -> Duration {
269
        Duration::System(SystemTimeDiff { secs, nanos })
270
    }
271

            
272
    // ========================================================================
273
    // TimerId::unique / ThreadId::unique  (monotonic, never hits reserved IDs)
274
    // ========================================================================
275

            
276
    #[test]
277
    fn timer_id_unique_is_strictly_increasing_and_above_reserved_range() {
278
        let a = TimerId::unique();
279
        let b = TimerId::unique();
280
        assert_ne!(a, b);
281
        assert!(
282
            b.id > a.id,
283
            "unique() must strictly increase: {a:?} -> {b:?}"
284
        );
285
        // User IDs must never land inside the reserved system-timer block.
286
        for id in [a, b] {
287
            assert!(
288
                id.id >= USER_TIMER_ID_START,
289
                "unique() handed out a reserved system ID: {id:?}"
290
            );
291
            assert_ne!(id, CURSOR_BLINK_TIMER_ID);
292
            assert_ne!(id, SCROLL_MOMENTUM_TIMER_ID);
293
            assert_ne!(id, DRAG_AUTOSCROLL_TIMER_ID);
294
            assert_ne!(id, TOOLTIP_DELAY_TIMER_ID);
295
            assert_ne!(id, CAPABILITY_PUMP_TIMER_ID);
296
            assert_ne!(id, LONG_PRESS_TIMER_ID);
297
        }
298
    }
299

            
300
    #[test]
301
    fn thread_id_unique_is_strictly_increasing_and_above_reserved_range() {
302
        let a = ThreadId::unique();
303
        let b = ThreadId::unique();
304
        assert_ne!(a, b);
305
        assert!(b.id > a.id);
306
        assert!(a.id >= RESERVED_THREAD_ID_COUNT);
307
    }
308

            
309
    // The counters are `AtomicUsize` + `fetch_add`, so concurrent callers must
310
    // never be handed the same ID. 8 threads x 64 IDs => 512 distinct values.
311
    #[cfg(feature = "std")]
312
    #[test]
313
    fn unique_ids_do_not_collide_across_threads() {
314
        use alloc::collections::BTreeSet;
315

            
316
        let handles: Vec<_> = (0..8)
317
            .map(|_| {
318
                std::thread::spawn(|| {
319
                    let mut out = Vec::new();
320
                    for _ in 0..64 {
321
                        out.push((TimerId::unique().id, ThreadId::unique().id));
322
                    }
323
                    out
324
                })
325
            })
326
            .collect();
327

            
328
        let mut timer_ids = BTreeSet::new();
329
        let mut thread_ids = BTreeSet::new();
330
        for h in handles {
331
            for (t, th) in h.join().expect("worker thread panicked") {
332
                assert!(timer_ids.insert(t), "duplicate TimerId handed out: {t}");
333
                assert!(thread_ids.insert(th), "duplicate ThreadId handed out: {th}");
334
            }
335
        }
336
        assert_eq!(timer_ids.len(), 8 * 64);
337
        assert_eq!(thread_ids.len(), 8 * 64);
338
    }
339

            
340
    // ========================================================================
341
    // Instant::now / get_system_time_libstd
342
    // ========================================================================
343

            
344
    #[cfg(feature = "std")]
345
    #[test]
346
    fn instant_now_is_system_and_monotonic() {
347
        let a = Instant::now();
348
        let b = Instant::now();
349
        assert!(matches!(a, Instant::System(_)));
350
        assert!(a <= b, "Instant::now() went backwards");
351
        // A later instant is never "before" an earlier one.
352
        assert_eq!(a.duration_since(&b), sys_dur(0, 0));
353
    }
354

            
355
    #[cfg(all(feature = "std", not(target_arch = "wasm32")))]
356
    #[test]
357
    fn get_system_time_libstd_is_monotonic_system_instant() {
358
        let a = get_system_time_libstd();
359
        let b = get_system_time_libstd();
360
        assert!(matches!(a, Instant::System(_)));
361
        assert!(matches!(b, Instant::System(_)));
362
        assert!(a <= b);
363
    }
364

            
365
    #[cfg(any(not(feature = "std"), target_arch = "wasm32"))]
366
    #[test]
367
    fn get_system_time_libstd_wasm_fallback_is_zero_tick() {
368
        // On WASM / no_std `StdInstant::now()` would panic, so the fallback must
369
        // hand back a tick instant instead of exploding.
370
        assert_eq!(get_system_time_libstd(), tick(0));
371
    }
372

            
373
    // ========================================================================
374
    // Instant::linear_interpolate  (must never return NaN / escape [0.0, 1.0])
375
    // ========================================================================
376

            
377
    #[test]
378
    fn linear_interpolate_clamps_outside_the_interval() {
379
        // before start -> 0.0, after end -> 1.0 (never negative / >1).
380
        assert_eq!(tick(0).linear_interpolate(tick(10), tick(20)), 0.0);
381
        assert_eq!(tick(999).linear_interpolate(tick(10), tick(20)), 1.0);
382
        // exactly on the boundaries
383
        assert_eq!(tick(10).linear_interpolate(tick(10), tick(20)), 0.0);
384
        assert_eq!(tick(20).linear_interpolate(tick(10), tick(20)), 1.0);
385
    }
386

            
387
    #[test]
388
    fn linear_interpolate_reversed_interval_is_normalized() {
389
        // `end < start` is swapped internally, so the ratio is the same as the
390
        // correctly-ordered call rather than a garbage / negative value.
391
        let forwards = tick(5).linear_interpolate(tick(0), tick(10));
392
        let backwards = tick(5).linear_interpolate(tick(10), tick(0));
393
        assert_eq!(forwards, backwards);
394
        assert!((backwards - 0.5).abs() < 1e-6);
395
    }
396

            
397
    #[test]
398
    fn linear_interpolate_saturating_extremes_stay_in_range() {
399
        // Full u64 span: the tick diff hits u64::MAX and the f64->f32 narrowing
400
        // must not produce inf/NaN.
401
        let v = tick(u64::MAX / 2).linear_interpolate(tick(0), tick(u64::MAX));
402
        assert!(
403
            v.is_finite(),
404
            "interpolation over the full u64 span went non-finite"
405
        );
406
        assert!((0.0..=1.0).contains(&v));
407
        assert!((v - 0.5).abs() < 1e-3, "expected ~0.5, got {v}");
408

            
409
        // Degenerate zero-length interval at the extremes -> 1.0, not 0/0 = NaN.
410
        let z = tick(u64::MAX).linear_interpolate(tick(u64::MAX), tick(u64::MAX));
411
        assert_eq!(z, 1.0);
412
        let z0 = tick(0).linear_interpolate(tick(0), tick(0));
413
        assert_eq!(z0, 1.0);
414
    }
415

            
416
    #[cfg(feature = "std")]
417
    #[test]
418
    fn linear_interpolate_mismatched_kinds_never_nan() {
419
        // Every mismatched (System / Tick) permutation feeds a 0/0 division
420
        // internally; the guard must turn that into a finite value in [0, 1].
421
        let sys = Instant::now();
422
        let cases = [
423
            (tick(5), sys.clone(), tick(10)),
424
            (sys.clone(), tick(0), tick(10)),
425
            (tick(5), tick(0), sys.clone()),
426
            (sys.clone(), sys.clone(), tick(10)),
427
            (tick(5), sys.clone(), sys.clone()),
428
        ];
429
        for (this, start, end) in cases {
430
            let v = this.linear_interpolate(start, end);
431
            assert!(v.is_finite(), "mismatched-kind interpolation returned {v}");
432
            assert!(
433
                (0.0..=1.0).contains(&v),
434
                "mismatched-kind interpolation escaped [0,1]: {v}"
435
            );
436
        }
437
    }
438

            
439
    // ========================================================================
440
    // Instant::add_optional_duration
441
    // ========================================================================
442

            
443
    #[test]
444
    fn add_optional_duration_none_is_identity() {
445
        let t = tick(42);
446
        assert_eq!(t.add_optional_duration(None), t);
447
        assert_eq!(tick(u64::MAX).add_optional_duration(None), tick(u64::MAX));
448
    }
449

            
450
    #[test]
451
    fn add_optional_duration_tick_saturates_at_u64_max() {
452
        // saturating_add: u64::MAX-1 + huge must clamp, not wrap or panic.
453
        let near_max = tick(u64::MAX - 1);
454
        assert_eq!(
455
            near_max.add_optional_duration(Some(&tick_dur(u64::MAX))),
456
            tick(u64::MAX)
457
        );
458
        assert_eq!(tick(0).add_optional_duration(Some(&tick_dur(0))), tick(0));
459
    }
460

            
461
    #[cfg(feature = "std")]
462
    #[test]
463
    fn add_optional_duration_system_advances_by_the_duration() {
464
        let base = Instant::now();
465
        let later =
466
            base.add_optional_duration(Some(&Duration::System(SystemTimeDiff::from_secs(1))));
467
        assert!(later > base);
468
        let delta = later.duration_since(&base);
469
        assert_eq!(delta, sys_dur(1, 0));
470
        // ... and the reverse span saturates to zero rather than going negative.
471
        assert_eq!(base.duration_since(&later), sys_dur(0, 0));
472
    }
473

            
474
    /// A `Tick` interval on a wall-clock instant has to ADVANCE that instant, not
475
    /// leave it alone. `Timer::instant_of_next_run` is exactly `last_run +
476
    /// delay + interval`; when this returned `self`, a tick-unit timer's next run
477
    /// was always "now" — permanently overdue, and `time_until_next_timer_ms`
478
    /// answered `Some(0)` for it.
479
    #[cfg(feature = "std")]
480
    #[test]
481
    fn add_optional_duration_converts_between_units_in_both_directions() {
482
        let sys = Instant::now();
483
        // System instant + Tick duration: 60 ticks is exactly one second.
484
        let later = sys.add_optional_duration(Some(&tick_dur(60)));
485
        assert!(
486
            later > sys,
487
            "a tick interval must advance a wall-clock instant"
488
        );
489
        assert_eq!(later.duration_since(&sys), sys_dur(1, 0));
490

            
491
        // 0 ticks is genuinely no time at all.
492
        assert_eq!(sys.add_optional_duration(Some(&tick_dur(0))), sys);
493

            
494
        // Tick instant + System duration: 3s is 180 whole frames.
495
        assert_eq!(
496
            tick(7).add_optional_duration(Some(&sys_dur(3, 0))),
497
            tick(187)
498
        );
499
    }
500

            
501
    // A `System` instant plus an enormous `System` duration overflows the
502
    // platform clock representation: `StdInstant + StdDuration` panics with
503
    // "overflow when adding duration to instant". Unlike the mismatched-kind
504
    // case (documented to saturate), this arm has no guard -- characterized
505
    // here so a future saturating fix flips this test loudly.
506
    #[cfg(all(feature = "std", not(target_arch = "wasm32")))]
507
    #[test]
508
    #[should_panic(expected = "overflow")]
509
    fn add_optional_duration_system_overflow_panics_today() {
510
        let base = Instant::now();
511
        let _ = base.add_optional_duration(Some(&Duration::max()));
512
    }
513

            
514
    // ========================================================================
515
    // Instant::duration_since / into_std_instant
516
    // ========================================================================
517

            
518
    #[test]
519
    fn duration_since_tick_saturates_and_is_exact() {
520
        assert_eq!(tick(10).duration_since(&tick(4)), tick_dur(6));
521
        // self == earlier -> zero span
522
        assert_eq!(tick(10).duration_since(&tick(10)), tick_dur(0));
523
        // earlier is later -> saturate to zero, no underflow panic
524
        assert_eq!(tick(0).duration_since(&tick(u64::MAX)), tick_dur(0));
525
        // full-range span does not overflow
526
        assert_eq!(tick(u64::MAX).duration_since(&tick(0)), tick_dur(u64::MAX));
527
    }
528

            
529
    #[cfg(feature = "std")]
530
    #[test]
531
    fn duration_since_mismatched_kinds_is_zero_tick_both_directions() {
532
        let sys = Instant::now();
533
        assert_eq!(sys.duration_since(&tick(5)), tick_dur(0));
534
        assert_eq!(tick(5).duration_since(&sys), tick_dur(0));
535
    }
536

            
537
    #[cfg(feature = "std")]
538
    #[test]
539
    fn into_std_instant_round_trips_a_system_instant() {
540
        let base = StdInstant::now();
541
        let wrapped: Instant = base.into();
542
        assert_eq!(wrapped.into_std_instant(), base);
543
    }
544

            
545
    #[cfg(feature = "std")]
546
    #[test]
547
    #[should_panic(expected = "internal error: entered unreachable code")]
548
    fn into_std_instant_on_tick_variant_panics() {
549
        // Documented: `into_std_instant` is `unreachable!()` for Tick instants.
550
        let _ = tick(1).into_std_instant();
551
    }
552

            
553
    // ========================================================================
554
    // SystemTick::new
555
    // ========================================================================
556

            
557
    #[test]
558
    fn system_tick_new_stores_the_counter_verbatim() {
559
        for n in [0_u64, 1, 0x0100, u64::MAX / 2, u64::MAX] {
560
            assert_eq!(SystemTick::new(n).tick_counter, n);
561
        }
562
        // Ordering follows the counter (used by Instant's derived Ord).
563
        assert!(SystemTick::new(0) < SystemTick::new(u64::MAX));
564
        assert_eq!(SystemTick::new(7), SystemTick::new(7));
565
    }
566

            
567
    // ========================================================================
568
    // InstantPtr: get / std_instant_clone / std_instant_drop
569
    // ========================================================================
570

            
571
    #[cfg(feature = "std")]
572
    #[test]
573
    fn instant_ptr_get_returns_the_wrapped_instant() {
574
        let base = StdInstant::now();
575
        let p: InstantPtr = base.into();
576
        assert_eq!(p.get(), base);
577
        // `get` is a copy, not a move: repeated reads stay stable.
578
        assert_eq!(p.get(), p.get());
579
        assert!(p.run_destructor);
580
        // Debug must not panic and must not be empty.
581
        assert!(!alloc::format!("{p:?}").is_empty());
582
    }
583

            
584
    #[cfg(feature = "std")]
585
    #[test]
586
    fn std_instant_clone_deep_copies_and_arms_the_destructor() {
587
        let base = StdInstant::now();
588
        let a: InstantPtr = base.into();
589
        let cloned = std_instant_clone(core::ptr::from_ref(&a));
590
        assert_eq!(cloned.get(), base);
591
        // The clone owns its OWN box (freeing both must not double-free).
592
        assert!(!core::ptr::eq(&**a.ptr, &**cloned.ptr));
593
        assert!(
594
            cloned.run_destructor,
595
            "clone handed back a disarmed destructor"
596
        );
597
        drop(cloned);
598
        // The source survives its clone being dropped.
599
        assert_eq!(a.get(), base);
600
    }
601

            
602
    #[cfg(feature = "std")]
603
    #[test]
604
    fn std_instant_drop_is_a_noop_even_for_null() {
605
        // The libstd destructor callback is deliberately empty: the Box is freed
606
        // by `InstantPtr::drop` under the `run_destructor` guard. Calling it with
607
        // a null pointer must therefore be harmless.
608
        std_instant_drop(core::ptr::null_mut());
609

            
610
        let mut p: InstantPtr = StdInstant::now().into();
611
        let before = p.get();
612
        std_instant_drop(core::ptr::from_mut(&mut p));
613
        // Value is untouched and still owned afterwards.
614
        assert_eq!(p.get(), before);
615
        assert!(p.run_destructor);
616
    }
617

            
618
    // ========================================================================
619
    // Duration::fmt (Display)
620
    // ========================================================================
621

            
622
    #[test]
623
    fn duration_display_tick_edge_values() {
624
        assert_eq!(alloc::format!("{}", tick_dur(0)), "0 ticks");
625
        assert_eq!(alloc::format!("{}", tick_dur(1)), "1 ticks");
626
        assert_eq!(
627
            alloc::format!("{}", tick_dur(u64::MAX)),
628
            "18446744073709551615 ticks"
629
        );
630
    }
631

            
632
    #[cfg(feature = "std")]
633
    #[test]
634
    fn duration_display_system_edge_values_do_not_panic() {
635
        // zero, sub-second, denormalized nanos and the absolute maximum all have
636
        // to format without panicking and without producing an empty string.
637
        for d in [
638
            sys_dur(0, 0),
639
            sys_dur(1, 500_000_000),
640
            sys_dur(0, u32::MAX),
641
            sys_dur(u64::MAX, NANOS_PER_SEC - 1),
642
            Duration::max(),
643
        ] {
644
            let s = alloc::format!("{d}");
645
            assert!(!s.is_empty());
646
            assert!(
647
                !s.ends_with("ticks"),
648
                "System duration formatted as ticks: {s}"
649
            );
650
        }
651
    }
652

            
653
    // ========================================================================
654
    // Duration::max / div / min / greater_than / smaller_than
655
    // ========================================================================
656

            
657
    #[cfg(feature = "std")]
658
    #[test]
659
    fn duration_max_is_the_upper_bound() {
660
        let m = Duration::max();
661
        assert_eq!(m, sys_dur(u64::MAX, NANOS_PER_SEC - 1));
662
        // Nothing of the same kind is greater than it...
663
        assert!(m.greater_than(&sys_dur(u64::MAX, NANOS_PER_SEC - 2)));
664
        assert!(m.greater_than(&sys_dur(0, 0)));
665
        // ... and it is not greater/smaller than itself.
666
        assert!(!m.greater_than(&m));
667
        assert!(!m.smaller_than(&m));
668
        // Converting the maximum back to std must not overflow-panic.
669
        let Duration::System(inner) = m else {
670
            panic!("Duration::max() is not a System duration under std")
671
        };
672
        assert_eq!(inner.get(), StdDuration::new(u64::MAX, NANOS_PER_SEC - 1));
673
    }
674

            
675
    #[test]
676
    fn duration_div_by_zero_yields_inf_or_nan_not_a_panic() {
677
        // 0/0 -> NaN, x/0 -> +inf. Neither may panic.
678
        assert!(tick_dur(0).div(&tick_dur(0)).is_nan());
679
        let inf = tick_dur(5).div(&tick_dur(0));
680
        assert!(inf.is_infinite() && inf.is_sign_positive());
681

            
682
        assert!(sys_dur(0, 0).div(&sys_dur(0, 0)).is_nan());
683
        let sinf = sys_dur(1, 0).div(&sys_dur(0, 0));
684
        assert!(sinf.is_infinite() && sinf.is_sign_positive());
685
    }
686

            
687
    #[test]
688
    fn duration_div_extremes_stay_finite_in_f32() {
689
        // u64::MAX / 1 ~= 1.8e19, comfortably inside f32 range: the f64 -> f32
690
        // narrowing must not produce inf.
691
        let r = tick_dur(u64::MAX).div(&tick_dur(1));
692
        assert!(r.is_finite(), "u64::MAX tick ratio overflowed f32: {r}");
693
        assert!(r > 1e19);
694
        // Identity ratios are exactly 1.0 for both kinds.
695
        assert_eq!(tick_dur(u64::MAX).div(&tick_dur(u64::MAX)), 1.0);
696
        assert_eq!(sys_dur(3, 0).div(&sys_dur(2, 0)), 1.5);
697
    }
698

            
699
    /// Cross-unit division converts instead of collapsing to `0.0`. 10 ticks is
700
    /// one sixth of a second, so the two ratios are reciprocals of each other —
701
    /// which is the property `0.0` both ways could never satisfy.
702
    #[test]
703
    fn duration_div_across_kinds_converts_both_ways() {
704
        assert!((sys_dur(1, 0).div(&tick_dur(10)) - 6.0).abs() < 1e-5);
705
        assert!((tick_dur(10).div(&sys_dur(1, 0)) - (1.0 / 6.0)).abs() < 1e-5);
706
    }
707

            
708
    #[test]
709
    fn duration_min_picks_the_smaller_of_the_same_kind() {
710
        assert_eq!(tick_dur(5).min(tick_dur(10)), tick_dur(5));
711
        assert_eq!(tick_dur(10).min(tick_dur(5)), tick_dur(5));
712
        assert_eq!(tick_dur(7).min(tick_dur(7)), tick_dur(7));
713
        assert_eq!(tick_dur(0).min(tick_dur(u64::MAX)), tick_dur(0));
714
        // Comparison no longer needs std: it is u128 nanosecond arithmetic.
715
        assert_eq!(sys_dur(1, 0).min(sys_dur(1, 1)), sys_dur(1, 0));
716
    }
717

            
718
    /// `min` is built on `smaller_than`, so it picks the genuinely shorter span
719
    /// across units and is COMMUTATIVE. It used to just return `other` whenever
720
    /// the units differed — so `a.min(b)` and `b.min(a)` disagreed, and the
721
    /// answer depended on argument order rather than on the durations.
722
    #[test]
723
    fn duration_min_across_kinds_picks_the_genuinely_shorter_span() {
724
        // 5 ticks is ~83ms, so it is shorter than a second either way round.
725
        assert_eq!(tick_dur(5).min(sys_dur(1, 0)), tick_dur(5));
726
        assert_eq!(sys_dur(1, 0).min(tick_dur(5)), tick_dur(5));
727
        // ...and 120 ticks is 2s, so the second wins either way round.
728
        assert_eq!(tick_dur(120).min(sys_dur(1, 0)), sys_dur(1, 0));
729
        assert_eq!(sys_dur(1, 0).min(tick_dur(120)), sys_dur(1, 0));
730
    }
731

            
732
    #[test]
733
    fn duration_comparison_is_a_strict_total_order_within_a_kind() {
734
        let mut pairs = alloc::vec![
735
            (tick_dur(0), tick_dur(u64::MAX)),
736
            (tick_dur(1), tick_dur(2))
737
        ];
738
        // System ordering no longer needs std: the comparison is u128 nanosecond
739
        // arithmetic. It used to defer to `StdDuration`, so on no_std it answered
740
        // `false` for every System pair — a total order that ordered nothing.
741
        pairs.extend_from_slice(&[
742
            (sys_dur(0, 0), sys_dur(u64::MAX, 0)),
743
            (sys_dur(1, 999_999_999), sys_dur(2, 0)),
744
        ]);
745

            
746
        for (a, b) in pairs {
747
            assert!(a.smaller_than(&b));
748
            assert!(b.greater_than(&a));
749
            assert!(!a.greater_than(&b));
750
            assert!(!b.smaller_than(&a));
751
        }
752
        // Equal values: neither greater nor smaller (holds for both kinds).
753
        let eq = tick_dur(4);
754
        assert!(!eq.greater_than(&eq));
755
        assert!(!eq.smaller_than(&eq));
756
        let eq_sys = sys_dur(4, 2);
757
        assert!(!eq_sys.greater_than(&eq_sys));
758
        assert!(!eq_sys.smaller_than(&eq_sys));
759
    }
760

            
761
    #[cfg(feature = "std")]
762
    #[test]
763
    fn duration_comparison_normalizes_denormalized_nanos() {
764
        // nanos == u32::MAX (> 1e9) is denormalized; the std conversion carries
765
        // it into secs, so {0, u32::MAX} == 4.294967295s > 4s.
766
        let denorm = sys_dur(0, u32::MAX);
767
        assert!(denorm.greater_than(&sys_dur(4, 0)));
768
        assert!(denorm.smaller_than(&sys_dur(5, 0)));
769
    }
770

            
771
    // ========================================================================
772
    // SystemTickDiff::div / SystemTimeDiff::div + as_secs_f64
773
    // ========================================================================
774

            
775
    #[test]
776
    fn system_tick_diff_div_edge_cases() {
777
        let zero = SystemTickDiff { tick_diff: 0 };
778
        let one = SystemTickDiff { tick_diff: 1 };
779
        let max = SystemTickDiff {
780
            tick_diff: u64::MAX,
781
        };
782

            
783
        assert!(zero.div(&zero).is_nan());
784
        assert!(one.div(&zero).is_infinite());
785
        assert_eq!(zero.div(&one), 0.0);
786
        assert_eq!(max.div(&max), 1.0);
787
        assert!(max.div(&one).is_finite());
788
        assert_eq!(
789
            SystemTickDiff { tick_diff: 5 }.div(&SystemTickDiff { tick_diff: 10 }),
790
            0.5
791
        );
792
    }
793

            
794
    #[test]
795
    fn system_time_diff_as_secs_f64_is_exact_for_representable_values() {
796
        assert_eq!(SystemTimeDiff { secs: 0, nanos: 0 }.as_secs_f64(), 0.0);
797
        assert_eq!(
798
            SystemTimeDiff {
799
                secs: 1,
800
                nanos: 500_000_000
801
            }
802
            .as_secs_f64(),
803
            1.5
804
        );
805
        assert_eq!(
806
            SystemTimeDiff {
807
                secs: 0,
808
                nanos: 500_000_000
809
            }
810
            .as_secs_f64(),
811
            0.5
812
        );
813
        // Extremes stay finite (u64::MAX secs ~= 1.8e19, well inside f64).
814
        let huge = SystemTimeDiff {
815
            secs: u64::MAX,
816
            nanos: NANOS_PER_SEC - 1,
817
        };
818
        assert!(huge.as_secs_f64().is_finite());
819
        assert!(huge.as_secs_f64() > 1e19);
820
        // Monotone in secs.
821
        assert!(
822
            SystemTimeDiff::from_secs(2).as_secs_f64() > SystemTimeDiff::from_secs(1).as_secs_f64()
823
        );
824
    }
825

            
826
    #[test]
827
    fn system_time_diff_div_edge_cases() {
828
        let zero = SystemTimeDiff { secs: 0, nanos: 0 };
829
        let one = SystemTimeDiff::from_secs(1);
830
        let half = SystemTimeDiff {
831
            secs: 0,
832
            nanos: 500_000_000,
833
        };
834

            
835
        assert!(zero.div(&zero).is_nan());
836
        assert!(one.div(&zero).is_infinite());
837
        assert_eq!(zero.div(&one), 0.0);
838
        assert_eq!(one.div(&one), 1.0);
839
        assert_eq!(one.div(&half), 2.0);
840
        let max = SystemTimeDiff {
841
            secs: u64::MAX,
842
            nanos: NANOS_PER_SEC - 1,
843
        };
844
        assert_eq!(max.div(&max), 1.0);
845
        assert!(max.div(&one).is_finite());
846
    }
847

            
848
    // ========================================================================
849
    // SystemTimeDiff constructors: from_secs / from_millis / from_nanos
850
    // ========================================================================
851

            
852
    #[test]
853
    fn from_secs_invariants() {
854
        for s in [0_u64, 1, 1_000, u64::MAX] {
855
            let d = SystemTimeDiff::from_secs(s);
856
            assert_eq!(d.secs, s);
857
            assert_eq!(d.nanos, 0, "from_secs must leave nanos at zero");
858
        }
859
    }
860

            
861
    #[test]
862
    fn from_millis_normalizes_and_keeps_nanos_in_range() {
863
        assert_eq!(
864
            SystemTimeDiff::from_millis(0),
865
            SystemTimeDiff { secs: 0, nanos: 0 }
866
        );
867
        assert_eq!(
868
            SystemTimeDiff::from_millis(999),
869
            SystemTimeDiff {
870
                secs: 0,
871
                nanos: 999_000_000
872
            }
873
        );
874
        assert_eq!(
875
            SystemTimeDiff::from_millis(1_000),
876
            SystemTimeDiff { secs: 1, nanos: 0 }
877
        );
878
        assert_eq!(
879
            SystemTimeDiff::from_millis(1_500),
880
            SystemTimeDiff {
881
                secs: 1,
882
                nanos: 500_000_000
883
            }
884
        );
885
        // u64::MAX millis must not overflow the u32 nanos field.
886
        let max = SystemTimeDiff::from_millis(u64::MAX);
887
        assert!(
888
            max.nanos < NANOS_PER_SEC,
889
            "from_millis produced denormalized nanos"
890
        );
891
        assert_eq!(max.secs, u64::MAX / MILLIS_PER_SEC);
892
    }
893

            
894
    #[test]
895
    fn from_nanos_normalizes_and_keeps_nanos_in_range() {
896
        assert_eq!(
897
            SystemTimeDiff::from_nanos(0),
898
            SystemTimeDiff { secs: 0, nanos: 0 }
899
        );
900
        assert_eq!(
901
            SystemTimeDiff::from_nanos(999_999_999),
902
            SystemTimeDiff {
903
                secs: 0,
904
                nanos: 999_999_999
905
            }
906
        );
907
        assert_eq!(
908
            SystemTimeDiff::from_nanos(1_000_000_000),
909
            SystemTimeDiff { secs: 1, nanos: 0 }
910
        );
911
        for n in [0_u64, 1, 999_999_999, 1_000_000_001, u64::MAX] {
912
            let d = SystemTimeDiff::from_nanos(n);
913
            assert!(
914
                d.nanos < NANOS_PER_SEC,
915
                "from_nanos({n}) produced denormalized nanos"
916
            );
917
            // Lossless round-trip: secs * 1e9 + nanos == n (checked in u128).
918
            let back = u128::from(d.secs) * u128::from(NANOS_PER_SEC) + u128::from(d.nanos);
919
            assert_eq!(back, u128::from(n), "from_nanos({n}) lost information");
920
        }
921
    }
922

            
923
    // ========================================================================
924
    // Round-trip: from_millis <-> millis
925
    // ========================================================================
926

            
927
    #[test]
928
    fn millis_round_trips_through_from_millis() {
929
        // Exact for every whole-millisecond value, INCLUDING u64::MAX (where
930
        // `secs * 1000 + 615` lands exactly on u64::MAX without saturating).
931
        for m in [0_u64, 1, 999, 1_000, 1_500, 86_400_000, u64::MAX] {
932
            assert_eq!(
933
                SystemTimeDiff::from_millis(m).millis(),
934
                m,
935
                "from_millis({m}).millis() is not lossless"
936
            );
937
        }
938
    }
939

            
940
    #[test]
941
    fn millis_truncates_and_saturates_instead_of_panicking() {
942
        // Sub-millisecond nanos truncate towards zero.
943
        assert_eq!(
944
            SystemTimeDiff {
945
                secs: 0,
946
                nanos: 999_999
947
            }
948
            .millis(),
949
            0
950
        );
951
        assert_eq!(
952
            SystemTimeDiff {
953
                secs: 0,
954
                nanos: 999_999_999
955
            }
956
            .millis(),
957
            999
958
        );
959
        // secs * 1000 overflows u64 -> saturate at u64::MAX, no panic.
960
        assert_eq!(
961
            SystemTimeDiff {
962
                secs: u64::MAX,
963
                nanos: 0
964
            }
965
            .millis(),
966
            u64::MAX
967
        );
968
        assert_eq!(
969
            SystemTimeDiff {
970
                secs: u64::MAX,
971
                nanos: NANOS_PER_SEC - 1
972
            }
973
            .millis(),
974
            u64::MAX
975
        );
976
        assert_eq!(
977
            SystemTimeDiff::from_secs(u64::MAX / 1_000).millis(),
978
            (u64::MAX / 1_000) * 1_000
979
        );
980
    }
981

            
982
    // ========================================================================
983
    // SystemTimeDiff::checked_add
984
    // ========================================================================
985

            
986
    #[test]
987
    fn checked_add_carries_nanos_into_secs() {
988
        let a = SystemTimeDiff {
989
            secs: 0,
990
            nanos: 999_999_999,
991
        };
992
        let sum = a.checked_add(a).expect("0.999s + 0.999s must not overflow");
993
        assert_eq!(
994
            sum,
995
            SystemTimeDiff {
996
                secs: 1,
997
                nanos: 999_999_998
998
            }
999
        );
        // Exactly one second of nanos carries cleanly.
        let b = SystemTimeDiff {
            secs: 1,
            nanos: 500_000_000,
        };
        assert_eq!(b.checked_add(b), Some(SystemTimeDiff { secs: 3, nanos: 0 }));
    }
    #[test]
    fn checked_add_returns_none_on_overflow_instead_of_panicking() {
        let max_secs = SystemTimeDiff {
            secs: u64::MAX,
            nanos: 0,
        };
        // secs overflow
        assert_eq!(max_secs.checked_add(SystemTimeDiff::from_secs(1)), None);
        // secs at max, nanos still fit -> Some
        assert_eq!(
            max_secs.checked_add(SystemTimeDiff {
                secs: 0,
                nanos: NANOS_PER_SEC - 1
            }),
            Some(SystemTimeDiff {
                secs: u64::MAX,
                nanos: NANOS_PER_SEC - 1
            })
        );
        // overflow that only happens because of the nanos CARRY
        let brim = SystemTimeDiff {
            secs: u64::MAX,
            nanos: NANOS_PER_SEC - 1,
        };
        assert_eq!(brim.checked_add(SystemTimeDiff { secs: 0, nanos: 1 }), None);
    }
    #[test]
    fn checked_add_identity_and_commutativity() {
        let zero = SystemTimeDiff { secs: 0, nanos: 0 };
        for d in [
            SystemTimeDiff::from_secs(0),
            SystemTimeDiff::from_millis(1_500),
            SystemTimeDiff::from_nanos(u64::MAX),
            SystemTimeDiff {
                secs: u64::MAX,
                nanos: 0,
            },
        ] {
            assert_eq!(d.checked_add(zero), Some(d));
            assert_eq!(zero.checked_add(d), Some(d));
            // a + b == b + a for well-formed operands
            let other = SystemTimeDiff::from_millis(750);
            assert_eq!(d.checked_add(other), other.checked_add(d));
        }
    }
    // ========================================================================
    // SystemTimeDiff::get  (std::time::Duration conversion round-trip)
    // ========================================================================
    #[cfg(feature = "std")]
    #[test]
    fn system_time_diff_get_round_trips_std_duration() {
        for std_d in [
            StdDuration::ZERO,
            StdDuration::from_millis(1_500),
            StdDuration::from_nanos(1),
            StdDuration::new(u64::MAX, NANOS_PER_SEC - 1),
        ] {
            let mid: SystemTimeDiff = std_d.into();
            assert_eq!(
                mid.get(),
                std_d,
                "StdDuration -> SystemTimeDiff -> StdDuration lost data"
            );
        }
    }
    #[cfg(feature = "std")]
    #[test]
    fn system_time_diff_get_on_edge_values_does_not_panic() {
        assert_eq!(
            SystemTimeDiff { secs: 0, nanos: 0 }.get(),
            StdDuration::ZERO
        );
        // secs at max with zero nanos: no carry, so no overflow in Duration::new.
        assert_eq!(
            SystemTimeDiff::from_secs(u64::MAX).get(),
            StdDuration::new(u64::MAX, 0)
        );
        // Denormalized nanos (>= 1e9) are carried by Duration::new, not rejected.
        assert_eq!(
            SystemTimeDiff {
                secs: 0,
                nanos: u32::MAX
            }
            .get(),
            StdDuration::new(0, u32::MAX)
        );
    }
    // ========================================================================
    // ThreadReceiver: new / get_ctx / recv / clone
    // ========================================================================
    #[cfg(feature = "std")]
    extern "C" fn test_thread_recv(ptr: *const c_void) -> OptionThreadSendMsg {
        // Mirrors the real callback: `ThreadReceiver::recv` hands over a pointer
        // to the boxed `Receiver<ThreadSendMsg>` inside `ThreadReceiverInner`.
        let receiver = unsafe { &*(ptr.cast::<Receiver<ThreadSendMsg>>()) };
        receiver.try_recv().ok().into()
    }
    #[cfg(feature = "std")]
    const extern "C" fn test_thread_recv_destructor(_: *mut ThreadReceiverInner) {}
    #[cfg(feature = "std")]
    fn test_receiver() -> (Sender<ThreadSendMsg>, ThreadReceiver) {
        let (tx, rx) = std::sync::mpsc::channel::<ThreadSendMsg>();
        let inner = ThreadReceiverInner {
            ptr: Box::new(rx),
            recv_fn: ThreadRecvCallback {
                cb: test_thread_recv,
            },
            destructor: ThreadReceiverDestructorCallback {
                cb: test_thread_recv_destructor,
            },
        };
        (tx, ThreadReceiver::new(inner))
    }
    #[cfg(feature = "std")]
    #[test]
    fn thread_receiver_new_arms_destructor_and_has_no_ctx() {
        let (_tx, r) = test_receiver();
        assert!(
            r.run_destructor,
            "ThreadReceiver::new left the destructor disarmed"
        );
        assert!(
            r.get_ctx().is_none(),
            "a fresh receiver must have no FFI context"
        );
    }
    #[cfg(feature = "std")]
    #[test]
    fn thread_receiver_recv_on_empty_and_disconnected_channel_is_none() {
        let (tx, mut r) = test_receiver();
        // Empty channel -> None (must not block / panic).
        assert!(r.recv().is_none());
        // Disconnected channel -> still None, not a panic.
        drop(tx);
        assert!(r.recv().is_none());
        assert!(r.recv().is_none());
    }
    #[cfg(feature = "std")]
    #[test]
    fn thread_receiver_recv_delivers_messages_in_order() {
        let (tx, mut r) = test_receiver();
        tx.send(ThreadSendMsg::Tick).unwrap();
        tx.send(ThreadSendMsg::Custom(RefAny::new(42_u32))).unwrap();
        tx.send(ThreadSendMsg::TerminateThread).unwrap();
        assert_eq!(r.recv(), OptionThreadSendMsg::Some(ThreadSendMsg::Tick));
        assert!(matches!(
            r.recv(),
            OptionThreadSendMsg::Some(ThreadSendMsg::Custom(_))
        ));
        assert_eq!(
            r.recv(),
            OptionThreadSendMsg::Some(ThreadSendMsg::TerminateThread)
        );
        // Drained.
        assert!(r.recv().is_none());
    }
    #[cfg(feature = "std")]
    #[test]
    fn thread_receiver_clone_shares_the_same_channel() {
        let (tx, mut a) = test_receiver();
        let mut b = a.clone();
        assert!(b.run_destructor);
        tx.send(ThreadSendMsg::Tick).unwrap();
        // The clone shares the Arc<Mutex<..>>: whichever half receives first
        // consumes the message; the other must see an empty channel, not a
        // duplicate and not a deadlock.
        assert_eq!(a.recv(), OptionThreadSendMsg::Some(ThreadSendMsg::Tick));
        assert!(b.recv().is_none());
        tx.send(ThreadSendMsg::TerminateThread).unwrap();
        assert_eq!(
            b.recv(),
            OptionThreadSendMsg::Some(ThreadSendMsg::TerminateThread)
        );
        assert!(a.recv().is_none());
    }
    #[cfg(feature = "std")]
    #[test]
    fn thread_receiver_get_ctx_clones_rather_than_takes() {
        let (_tx, mut r) = test_receiver();
        r.ctx = OptionRefAny::Some(RefAny::new(7_u64));
        // Repeated reads must all succeed -- `get_ctx` clones the RefAny (refcount
        // bump); a take/move would leave the second call empty.
        assert!(r.get_ctx().is_some());
        assert!(r.get_ctx().is_some());
        let held = r.get_ctx();
        drop(r);
        // The cloned handle outlives the receiver it came from.
        assert!(held.is_some());
    }
}