libsw-core 0.3.2

Comprehensive stopwatch library
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
// libsw: stopwatch library (tests)
// copyright (C) 2022-2023 Ula Shipman <ula.hello@mailbox.org>
// licensed under MIT OR Apache-2.0

/* TODOO: not designed for approximate time but coarsetime is
 * supported. it fails some of these tests; grep for @depends-exact */

use ::core::hash::{Hash, Hasher};
use ::core::time::Duration;
use ::std::collections::hash_map::DefaultHasher;
use ::std::thread;

use crate::Instant;

/* TODO: manually changing these aliases if i want to test all supported
 * `Instant` impls is annoying */
type I = std::time::Instant;
type Stopwatch = crate::stopwatch::Stopwatch<I>;

const DELAY: Duration = Duration::from_millis(100);

#[test]
fn default() {
    assert_eq!(Stopwatch::default(), Stopwatch::new());
}

#[test]
fn new() {
    let now = I::now();
    assert_eq!(Stopwatch::new().elapsed(), Duration::ZERO);
    assert_eq!(Stopwatch::new_started().elapsed, Duration::ZERO);
    assert_eq!(
        Stopwatch::new_started_at(now).elapsed_at(now),
        Duration::ZERO
    );
}

#[test]
fn is_running() {
    let mut sw = Stopwatch::new();
    assert!(!sw.is_running());

    sw.start();
    assert!(sw.is_running());

    sw.stop();
    assert!(!sw.is_running());
}

#[test]
fn is_stopped() {
    let mut sw = Stopwatch::new();
    assert!(sw.is_stopped());

    sw.start();
    assert!(!sw.is_stopped());

    sw.stop();
    assert!(sw.is_stopped());
}

#[test]
fn toggle() {
    let mut sw = Stopwatch::new();
    assert!(sw.is_stopped());

    sw.toggle();
    assert!(sw.is_running());

    sw.toggle();
    assert!(sw.is_stopped());
}

#[test]
fn checked_toggle() {
    let mut sw = Stopwatch::new();
    assert!(sw.is_stopped());

    assert!(sw.checked_toggle());
    assert!(sw.is_running());

    assert!(sw.checked_toggle());
    assert!(sw.is_stopped());
}

#[test]
fn reset() {
    let mut sw = Stopwatch::new_started();
    thread::sleep(DELAY);

    sw.stop();
    sw.start();
    sw.reset();

    assert_eq!(sw, Stopwatch::new());
}

#[test]
fn set() {
    let mut sw = Stopwatch::new_started();
    sw.set(DELAY);
    assert_eq!(sw, Stopwatch::with_elapsed(DELAY));
}

#[test]
fn set_in_place() {
    let mut sw = Stopwatch::new_started();
    sw.set_in_place(DELAY);
    assert!(sw.is_running());
    assert!(sw.elapsed() >= DELAY);

    thread::sleep(DELAY);

    sw.set_in_place(DELAY);
    assert!(sw.is_running());
    assert!(sw.elapsed() < DELAY * 2);
}

#[test]
fn replace() {
    let mut sw = Stopwatch::with_elapsed_started(DELAY);
    let prev = sw.replace(DELAY * 2);

    assert!(sw.is_stopped());
    assert!(prev >= DELAY);
    assert_eq!(sw.elapsed(), DELAY * 2);
}

#[test]
fn add() {
    let mut sw = Stopwatch::new();

    sw += DELAY;
    sw.start();
    sw += DELAY;
    sw.stop();
    sw += DELAY;

    assert!(sw.elapsed() >= DELAY * 3);
}

#[test]
fn sub() {
    assert_eq!(
        Stopwatch::with_elapsed(DELAY * 3) - DELAY,
        Stopwatch::with_elapsed(DELAY * 2)
    );
}

#[test]
fn sub_at() {
    let mut sw = Stopwatch::with_elapsed_started(DELAY * 3);
    thread::sleep(DELAY);
    let now = I::now();
    let old_elapsed = sw.elapsed_at(now);
    sw = sw.saturating_sub_at(DELAY * 3, now);
    thread::sleep(DELAY);
    assert_eq!(sw.elapsed_at(now), old_elapsed - DELAY * 3);
}

