libsw 3.5.0

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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
// libsw: stopwatch library
// copyright (C) 2022-2023 Ula Shipman <ula.hello@mailbox.org>
// licensed under MIT OR Apache-2.0

use ::libsw_core::Stopwatch as CoreSw;

use ::core::fmt;
use ::core::hash::{Hash, Hasher};
use ::core::ops;
use ::core::time::Duration;

use crate::{Error, Guard, Instant};

/* TODO: methods that take an anchor could be changed to minimize calls to
 * Instant::now. currently we force the caller to evaluate it and pass it to
 * such methods, even if the value is used *conditionally* based on the state of
 * the stopwatch. it may be desirable to add functions that take a closure that
 * returns an instant so we can only call Instant::now when necessary. */

/// A stopwatch measures and accumulates elapsed time between starts and stops.
///
/// Stopwatches work with any type that implements [`Instant`].
#[derive(Clone, Copy)]
#[allow(clippy::module_name_repetitions)]
pub struct StopwatchImpl<I: Instant> {
    pub(crate) inner: CoreSw<I>,
}

impl<I: Instant> StopwatchImpl<I> {
    /// Returns a stopped stopwatch with zero elapsed time.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// let sw = Sw::new();
    /// assert!(sw.is_stopped());
    /// assert_eq!(sw.elapsed(), Duration::ZERO);
    /// ```
    #[must_use]
    pub const fn new() -> Self {
        Self::with_elapsed(Duration::ZERO)
    }

    /// Returns a running stopwatch initialized with zero elapsed time.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// let sw = Sw::new_started();
    /// assert!(sw.is_running());
    /// ```
    #[must_use]
    pub fn new_started() -> Self {
        Self::with_elapsed_started(Duration::ZERO)
    }

    /// Returns a stopwatch initialized with zero elapsed time, started at the
    /// given instant.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// # use std::time::Instant;
    /// let now = Instant::now();
    /// let sw_1 = Sw::new_started_at(now);
    /// let sw_2 = Sw::new_started_at(now);
    /// // they've both started at the same time
    /// assert_eq!(sw_1, sw_2);
    /// // (and had zero elapsed time when they started)
    /// assert_eq!(sw_1.elapsed_at(now), Duration::ZERO);
    /// ```
    #[must_use]
    pub const fn new_started_at(start: I) -> Self {
        Self::from_raw(Duration::ZERO, Some(start))
    }

    /// Returns a stopped stopwatch with the given elapsed time.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// let sw = Sw::with_elapsed(Duration::from_secs(1));
    /// assert!(sw.is_stopped());
    /// assert_eq!(sw.elapsed(), Duration::from_secs(1));
    /// ```
    #[must_use]
    pub const fn with_elapsed(elapsed: Duration) -> Self {
        Self::from_raw(elapsed, None)
    }

    /// Returns a running stopwatch initialized with the given elapsed time.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// let sw = Sw::with_elapsed_started(Duration::from_secs(1));
    /// assert!(sw.is_running());
    /// assert!(sw.elapsed() >= Duration::from_secs(1));
    /// ```
    #[must_use]
    pub fn with_elapsed_started(elapsed: Duration) -> Self {
        Self::from_raw(elapsed, Some(I::now()))
    }

    /// Returns a stopwatch from its raw parts.
    ///
    /// Internally, a `StopwatchImpl` combines a saved elapsed time and an
    /// instant which records the latest start time.
    ///
    /// While the start time is [`Some`], the stopwatch is running. When it
    /// stops, the time which has elapsed since the start time is added to the
    /// elapsed time, and the start time is set to [`None`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// let sw = Sw::from_raw(Duration::from_secs(1), None);
    /// assert!(sw.is_stopped());
    /// assert_eq!(sw.elapsed(), Duration::from_secs(1));
    /// ```
    ///
    /// # Notes
    ///
    /// It is possible to craft two stopwatches whose internal components
    /// differ, but are equal according to [`PartialEq`], [`Eq`], and [`Hash`].
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// # use std::time::Instant;
    /// let mut elapsed = Duration::from_secs(10);
    /// let mut start = Instant::now();
    /// let sw_1 = Sw::from_raw(elapsed, Some(start));
    /// let sw_2 = Sw::from_raw(
    ///     elapsed - Duration::from_secs(1),     // now `elapsed()` is 1s less
    ///     Some(start - Duration::from_secs(1)), // now with start pushed back, `elapsed()` is equal
    /// );
    ///
    /// // different components, but they are equal!
    /// assert_eq!(sw_1, sw_2);
    /// ```
    #[must_use]
    pub const fn from_raw(elapsed: Duration, start: Option<I>) -> Self {
        Self::from_core(CoreSw::from_raw(elapsed, start))
    }

