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
// libsw: stopwatch library
// copyright (C) 2022-2023 Nissa <and-nissa@protonmail.com>
// licensed under MIT OR Apache-2.0
use ::core::hash::{Hash, Hasher};
use ::core::ops;
use ::core::time::Duration;
use crate::Instant;
/// A stopwatch measures and accumulates elapsed time between starts and stops.
///
/// Stopwatches work with any type that implements [`Instant`].
///
/// # Notes
///
/// It is possible to craft two stopwatches whose internal components differ,
/// but are equal according to [`PartialEq`], [`Eq`], and [`Hash`].
///
/// ```
/// # use libsw_core::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 {
/// elapsed,
/// start: Some(start),
/// };
/// let sw_2 = Sw {
/// // `elapsed()` is 1s less
/// elapsed: elapsed - Duration::from_secs(1),
/// // now with start pushed back, `elapsed()` is equal
/// start: Some(start - Duration::from_secs(1)),
/// };
///
/// // different components, but they are equal!
/// assert_eq!(sw_1, sw_2);
/// ```
#[derive(Clone, Copy, Debug)]
pub struct Stopwatch<I: Instant> {
/// Accumulated elapsed time.
pub elapsed: Duration,
/// The instant at which the stopwatch was started, if it is running.
/// Otherwise, [`None`].
pub start: Option<I>,
}
impl<I: Instant> Stopwatch<I> {
/// Returns a stopped stopwatch with zero elapsed time.
///
/// # Examples
///
/// ```
/// # use libsw_core::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_core::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_core::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_core::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_core::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.
///
/// See the [top-level documentation](`Stopwatch`) for more details.
#[must_use]
pub const fn from_raw(elapsed: Duration, start: Option<I>) -> Self {
Self { elapsed, start }
}
/// Returns `true` if the stopwatch is running.
///
/// # Examples
///
/// ```
/// # use libsw_core::Sw;
/// let sw = Sw::new_started();
/// assert!(sw.is_running());
/// ```
#[must_use]
pub const fn is_running(&self) -> bool {
self.start.is_some()
}
/// Returns `true` if the stopwatch is stopped.
///
/// # Examples
///
/// ```
/// # use libsw_core::Sw;
/// let sw = Sw::new();
/// assert!(sw.is_stopped());
/// ```
#[must_use]
pub const fn is_stopped(&self) -> bool {
!self.is_running()
}
/// Returns the total time elapsed. If overflow occurs, the elapsed time is
/// saturated to [`Duration::MAX`].
///
/// # Examples
///
/// ```
/// # use libsw_core::Sw;
/// # use core::time::Duration;
/// # use std::thread;
/// let sw = Sw::new_started();
/// thread::sleep(Duration::from_millis(100));
/// assert!(sw.elapsed() >= Duration::from_millis(100));
/// ```
#[must_use]
pub fn elapsed(&self) -> Duration {
self.elapsed_at(I::now())
}
/// 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_core::Sw;
/// # use std::time::Instant;
/// let sw_1 = Sw::new_started();
/// let sw_2 = sw_1;
/// 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.checked_elapsed_at(anchor).unwrap_or(Duration::MAX)
}
/// Computes the total time elapsed. If overflow occurred, returns [`None`].
///
/// # Examples
///
/// ```
/// # use libsw_core::Sw;
/// # use core::time::Duration;
/// # use std::thread;
/// 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());
/// ```
#[must_use]
pub fn checked_elapsed(&self) -> Option<Duration> {
self.checked_elapsed_at(I::now())
}
/// 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.
#[must_use]
pub fn checked_elapsed_at(&self, anchor: I) -> Option<Duration> {
let before_start = self.elapsed;
if let Some(start) = self.start {
let after_start = anchor.saturating_duration_since(start);
before_start.checked_add(after_start)
} else {
Some(before_start)
}
}
/// Starts measuring the time elapsed.
///
/// # Examples
///
/// ```
/// # use libsw_core::Sw;
/// # use core::time::Duration;
/// # use std::thread;
/// let mut sw = Sw::new();
/// sw.start();
///
/// let then = sw.elapsed();
/// thread::sleep(Duration::from_millis(100));
/// let now = sw.elapsed();
/// assert!(then != now);
/// ```
pub fn start(&mut self) {
self.start_at(I::now());
}
/// Starts measuring the time elapsed as if the current time were `anchor`.
///
/// # 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_core::Sw;
/// # use core::time::Duration;
/// # use std::thread;
/// # use std::time::Instant;
/// 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));
/// ```
pub fn start_at(&mut self, anchor: I) {
self.start = Some(anchor);
}
/// Stops measuring the time elapsed since the last start.
///
/// # Notes
///
/// Overflows of the new elapsed time are saturated to [`Duration::MAX`].
/// Use [`Stopwatch::checked_stop`] to explicitly check for overflow.
///
/// # Examples
///
/// ```
/// # use libsw_core::Sw;
/// # use core::time::Duration;
/// # use std::thread;
/// let mut sw = Sw::new_started();
/// sw.stop();
///
/// let then = sw.elapsed();
/// thread::sleep(Duration::from_millis(100));
/// let now = sw.elapsed();
/// assert!(then == now);
/// ```
pub fn stop(&mut self) {
self.stop_at(I::now());
}
/// Stops measuring the time elapsed since the last start as if the current
/// time were `anchor`.
///
/// # 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 [`Stopwatch::checked_stop_at`] to explicitly check for overflow.
///
/// # Examples
///
/// ```
/// # use libsw_core::Sw;
/// # use core::time::Duration;
/// # use std::thread;
/// # use std::time::Instant;
/// let mut sw_1 = Sw::new_started();
/// let mut sw_2 = sw_1;
/// let stop = Instant::now();
/// sw_1.stop_at(stop);
/// sw_2.stop_at(stop);
/// assert_eq!(sw_1, sw_2);
/// ```
pub fn stop_at(&mut self, anchor: I) {
if let Some(start) = self.start.take() {
let after_start = anchor.saturating_duration_since(start);
*self = self.saturating_add(after_start);
}
}
/// Tries to stop the stopwatch. If the new elapsed time overflows, returns
/// `false` without mutating the stopwatch.
///
/// # Examples
///
/// ```
/// # use libsw_core::Sw;
/// # use core::time::Duration;
/// let mut sw = Sw::new_started();
/// assert!(sw.checked_stop());
/// sw.set(Duration::MAX);
/// sw.start();
/// assert!(!sw.checked_stop());
/// ```
#[must_use]
pub fn checked_stop(&mut self) -> bool {
self.checked_stop_at(I::now())
}
/// Tries to stop the stopwatch, as if the current time were `anchor`. If
/// the new elapsed time overflows, returns `false` without mutating the
/// stopwatch.
///
/// # Notes
///
/// If `anchor` is earlier than the last start, there is no effect on the
/// elapsed time.
#[must_use]
pub fn checked_stop_at(&mut self, anchor: I) -> bool {
if let Some(start) = self.start {
let after_start = anchor.saturating_duration_since(start);
if let Some(new) = self.checked_add(after_start) {
self.set(new.elapsed);
} else {
return false;
}
}
true
}
/// Toggles whether the stopwatch is running or stopped.
///
/// # Notes
///
/// See [`stop`](Self::stop) for details about how overflow is handled.
///
/// # Examples
///
/// ```
/// # use libsw_core::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_core::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) {
if self.is_running() {
self.stop_at(anchor);
} else {
self.start_at(anchor);
}
}
/// Tries to toggle whether the stopwatch is running or stopped. If the new
/// elapsed time overflows, returns `false` without mutating the stopwatch.
///
/// # Examples
///
/// ```
/// # use libsw_core::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());
/// ```
#[must_use]
pub fn checked_toggle(&mut self) -> bool {
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
/// `false` without mutating the stopwatch.
#[must_use]
pub fn checked_toggle_at(&mut self, anchor: I) -> bool {
if self.is_running() {
self.checked_stop_at(anchor)
} else {
self.start_at(anchor);
true
}
}
/// Stops and resets the elapsed time to zero.
///
/// # Examples
///
/// ```
/// # use libsw_core::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 = Self::new();
}
/// Resets the elapsed time to zero without affecting whether the stopwatch
/// is running.
///
/// # Examples
///
/// ```
/// # use libsw_core::Sw;
/// # use core::time::Duration;
/// 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());
/// ```
pub fn reset_in_place(&mut self) {
self.reset_in_place_at(Instant::now());
}
/// 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`.
pub fn reset_in_place_at(&mut self, start: I) {
self.set_in_place_at(Duration::ZERO, start);
}
/// Stops and sets the total elapsed time to `new`.
///
/// # Examples
///
/// ```
/// # use libsw_core::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 = Self::with_elapsed(new);
}
/// Sets the total elapsed time to `new` without affecting whether the
/// stopwatch is running.
///
/// # Examples
///
/// ```
/// # use libsw_core::Sw;
/// # use core::time::Duration;
/// 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());
/// ```
pub fn set_in_place(&mut self, new: Duration) {
self.set_in_place_at(new, Instant::now());
}
/// 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`.
pub fn set_in_place_at(&mut self, new: Duration, anchor: I) {
let was_running = self.is_running();
self.set(new);
if was_running {
self.start_at(anchor);
}
}
/// Stops and sets the total elapsed time to `new`, returning the previous
/// elapsed time.
///
/// # Examples
///
/// ```
/// # use libsw_core::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.replace_at(new, Instant::now())
}
/// 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`.
pub fn replace_at(&mut self, new: Duration, anchor: I) -> Duration {
let old = self.elapsed_at(anchor);
self.set(new);
old
}
/// Adds `dur` to the total elapsed time. If overflow occurred, the total
/// elapsed time is set to [`Duration::MAX`].
///
/// ```
/// # use libsw_core::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.elapsed = self.elapsed.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_core::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_core::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, mut anchor: I) -> Self {
self.saturate_anchor_to_start(&mut anchor);
self.saturating_sync_elapsed_at(anchor);
self.elapsed = self.elapsed.saturating_sub(dur);
self
}
/// Adds `dur` to the total elapsed time. If overflow occurred, returns
/// [`None`].
///
/// # Examples
///
/// ```
/// # use libsw_core::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.elapsed.checked_add(dur) {
Some(new) => {
self.elapsed = 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_core::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_core::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, mut anchor: I) -> Option<Self> {
self.saturate_anchor_to_start(&mut anchor);
self.checked_sync_elapsed_at(anchor)?;
let new = self.elapsed.checked_sub(dur)?;
self.elapsed = new;
Some(self)
}
}
// private methods
impl<I: Instant> Stopwatch<I> {
fn saturate_anchor_to_start(&self, anchor: &mut I) {
if let Some(start) = self.start {
let future = anchor.saturating_duration_since(start);
let past = start.saturating_duration_since(*anchor);
if future < past {
*anchor = start;
}
}
}
/// Syncs changes in the elapsed time, effectively toggling the stopwatch
/// twice. If the new elapsed time overflows, it is saturated to
/// [`Duration::MAX`].
fn saturating_sync_elapsed_at(&mut self, anchor: I) {
if let Some(start) = self.start {
*self = self.saturating_add(anchor.saturating_duration_since(start));
self.start = Some(anchor);
}
}
/// Syncs changes in the elapsed time, effectively toggling the stopwatch
/// twice. If the new elapsed time overflows, returns [`None`] without
/// mutating the stopwatch.
#[must_use]
fn checked_sync_elapsed_at(&mut self, anchor: I) -> Option<()> {
if let Some(start) = self.start {
let after_start = anchor.saturating_duration_since(start);
*self = self.checked_add(after_start)?;
self.start = Some(anchor);
}
Some(())
}
/// "Transfers" `elapsed` to `start`, such that [`Self::elapsed`] is
/// unchanged, and the new `elapsed` is zero. Returns `false` if the new
/// start time cannot be represented.
fn normalize_start(&mut self) -> bool {
if let Some(ref mut start) = self.start {
if !Self::normalize_start_inner(start, self.elapsed) {
return false;
}
self.elapsed = Duration::ZERO;
}
true
}
fn normalize_start_inner(start: &mut I, elapsed: Duration) -> bool {
if let Some(new) = start.checked_sub(elapsed) {
*start = new;
true
} else {
false
}
}
}
impl<I: Instant> Default for Stopwatch<I> {
/// Returns the default stopwatch. Same as calling [`Stopwatch::new`].
fn default() -> Self {
Self::new()
}
}
impl<I: Instant> ops::Add<Duration> for Stopwatch<I> {
type Output = Self;
/// Add `dur` to `self`.
///
/// Currently this is an alias to [`Stopwatch::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.checked_add(dur)
.expect("attempt to add stopwatch with overflow")
}
}
impl<I: Instant> ops::Sub<Duration> for Stopwatch<I> {
type Output = Self;
/// Subtract `dur` from `self`.
///
/// Currently this is an alias to [`Stopwatch::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.checked_sub(dur)
.expect("attempt to subtract stopwatch with overflow")
}
}
impl<I: Instant> ops::AddAssign<Duration> for Stopwatch<I> {
#[track_caller]
fn add_assign(&mut self, dur: Duration) {
*self = *self + dur;
}
}
impl<I: Instant> ops::SubAssign<Duration> for Stopwatch<I> {
#[track_caller]
fn sub_assign(&mut self, dur: Duration) {
*self = *self - dur;
}
}
impl<I: Instant> PartialEq for Stopwatch<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 {
match (self.start, rhs.start) {
(Some(_), None) | (None, Some(_)) => {
// they have different states, definitely not equal
debug_assert_ne!(self.is_running(), rhs.is_running());
false
}
(None, None) => {
/* they're both stopped, we can simply compare `elapsed` without
* worrying about time */
debug_assert!(self.is_stopped() && rhs.is_stopped());
self.elapsed == rhs.elapsed
}
(Some(mut self_start), Some(mut rhs_start)) => {
// they're both running, we need to worry about time
debug_assert!(self.is_running() && rhs.is_running());
let self_ok = Self::normalize_start_inner(&mut self_start, self.elapsed);
let rhs_ok = Self::normalize_start_inner(&mut rhs_start, rhs.elapsed);
if self_ok & rhs_ok {
self_start.saturating_duration_since(rhs_start)
== rhs_start.saturating_duration_since(self_start)
} else {
/* start times can't be trusted since normalizing failed! we
* cannot compare them. */
self_ok == rhs_ok
}
}
}
}
}
impl<I: Instant> Eq for Stopwatch<I> {}
impl<I: Instant + Hash> Hash for Stopwatch<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) {
let mut self_ = *self;
let ok = self_.normalize_start();
ok.hash(state);
if ok {
// we can only trust `elapsed` and `start` if normalizing succeeded.
self_.elapsed.hash(state);
self_.start.hash(state);
}
}
}