#[test]
#[should_panic]
fn add_overloaded_overflow() {
    _ = Stopwatch::with_elapsed(Duration::MAX) + DELAY;
}

#[test]
#[should_panic]
fn sub_overloaded_overflow() {
    _ = Stopwatch::new() - DELAY;
}

#[test]
fn checked_add() {
    let mut sw = Stopwatch::new();

    sw = sw.checked_add(DELAY).unwrap();
    sw.start();
    sw = sw.checked_add(DELAY).unwrap();
    sw.stop();
    sw = sw.checked_add(DELAY).unwrap();

    assert!(sw.elapsed() >= DELAY * 3);
}

#[test]
fn checked_sub() {
    assert_eq!(
        Stopwatch::with_elapsed(DELAY * 3)
            .checked_sub(DELAY)
            .unwrap(),
        Stopwatch::with_elapsed(DELAY * 2)
    );

    let start = Some(I::now());
    assert_eq!(
        Stopwatch::from_raw(DELAY * 3, start)
            .checked_sub(DELAY)
            .unwrap(),
        Stopwatch::from_raw(DELAY * 2, start)
    );
}

#[test]
fn checked_add_overflow() {
    assert_eq!(
        Stopwatch::new().checked_add(Duration::MAX).unwrap(),
        Stopwatch::with_elapsed(Duration::MAX),
    );
    assert_eq!(
        Stopwatch::with_elapsed(DELAY).checked_add(Duration::MAX),
        None,
    );
}

#[test]
fn checked_sub_overflow() {
    assert_eq!(
        Stopwatch::with_elapsed(Duration::MAX)
            .checked_sub(Duration::MAX)
            .unwrap(),
        Stopwatch::new(),
    );
    assert_eq!(Stopwatch::with_elapsed(DELAY).checked_sub(DELAY * 2), None);
}

#[test]
fn saturating_sub_overflow() {
    let mut sw = Stopwatch::with_elapsed(Duration::MAX);
    assert_eq!(sw.checked_elapsed(), Some(Duration::MAX));

    let anchor0 = I::now();
    let anchor1 = Instant::checked_add(&anchor0, DELAY * 2).unwrap();
    sw.start_at(anchor0);

    assert_eq!(sw.checked_elapsed_at(anchor0), Some(Duration::MAX));
    assert_eq!(sw.checked_elapsed_at(anchor1), None);

    sw = sw.saturating_sub_at(DELAY, anchor1);
    assert_eq!(sw.checked_elapsed_at(anchor0), Some(Duration::MAX - DELAY)); // when elapsed overflows, subtraction occurs "after clamping"
}

// @depends-exact
#[test]
fn sane_elapsed_while_stopped() {
    let mut sw = Stopwatch::new_started();
    thread::sleep(DELAY);
    sw.stop();

    assert!(sw.elapsed() >= DELAY);
}

// @depends-exact
#[test]
fn sane_elapsed_while_running() {
    let sw = Stopwatch::new_started();
    thread::sleep(DELAY);

    assert!(sw.elapsed() >= DELAY);
}

#[test]
fn sync_before_sub_saturating() {
    let mut sw = Stopwatch::new_started();
    thread::sleep(DELAY);
    sw = sw.saturating_sub(DELAY);
    assert!(sw.elapsed() < DELAY);
}

#[test]
fn sync_before_sub_checked() {
    let mut sw = Stopwatch::new_started();
    thread::sleep(DELAY);
    sw = sw.checked_sub(DELAY).unwrap(); // @depends-exact
    assert!(sw.elapsed() < DELAY);
}

#[test]
fn sync_before_sub_checked_overflow() {
    let sw = Stopwatch::with_elapsed_started(Duration::MAX);
    thread::sleep(DELAY);
    assert_eq!(sw.checked_sub(DELAY * 2), None);
}

#[test]
fn sub_at_earlier_anchor_behavior() {
    let mut sw = Stopwatch::new();

    let earlier = I::now();
    thread::sleep(DELAY);
    let later = I::now();
    thread::sleep(DELAY);

    sw.start_at(later);

    for dur in (0..10).map(Duration::from_secs) {
        assert_eq!(
            sw.checked_sub_at(dur, earlier),
            sw.checked_sub_at(dur, later)
        );
        assert!(sw.is_running());
        assert_eq!(
            sw.saturating_sub_at(dur, earlier),
            sw.saturating_sub_at(dur, later)
        );
        assert!(sw.is_running());
    }
}