    /// Constructs a `StopwatchImpl` from a [`libsw_core::Stopwatch`].
    pub const fn from_core(core_sw: CoreSw<I>) -> Self {
        Self { inner: core_sw }
    }

    /// Returns a [`libsw_core::Stopwatch`] with the same elapsed time and start.
    pub const fn to_core(self) -> CoreSw<I> {
        self.inner
    }

    /// Returns `true` if the stopwatch is running.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// let sw = Sw::new_started();
    /// assert!(sw.is_running());
    /// ```
    #[must_use]
    pub const fn is_running(&self) -> bool {
        self.inner.is_running()
    }

    /// Returns `true` if the stopwatch is stopped.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// let sw = Sw::new();
    /// assert!(sw.is_stopped());
    /// ```
    #[must_use]
    pub const fn is_stopped(&self) -> bool {
        self.inner.is_stopped()
    }

    /// Returns the total time elapsed. If overflow occurs, the elapsed time is
    /// saturated to [`Duration::MAX`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// # use std::thread;
    /// # fn main() -> libsw::Result<()> {
    /// let sw = Sw::new_started();
    /// thread::sleep(Duration::from_millis(100));
    /// assert!(sw.elapsed() >= Duration::from_millis(100));
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn elapsed(&self) -> Duration {
        self.inner.elapsed()
    }

    /// Returns the total time elapsed, measured as if the current time were
    /// `anchor`. If overflow occurs, the elapsed time is saturated to
    /// [`Duration::MAX`].
    ///
    /// # Notes
    ///
    /// `anchor` saturates to the last instant the stopwatch was started.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use std::time::Instant;
    /// let sw_1 = Sw::new_started();
    /// let sw_2 = sw_1.clone();
    /// let anchor = Instant::now();
    /// assert!(sw_1.elapsed_at(anchor) == sw_2.elapsed_at(anchor));
    /// ```
    #[must_use]
    pub fn elapsed_at(&self, anchor: I) -> Duration {
        self.inner.elapsed_at(anchor)
    }

    /// Computes the total time elapsed. If overflow occurred, returns [`None`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// # use std::thread;
    /// # fn main() -> libsw::Result<()> {
    /// let mut sw = Sw::new_started();
    /// thread::sleep(Duration::from_millis(100));
    /// assert!(sw.checked_elapsed().unwrap() >= Duration::from_millis(100));
    /// sw += Duration::MAX;
    /// assert!(sw.checked_elapsed().is_none());
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn checked_elapsed(&self) -> Option<Duration> {
        self.inner.checked_elapsed()
    }

    /// Computes the total time elapsed, measured as if the current time were
    /// `anchor`. If overflow occurred, returns [`None`].
    ///
    /// # Notes
    ///
    /// `anchor` saturates to the last instant the stopwatch was started.
    ///
    /// # Examples
    ///
    /// See the documentation for [`checked_elapsed`](Self::checked_elapsed) for
    /// a related example.
    #[must_use]
    pub fn checked_elapsed_at(&self, anchor: I) -> Option<Duration> {
        self.inner.checked_elapsed_at(anchor)
    }

    /// Starts measuring the time elapsed.
    ///
    /// # Errors
    ///
    /// Returns [`SwStart`](Error::SwStart) if the stopwatch is running.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// # use std::thread;
    /// let mut sw = Sw::new();
    /// assert!(sw.start().is_ok());
    /// assert!(sw.start().is_err());
    ///
    /// let then = sw.elapsed();
    /// thread::sleep(Duration::from_millis(100));
    /// let now = sw.elapsed();
    /// assert!(then != now);
    /// ```
    pub fn start(&mut self) -> crate::Result<()> {
        self.start_at(I::now())
    }

    /// Stops measuring the time elapsed since the last start.
    ///
    /// # Errors
    ///
    /// Returns [`SwStop`](Error::SwStop) if the stopwatch is already stopped.
    ///
    /// # Notes
    ///
    /// Overflows of the new elapsed time are saturated to [`Duration::MAX`].
    /// Use [`StopwatchImpl::checked_stop`] to explicitly check for overflow.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// # use std::thread;
    /// let mut sw = Sw::new_started();
    /// assert!(sw.stop().is_ok());
    /// assert!(sw.stop().is_err());
    ///
    /// let then = sw.elapsed();
    /// thread::sleep(Duration::from_millis(100));
    /// let now = sw.elapsed();
    /// assert!(then == now);
    /// ```
    #[inline]
    pub fn stop(&mut self) -> crate::Result<()> {
        self.stop_at(I::now())
    }

    /// Starts measuring the time elapsed as if the current time were `anchor`.
    ///
    /// # Errors
    ///
    /// Returns [`SwStart`](Error::SwStart) if the stopwatch is running.
    ///
    /// # Notes
    ///
    /// If `anchor` is in the future, [`elapsed`](Self::elapsed) will return
    /// [`Duration::ZERO`] until the current time catches up to it.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// # use std::thread;
    /// # use std::time::Instant;
    /// # fn main() -> libsw::Result<()> {
    /// let mut sw_1 = Sw::new();
    /// let mut sw_2 = Sw::new();
    ///
    /// let start = Instant::now();
    /// // off to the races! at the same time!
    /// sw_1.start_at(start)?;
    /// sw_2.start_at(start)?;
    ///
    /// thread::sleep(Duration::from_millis(100));
    /// let anchor = Instant::now();
    ///
    /// assert_eq!(sw_1.elapsed_at(anchor), sw_2.elapsed_at(anchor)); // 'twas a tie
    /// assert!(sw_1.elapsed_at(anchor) >= Duration::from_millis(100));
    /// # Ok(())
    /// # }
    /// ```
    pub fn start_at(&mut self, anchor: I) -> crate::Result<()> {
        if self.is_stopped() {
            self.inner.start_at(anchor);
            Ok(())
        } else {
            Err(Error::SwStart)
        }
    }

    /// Stops measuring the time elapsed since the last start as if the current
    /// time were `anchor`.
    ///
    /// # Errors
    ///
    /// Returns [`SwStop`](Error::SwStop) if the stopwatch is already stopped.
    ///
    /// # Notes
    ///
    /// - If `anchor` is earlier than the last start, there is no effect on the
    ///   elapsed time.
    ///
    /// - Overflows of the new elapsed time are saturated to [`Duration::MAX`].
    ///   Use [`StopwatchImpl::checked_stop_at`] to explicitly check for overflow.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// # use std::thread;
    /// # use std::time::Instant;
    /// # fn main() -> libsw::Result<()> {
    /// let mut sw_1 = Sw::new_started();
    /// let mut sw_2 = sw_1.clone();
    /// let stop = Instant::now();
    /// sw_1.stop_at(stop)?;
    /// sw_2.stop_at(stop)?;
    /// assert_eq!(sw_1, sw_2);
    /// # Ok(())
    /// # }
    /// ```
    pub fn stop_at(&mut self, anchor: I) -> crate::Result<()> {
        if self.is_running() {
            self.inner.stop_at(anchor);
            Ok(())
        } else {
            Err(Error::SwStop)
        }
    }

    /// Tries to stop the stopwatch. If the new elapsed time overflows, returns
    /// [`None`] without mutating the stopwatch.
    ///
    /// # Errors
    ///
    /// Returns [`SwStop`](Error::SwStop) if the stopwatch is already stopped.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// # fn main() -> libsw::Result<()> {
    /// let mut sw = Sw::new_started();
    /// assert!(sw.checked_stop()?.is_some());
    /// sw.set(Duration::MAX);
    /// sw.start()?;
    /// assert!(sw.checked_stop()?.is_none());
    /// # Ok(())
    /// # }
    /// ```
    pub fn checked_stop(&mut self) -> crate::Result<Option<()>> {
        self.checked_stop_at(I::now())
    }