#[test]
fn elapsed_at_saturates() {
    let sw = Stopwatch::with_elapsed_started(DELAY);
    let now = I::now();
    assert_eq!(
        sw.elapsed_at(Instant::checked_sub(&now, DELAY * 2).unwrap()),
        DELAY
    );
}

#[test]
fn checked_elapsed_overflows() {
    let sw = Stopwatch::with_elapsed_started(Duration::MAX);
    thread::sleep(DELAY);
    assert_eq!(sw.checked_elapsed(), None);
}

#[test]
fn start_in_future() {
    let mut sw = Stopwatch::new();
    let now = I::now();
    sw.start_at(Instant::checked_add(&now, DELAY * 2).unwrap());

    thread::sleep(DELAY);
    sw.stop();
    assert_eq!(sw.elapsed(), Duration::ZERO);
}

#[test]
fn stop_before_last_start() {
    let mut sw = Stopwatch::with_elapsed(DELAY);
    let start = I::now();
    let old_elapsed = sw.elapsed();

    sw.start_at(start);
    thread::sleep(DELAY);
    sw.stop_at(Instant::checked_sub(&start, DELAY).unwrap());

    assert_eq!(old_elapsed, sw.elapsed());
}

// @depends-exact
#[test]
fn repeat_start() {
    let mut sw = Stopwatch::with_elapsed(DELAY);
    let anchor1 = I::now();
    let anchor2 = Instant::checked_add(&anchor1, DELAY).unwrap();
    sw.start_at(anchor1);
    assert!(sw.is_running());
    assert_eq!(sw.elapsed_at(anchor2), DELAY * 2);
    sw.start_at(anchor2);
    assert_eq!(sw.elapsed_at(anchor2), DELAY);
    assert!(sw.is_running());
}

// @depends-exact
#[test]
fn repeat_stop() {
    let mut sw = Stopwatch::with_elapsed(DELAY);
    let anchor1 = I::now();
    let anchor2 = Instant::checked_add(&anchor1, DELAY).unwrap();
    sw.start_at(anchor1);
    for _ in 0..2 {
        sw.stop_at(anchor2);
        assert!(sw.is_stopped());
        assert_eq!(sw.elapsed(), DELAY * 2);
    }
}

#[test]
fn checked_stop_overflows() {
    let mut sw = Stopwatch::with_elapsed_started(Duration::MAX);
    thread::sleep(DELAY);
    assert!(sw.checked_elapsed().is_none());
    assert!(!sw.checked_stop());
    assert!(sw.is_running());
    sw.stop();
    assert!(sw.checked_stop()); // no overflow, not running
}

#[test]
fn checked_stop_stops() {
    let mut sw = Stopwatch::new_started();
    assert!(sw.is_running());
    assert!(sw.checked_stop());
    assert!(sw.is_stopped());
    assert!(sw.checked_stop()); // no overflow, not running
}

#[test]
fn eq_properties() {
    for [a, b, c] in mixed_stopwatches() {
        dbg!(a, b, c);

        // reflexive
        assert!(a == a);
        assert!(b == b);
        assert!(c == c);

        // symmetric
        assert_eq!(a == b, b == a);
        assert_eq!(a == c, c == a);
        assert_eq!(b == c, c == b);

        // transitive
        if (a == b) && (b == c) {
            assert_eq!(a, c);
        }
        if (b == a) && (a == c) {
            assert_eq!(b, c);
        }
        if (a == c) && (c == b) {
            assert_eq!(a, b);
        }
    }
}

#[test]
fn eq_running() {
    // whatever is compared shouldn't depend on the time of observation
    let now = I::now();
    let sw_1 = Stopwatch::new_started_at(now);
    let sw_2 = Stopwatch::new_started_at(now);
    let sw_3 = Stopwatch::from_raw(DELAY, Some(now));
    assert_eq!(sw_1, sw_2);
    assert_ne!(sw_1, sw_3);
}