    /* TODO: these checked fallible type signatures are silly yet consistent */
    /// Tries to stop the stopwatch, as if the current time were `anchor`. If
    /// the new elapsed time overflows, returns [`None`] without mutating the
    /// stopwatch.
    ///
    /// # Errors
    ///
    /// Returns [`SwStop`](Error::SwStop) if the stopwatch is already stopped.
    ///
    /// # Notes
    ///
    /// If `anchor` is earlier than the last start, there is no effect on the
    /// elapsed time.
    ///
    /// # Examples
    ///
    /// See [`StopwatchImpl::checked_stop`] for comparable example usage.
    pub fn checked_stop_at(&mut self, anchor: I) -> crate::Result<Option<()>> {
        if self.is_running() {
            let overflow: bool = !self.inner.checked_stop_at(anchor);
            let flag = if overflow { None } else { Some(()) };
            Ok(flag)
        } else {
            Err(Error::SwStop)
        }
    }

    /// Toggles whether the stopwatch is running or stopped.
    ///
    /// # Notes
    ///
    /// See [`stop`](Self::stop) for details about how overflow is handled.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// let mut sw = Sw::new();
    /// sw.toggle();
    /// assert!(sw.is_running());
    /// sw.toggle();
    /// assert!(sw.is_stopped());
    /// ```
    pub fn toggle(&mut self) {
        self.toggle_at(I::now());
    }

    /// Toggles whether the stopwatch is running or stopped, as if the current
    /// time were `anchor`.
    ///
    /// # Notes
    ///
    /// See [`start_at`](Self::start_at) and [`stop_at`](Self::stop_at) for
    /// notes about the chronology of `anchor`, as well as what happens if
    /// overflow occurs.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use std::time::Instant;
    /// let mut left = Sw::new();
    /// let mut right = Sw::new_started();
    ///
    /// // perfect swap of left and right running
    /// let now = Instant::now();
    /// left.toggle_at(now);
    /// right.toggle_at(now);
    ///
    /// assert!(left.is_running());
    /// assert!(right.is_stopped());
    /// ```
    pub fn toggle_at(&mut self, anchor: I) {
        self.inner.toggle_at(anchor);
    }

    /// Tries to toggle whether the stopwatch is running or stopped. If the new
    /// elapsed time overflows, returns [`None`] without mutating the stopwatch.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// # use std::thread;
    /// let mut sw = Sw::with_elapsed_started(Duration::MAX);
    /// thread::sleep(Duration::from_millis(100));
    /// // whoops, new elapsed time can't be Duration::MAX + 100ms
    /// assert!(sw.checked_toggle().is_none());
    /// ```
    #[must_use]
    pub fn checked_toggle(&mut self) -> Option<()> {
        self.checked_toggle_at(I::now())
    }

    /// Tries to toggle whether the stopwatch is running or stopped, as if the
    /// current time were `anchor`. If the new elapsed time overflows, returns
    /// [`None`] without mutating the stopwatch.
    ///
    /// # Examples
    ///
    /// See the documentation for [`checked_toggle`](Self::checked_toggle) for a
    /// related example.
    #[must_use]
    pub fn checked_toggle_at(&mut self, anchor: I) -> Option<()> {
        if self.inner.checked_toggle_at(anchor) {
            Some(())
        } else {
            None
        }
    }