#[test]
fn eq_correct() {
    assert_ne!(Stopwatch::new(), Stopwatch::new_started());
    assert_ne!(
        Stopwatch::with_elapsed(Duration::from_secs(1)),
        Stopwatch::with_elapsed(Duration::from_secs(2)),
    );

    let mut sw_1 = Stopwatch::new();
    let mut sw_2 = Stopwatch::new();
    let start = I::now();
    sw_1.start_at(start);
    sw_2.start_at(start);
    assert_eq!(sw_1, sw_2);
}

#[test]
fn partial_eq_use_of_unnormalized_instant() {
    /// Returns an instant that is pretty close to the epoch, and a duration reaching past it.
    fn approximately_the_epoch(search_start: I) -> (I, Duration) {
        let mut dt = Duration::MAX;
        let mut t = search_start;
        while Instant::checked_sub(&t, dt).is_some() || Instant::checked_add(&t, dt).is_none() {
            while let Some(new_t) = Instant::checked_sub(&t, dt) {
                t = new_t;
            }
            dt /= 2;
        }
        (t, dt)
    }

    let (anchor1, dt) = approximately_the_epoch(I::now());
    let anchor2 = Instant::checked_add(&anchor1, dt).unwrap();
    assert_eq!(None, Instant::checked_sub(&anchor1, dt));
    assert_eq!(anchor1, Instant::checked_sub(&anchor2, dt).unwrap()); // @depends-exact

    assert_ne!(
        Stopwatch::from_raw(dt, Some(anchor1)),
        Stopwatch::from_raw(dt, Some(anchor2)),
    );
}

#[test]
fn partial_eq_saturation_disqualifies_elapsed_as_viable_method() {
    let anchor0 = I::now();
    let anchor1 = Instant::checked_add(&anchor0, DELAY).unwrap();
    let anchor2 = Instant::checked_add(&anchor1, DELAY).unwrap();
    //     NOW
    // <----|--------->
    //      0   1   2
    let sw_1 = Stopwatch::new_started_at(anchor1);
    let sw_2 = Stopwatch::new_started_at(anchor2);

    // yes,
    assert_eq!(sw_1.elapsed_at(anchor0), sw_2.elapsed_at(anchor0));
    assert_eq!(sw_1.is_running(), sw_2.is_running());

    // but...
    assert_ne!(sw_1, sw_2);
}

#[test]
fn partial_eq_mixed_state() {
    let anchor1 = I::now();
    let anchor2 = Instant::checked_add(&anchor1, DELAY).unwrap();
    let sw_0 = Stopwatch::new();
    let sw_1 = Stopwatch::new_started_at(anchor1);
    let sw_2 = Stopwatch::new_started_at(anchor2);

    // yes,
    assert_eq!(sw_0.elapsed_at(anchor1), sw_1.elapsed_at(anchor1));
    assert_eq!(sw_0.elapsed_at(anchor1), sw_2.elapsed_at(anchor1));
    assert_eq!(sw_1.elapsed_at(anchor1), sw_2.elapsed_at(anchor1));

    // but...
    assert_ne!(sw_0, sw_1);
    assert_ne!(sw_0, sw_2);
    assert_ne!(sw_1, sw_2);
}

/* NOTE: currently, the canonicalized form for stopwatches s.t.
 * `start.checked_sub(elapsed).is_none()` carries no information, so they are
 * all equal. this test is written for a future with multiple equivalence
 * classes of said stopwatches, where they can be compared as if `checked_sub`
 * didn't overflow. */
#[ignore]
#[test]
fn unbounded_eq_future() {
    let anchor = I::now();
    let sw_1 = Stopwatch::from_raw(Duration::MAX, Some(anchor));
    let sw_2 = Stopwatch::from_raw(
        Duration::MAX - DELAY,
        Some(Instant::checked_sub(&anchor, DELAY).unwrap()),
    );
    let sw_3 = Stopwatch::from_raw(Duration::MAX - DELAY, Some(anchor));

    assert_eq!(sw_1, sw_2);
    assert_ne!(sw_1, sw_3);
    assert_ne!(sw_2, sw_3);
}

#[test]
fn unbounded_eq_status_quo() {
    let overflowing_1;
    let overflowing_2;
    {
        let start_1 = I::now();
        let start_2 = Instant::checked_sub(&start_1, DELAY).unwrap();
        overflowing_1 = Stopwatch::from_raw(Duration::MAX, Some(start_1));
        overflowing_2 = Stopwatch::from_raw(Duration::MAX, Some(start_2));
    }

    assert_eq!(overflowing_1, overflowing_2);
}