    /// Starts the stopwatch, returning a [`Guard`] which when dropped, will
    /// stop the stopwatch.
    ///
    /// # Errors
    ///
    /// Returns [`SwGuard`](Error::SwGuard) if the stopwatch is running.
    ///
    /// # Examples
    ///
    /// For examples on how to use `Guard`s, see the [struct
    /// documentation](Guard).
    pub fn guard(&mut self) -> crate::Result<Guard<'_, I>> {
        self.guard_at(I::now())
    }

    /// Starts the stopwatch as if the current time were `anchor`, returning a
    /// [`Guard`], which when dropped, will stop the stopwatch.
    ///
    /// # Errors
    ///
    /// Returns [`SwGuard`](Error::SwGuard) if the stopwatch is running.
    ///
    /// # Notes
    ///
    /// For details about `anchor`, see [`start_at`](Self::start_at). For
    /// examples on how to use `Guard`s, see the [struct documentation](Guard).
    pub fn guard_at(&mut self, anchor: I) -> crate::Result<Guard<'_, I>> {
        self.start_at(anchor).map_err(|_| Error::SwGuard)?;
        let guard = Guard::new(self);
        debug_assert!(guard.is_ok());
        guard
    }

    /// Stops and resets the elapsed time to zero.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// let mut sw = Sw::with_elapsed_started(Duration::from_secs(1));
    /// sw.reset();
    /// assert_eq!(sw, Sw::new());
    /// ```
    pub fn reset(&mut self) {
        self.inner.reset();
    }

    /// Resets the elapsed time to zero without affecting whether the stopwatch
    /// is running.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// # fn main() -> libsw::Result<()> {
    /// let mut sw = Sw::with_elapsed_started(Duration::from_secs(1));
    /// sw.reset_in_place();
    /// assert!(sw.is_running());
    /// // new elapsed time is close to zero
    /// assert!(sw.elapsed() < Duration::from_millis(1));
    ///
    /// sw.stop()?;
    /// sw.reset_in_place();
    /// assert_eq!(sw, Sw::new());
    /// # Ok(())
    /// # }
    /// ```
    pub fn reset_in_place(&mut self) {
        self.inner.reset_in_place();
    }

    /// Resets the elapsed time to zero without affecting whether the stopwatch
    /// is running.
    ///
    /// # Notes
    ///
    /// See [`start_at`](Self::start_at) for notes about the chronology of
    /// `anchor`.
    ///
    /// # Examples
    ///
    /// See the documentation for [`reset_in_place`](Self::reset_in_place) for a
    /// related example.
    pub fn reset_in_place_at(&mut self, start: I) {
        self.inner.reset_in_place_at(start);
    }

    /// Stops and sets the total elapsed time to `new`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// let mut sw = Sw::new();
    /// sw.set(Duration::from_secs(1));
    /// assert_eq!(sw.elapsed(), Duration::from_secs(1));
    /// ```
    pub fn set(&mut self, new: Duration) {
        self.inner.set(new);
    }

    /// Sets the total elapsed time to `new` without affecting whether the
    /// stopwatch is running.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// # fn main() -> libsw::Result<()> {
    /// let mut sw = Sw::new();
    /// sw.set_in_place(Duration::from_secs(1));
    /// assert_eq!(sw.elapsed(), Duration::from_secs(1));
    /// assert!(sw.is_stopped());
    ///
    /// sw.start()?;
    /// sw.set_in_place(Duration::from_secs(2));
    /// assert!(sw.elapsed() >= Duration::from_secs(2));
    /// assert!(sw.is_running());
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_in_place(&mut self, new: Duration) {
        self.inner.set_in_place(new);
    }

    /// Sets the total elapsed time to `new` as if the current time were
    /// `anchor`, and without affecting whether the stopwatch is running.
    ///
    /// # Notes
    ///
    /// See [`start_at`](Self::start_at) for notes about the chronology of
    /// `anchor`.
    ///
    /// # Examples
    ///
    /// See the documentation for [`set_in_place`](Self::set_in_place) for
    /// a related example.
    pub fn set_in_place_at(&mut self, new: Duration, anchor: I) {
        self.inner.set_in_place_at(new, anchor);
    }

    /// Stops and sets the total elapsed time to `new`, returning the previous
    /// elapsed time.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// let mut sw = Sw::with_elapsed(Duration::from_secs(3));
    /// let previous = sw.replace(Duration::from_secs(1));
    /// assert_eq!(previous, Duration::from_secs(3));
    /// assert_eq!(sw.elapsed(), Duration::from_secs(1));
    /// ```
    pub fn replace(&mut self, new: Duration) -> Duration {
        self.inner.replace(new)
    }

    /// Stops and sets the total elapsed time to `new`, returning the previous
    /// elapsed time as if the current time were `anchor`.
    ///
    /// # Notes
    ///
    /// See [`elapsed_at`](Self::elapsed_at) for notes about the chronology of
    /// `anchor`.
    ///
    /// # Examples
    ///
    /// See the documentation for [`replace`](Self::replace) for a related
    /// example.
    pub fn replace_at(&mut self, new: Duration, anchor: I) -> Duration {
        self.inner.replace_at(new, anchor)
    }

    /// Adds `dur` to the total elapsed time. If overflow occurred, the total
    /// elapsed time is set to [`Duration::MAX`].
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// let mut sw = Sw::with_elapsed(Duration::from_secs(1));
    /// sw = sw.saturating_add(Duration::from_secs(1));
    /// assert_eq!(sw.elapsed(), Duration::from_secs(2));
    /// sw = sw.saturating_add(Duration::MAX);
    /// assert_eq!(sw.elapsed(), Duration::MAX);
    /// ```
    #[must_use]
    pub const fn saturating_add(mut self, dur: Duration) -> Self {
        self.inner = self.inner.saturating_add(dur);
        self
    }

    /// Subtracts `dur` from the total elapsed time. If underflow occurred, the
    /// total elapsed time is set to [`Duration::ZERO`].
    ///
    /// # Notes
    ///
    /// See the documentation for [`saturating_sub_at`](Self::saturating_sub_at)
    /// for notes about positive overflow.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// let mut sw = Sw::with_elapsed(Duration::from_secs(1));
    /// sw = sw.saturating_sub(Duration::from_secs(1));
    /// assert_eq!(sw.elapsed(), Duration::ZERO);
    /// sw = sw.saturating_sub(Duration::from_secs(1));
    /// assert_eq!(sw.elapsed(), Duration::ZERO);
    /// ```
    #[must_use]
    pub fn saturating_sub(self, dur: Duration) -> Self {
        self.saturating_sub_at(dur, I::now())
    }

    /// Subtracts `dur` from the total elapsed time, as if the current time were
    /// `anchor`. If underflow occurred, the total elapsed time is set to
    /// [`Duration::ZERO`].
    ///
    /// # Notes
    ///
    /// - If the elapsed time is overflowing (as in, would exceed
    ///   [`Duration::MAX`]), the elapsed time is clamped to [`Duration::MAX`] and
    ///   `dur` is subtracted from that.
    ///
    /// - `anchor` saturates to the last instant the stopwatch was started.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// # use std::time::Instant;
    /// # use std::thread;
    /// let mut sw = Sw::new_started();
    /// thread::sleep(Duration::from_millis(100));
    /// let mut now = Instant::now();
    /// sw = sw.saturating_sub_at(Duration::from_secs(1), now);
    /// assert_eq!(sw.elapsed_at(now), Duration::ZERO);
    /// ```
    #[must_use]
    pub fn saturating_sub_at(mut self, dur: Duration, anchor: I) -> Self {
        self.inner = self.inner.saturating_sub_at(dur, anchor);
        self
    }

    /// Adds `dur` to the total elapsed time. If overflow occurred, returns
    /// [`None`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// let mut sw = Sw::new();
    /// sw = sw.checked_add(Duration::from_secs(1)).unwrap();
    /// assert_eq!(sw.elapsed(), Duration::from_secs(1));
    /// assert_eq!(sw.checked_add(Duration::MAX), None);
    /// ```
    #[must_use]
    pub const fn checked_add(mut self, dur: Duration) -> Option<Self> {
        match self.inner.checked_add(dur) {
            Some(new) => {
                self.inner = new;
                Some(self)
            }
            None => None,
        }
    }

    /// Subtracts `dur` from the total elapsed time. If overflow occurred,
    /// returns [`None`].
    ///
    /// # Notes
    ///
    /// See the documentation for [`checked_sub_at`](Self::checked_sub_at) for
    /// notes about positive overflow.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// let mut sw = Sw::new();
    /// assert_eq!(sw.checked_sub(Duration::from_secs(1)), None);
    /// sw += Duration::from_secs(1);
    /// assert_eq!(
    ///     sw.checked_sub(Duration::from_secs(1)),
    ///     Some(Sw::with_elapsed(Duration::ZERO)),
    /// );
    /// ```
    #[must_use]
    pub fn checked_sub(self, dur: Duration) -> Option<Self> {
        self.checked_sub_at(dur, I::now())
    }

    /// Subtracts `dur` from the total elapsed time, as if the current time were
    /// `anchor`. If overflow occurred, returns [`None`].
    ///
    /// # Notes
    ///
    /// - Overflow can also occur if the elapsed time is overflowing (as in, would
    ///   exceed [`Duration::MAX`]).
    ///
    /// - `anchor` saturates to the last instant the stopwatch was started.
    ///
    /// # Examples
    ///
    /// ```
    /// # use libsw::Sw;
    /// # use core::time::Duration;
    /// # use std::time::Instant;
    /// # use std::thread;
    /// let mut sw = Sw::new_started();
    /// thread::sleep(Duration::from_millis(100));
    /// let now = Instant::now();
    /// // underflow yields `None`
    /// assert_eq!(sw.checked_sub_at(Duration::from_secs(1), now), None);
    ///
    /// // positive overflow yields `None`
    /// sw.set_in_place(Duration::MAX);
    /// assert_eq!(sw.checked_sub(Duration::ZERO), None);
    /// ```
    #[must_use]
    pub fn checked_sub_at(mut self, dur: Duration, anchor: I) -> Option<Self> {
        self.inner = self.inner.checked_sub_at(dur, anchor)?;
        Some(self)
    }
}

impl<I: Instant> From<StopwatchImpl<I>> for CoreSw<I> {
    fn from(val: StopwatchImpl<I>) -> Self {
        val.inner
    }
}

impl<I: Instant> From<CoreSw<I>> for StopwatchImpl<I> {
    fn from(core_sw: CoreSw<I>) -> Self {
        Self { inner: core_sw }
    }
}

impl<I: Instant> fmt::Debug for StopwatchImpl<I> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("StopwatchImpl")
            .field("elapsed", &self.inner.elapsed)
            .field("start", &self.inner.start)
            .finish()
    }
}

impl<I: Instant> Default for StopwatchImpl<I> {
    /// Returns the default stopwatch. Same as calling [`StopwatchImpl::new`].
    fn default() -> Self {
        Self::new()
    }
}

impl<I: Instant> ops::Add<Duration> for StopwatchImpl<I> {
    type Output = Self;

    /// Add `dur` to `self`.
    ///
    /// Currently this is an alias to [`StopwatchImpl::checked_add`], but that
    /// is not a stable guarentee. If you need a guarentee on the
    /// implementation, use the [checked](Self::checked_add) or
    /// [saturating](Self::checked_add) methods explicitly.
    ///
    /// # Panics
    ///
    /// Panics if overflow occurs.
    #[track_caller]
    fn add(self, dur: Duration) -> Self::Output {
        self.inner.add(dur).into()
    }
}