#[test]
fn hash_and_eq() {
    for [sw_1, sw_2, sw_3] in mixed_stopwatches() {
        let mut hasher_1 = DefaultHasher::new();
        let mut hasher_2 = DefaultHasher::new();
        let mut hasher_3 = DefaultHasher::new();

        sw_1.hash(&mut hasher_1);
        sw_2.hash(&mut hasher_2);
        sw_3.hash(&mut hasher_3);

        dbg!(sw_1, sw_2, sw_3);

        // > When implementing both Hash and Eq, it is important that the following property holds:
        // > k1 == k2 -> hash(k1) == hash(k2)
        assert_eq!(sw_1 == sw_2, hasher_1.finish() == hasher_2.finish());
        assert_eq!(sw_1 == sw_3, hasher_1.finish() == hasher_3.finish());
        assert_eq!(sw_2 == sw_3, hasher_2.finish() == hasher_3.finish());
    }
}

#[test]
fn hash_running() {
    let now = I::now();
    let sw_1 = Stopwatch::new_started_at(now);
    let sw_2 = Stopwatch::new_started_at(now);
    let sw_3 = Stopwatch::from_raw(DELAY, Some(now));

    let mut hasher_1 = DefaultHasher::new();
    let mut hasher_2 = DefaultHasher::new();
    let mut hasher_3 = DefaultHasher::new();

    sw_1.hash(&mut hasher_1);
    sw_2.hash(&mut hasher_2);
    sw_3.hash(&mut hasher_3);

    // whatever is hashed shouldn't depend on the time of observation
    assert_eq!(hasher_1.finish(), hasher_2.finish());
    assert_ne!(hasher_1.finish(), hasher_3.finish());
}

fn mixed_stopwatches() -> [[Stopwatch; 3]; 11] {
    let crafted_1;
    let crafted_2;
    {
        let mut elapsed = Duration::from_secs(10);
        let mut start = I::now();
        crafted_1 = Stopwatch::from_raw(elapsed, Some(start));

        elapsed -= Duration::from_secs(1);
        start = Instant::checked_sub(&start, Duration::from_secs(1)).unwrap();
        crafted_2 = Stopwatch::from_raw(elapsed, Some(start));
    }
    assert_eq!(crafted_1, crafted_2);

    let started = Stopwatch::new_started();
    let started_elapsed_1 = Stopwatch::with_elapsed_started(Duration::from_secs(1));
    let started_elapsed_2 = Stopwatch::with_elapsed_started(Duration::from_secs(2));

    let overflowing_1;
    let overflowing_2;
    {
        let start_1 = I::now();
        let start_2 = Instant::checked_sub(&start_1, DELAY).unwrap();
        overflowing_1 = Stopwatch::from_raw(Duration::MAX, Some(start_1));
        overflowing_2 = Stopwatch::from_raw(Duration::MAX, Some(start_2));
    }

    [
        [Stopwatch::new(), Stopwatch::new(), Stopwatch::new()],
        [started, started, started],
        [started, Stopwatch::new(), Stopwatch::new()],
        [
            Stopwatch::with_elapsed(Duration::from_secs(1)),
            Stopwatch::with_elapsed(Duration::from_secs(1)),
            Stopwatch::with_elapsed(Duration::from_secs(1)),
        ],
        [started_elapsed_1, started_elapsed_1, started_elapsed_1],
        [started_elapsed_1, started_elapsed_2, started_elapsed_1],
        [overflowing_1, overflowing_2, started],
        [
            started_elapsed_1,
            Stopwatch::with_elapsed(Duration::from_secs(1)),
            Stopwatch::with_elapsed(Duration::from_secs(1)),
        ],
        [
            started_elapsed_2,
            Stopwatch::with_elapsed(Duration::from_secs(1)),
            Stopwatch::with_elapsed(Duration::from_secs(1)),
        ],
        [
            Stopwatch::with_elapsed(Duration::from_secs(1)),
            Stopwatch::with_elapsed(Duration::from_secs(2)),
            Stopwatch::with_elapsed(Duration::from_secs(3)),
        ],
        [crafted_1, crafted_2, Stopwatch::default()],
    ]
}