impl<I: Instant> ops::Sub<Duration> for StopwatchImpl<I> {
    type Output = Self;

    /// Subtract `dur` from `self`.
    ///
    /// Currently this is an alias to [`StopwatchImpl::checked_sub`], but that
    /// is not a stable guarentee. If you need a guarentee on the
    /// implementation, use the [checked](Self::checked_sub) or
    /// [saturating](Self::checked_sub) methods explicitly.
    ///
    /// # Panics
    ///
    /// Panics if overflow occurs.
    #[track_caller]
    fn sub(self, dur: Duration) -> Self::Output {
        self.inner.sub(dur).into()
    }
}

impl<I: Instant> ops::AddAssign<Duration> for StopwatchImpl<I> {
    #[track_caller]
    fn add_assign(&mut self, dur: Duration) {
        self.inner.add_assign(dur);
    }
}

impl<I: Instant> ops::SubAssign<Duration> for StopwatchImpl<I> {
    #[track_caller]
    fn sub_assign(&mut self, dur: Duration) {
        self.inner.sub_assign(dur);
    }
}

impl<I: Instant> PartialEq for StopwatchImpl<I> {
    /// Tests for equality between `self` and `rhs`.
    ///
    /// Stopwatches are equal if whether they are running and their elapsed time
    /// are equal.
    fn eq(&self, rhs: &Self) -> bool {
        self.inner.eq(&rhs.inner)
    }
}

impl<I: Instant> Eq for StopwatchImpl<I> {}

impl<I: Instant + Hash> Hash for StopwatchImpl<I> {
    /// Hashes `self` and `rhs`. These hashes are not dependent on the time of
    /// measurement, so they can be used to test equality.
    ///
    /// # Support
    ///
    /// `I` (the [`Instant`] type used by the stopwatch) must implement
    /// [`Hash`].
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.inner.hash(state);
    }
}