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
//! # Stopwatch
//!
//! A stopwatch that mimics iOS's stopwatch.
//!
//! ## Usage
//!
//! - Use `Stopwatch::new()` to initialise a new stopwatch instance. The stopwatch is paused
//! at `00:00` and will **not** run until you call `.resume()` or `.pause_or_resume()`.
//! - While running:
//!     - Call `.lap()` to record lap times.
//!     - Call `.pause_or_resume()`, `.pause()` or `.resume()` to pause or resume.
//! - When you want to stop (reset), call `.stop()`, which resets the stopwatch and returns
//!   [`StopwatchData`](struct.StopwatchData.html)
//!
//! ## Examples
//!
//! ## Schematic
//!
//! ```ignore
//!                  lap    lap          lap
//! start       start |      |     start  |
//!   o--------x   o-----------x      o-----------x
//!          pause           pause            pause(end)
//! ```

use chrono::{DateTime, Duration, Local};
use std::{default::Default, mem};

#[derive(Debug)]
/// The data returned by [`Stopwatch`](struct.Stopwatch.html) upon `.stop`ping (i.e. resetting)
pub struct StopwatchData {
    pub elapsed: Duration,
    pub pause_moments: Vec<DateTime<Local>>, // moments at which the stopwatch is paused
    pub start_moments: Vec<DateTime<Local>>, // moments at which the stopwatch resumes
    pub lap_moments: Vec<DateTime<Local>>,   // moments at which a lap time is read
    pub laps: Vec<Duration>,                 // lap times
}

impl Default for StopwatchData {
    fn default() -> Self {
        Self {
            elapsed: Duration::zero(),
            start_moments: Vec::new(),
            pause_moments: Vec::new(),
            lap_moments: Vec::new(),
            laps: Vec::new(),
        }
    }
}

impl StopwatchData {
    fn new() -> Self {
        Self::default()
    }
    pub fn start(&self) -> DateTime<Local> {
        self.start_moments[0]
    }
    pub fn stop(&self) -> DateTime<Local> {
        self.pause_moments[self.pause_moments.len() - 1]
    }
}

#[derive(Debug)]
pub struct Stopwatch {
    pub lap_elapsed: Duration, // elapsed time of the current lap
    pub paused: bool,
    pub data: StopwatchData,
}

impl Default for Stopwatch {
    fn default() -> Self {
        Self {
            lap_elapsed: Duration::zero(),
            paused: true, // stopped by default; start by explicitly calling `.resume()`
            data: StopwatchData::new(),
        }
    }
}

impl Stopwatch {
    /// initialise a new stopwatch instance.
    /// The stopwatch is paused at zero and will **not** run until you call `.resume()`
    /// or `.pause_or_resume()`.
    pub fn new() -> Self {
        Self::default()
    }
    /// Read the total time elapsed
    pub fn read(&self) -> Duration {
        if self.paused {
            self.data.elapsed
        } else {
            self.data.elapsed + (Local::now() - self.last_start())
        }
    }
    /// Pause or resume the timer.
    pub fn pause_or_resume(&mut self) {
        self.pause_or_resume_at(Local::now());
    }

    pub fn pause_or_resume_at(&mut self, moment: DateTime<Local>) {
        if self.paused {
            self.resume_at(moment);
        } else {
            self.pause_at(moment);
        }
    }
    /// Lap the stopwatch. If the stopwatch is running, return `Some(<laptime>)`.
    /// If the stopwatch is paused, return `None`.
    pub fn lap(&mut self) -> Option<Duration> {
        self.lap_at(Local::now())
    }

    pub fn lap_at(&mut self, moment: DateTime<Local>) -> Option<Duration> {
        // assert!(!self.paused, "Paused!");
        if self.paused {
            None
        } else {
            let lap = self.read_lap_elapsed(moment);
            self.data.lap_moments.push(moment);
            self.data.laps.push(lap);
            self.lap_elapsed = Duration::zero();
            Some(lap)
        }
    }

    /// resets the stopwatch and returns [`StopwatchData`](struct.StopwatchData.html)
    pub fn stop(&mut self) -> StopwatchData {
        self.stop_at(Local::now())
    }

    pub fn stop_at(&mut self, moment: DateTime<Local>) -> StopwatchData {
        // lap
        let lap = self.read_lap_elapsed(moment);
        self.data.lap_moments.push(moment);
        self.data.laps.push(lap);
        self.lap_elapsed = Duration::zero();
        // pause
        self.data.pause_moments.push(moment);
        self.data.elapsed = self.data.elapsed + (moment - self.last_start());
        self.paused = true;
        // data
        let data = mem::replace(&mut self.data, StopwatchData::new());
        data
    }

    /// Read the time elapsed in the current lap
    fn read_lap_elapsed(&self, moment: DateTime<Local>) -> Duration {
        self.lap_elapsed
            + if self.lap_elapsed == Duration::zero() && !self.data.lap_moments.is_empty() {
                moment - self.last_lap()
            } else {
                moment - self.last_start()
            }
    }

    fn last_start(&self) -> DateTime<Local> {
        self.data.start_moments[self.data.start_moments.len() - 1]
    }
    fn last_lap(&self) -> DateTime<Local> {
        self.data.lap_moments[self.data.lap_moments.len() - 1]
    }
    /// Pause the stopwatch (suggest using `pause_or_resume` instead.)
    pub fn pause(&mut self) {
        self.pause_at(Local::now());
    }
    /// Resume the stopwatch (suggest using `pause_or_resume` instead.)
    pub fn resume(&mut self) {
        self.resume_at(Local::now());
    }

    pub fn pause_at(&mut self, moment: DateTime<Local>) {
        self.data.pause_moments.push(moment);
        self.data.elapsed = self.data.elapsed + (moment - self.last_start());
        self.lap_elapsed = self.read_lap_elapsed(moment);
        self.paused = true;
    }

    pub fn resume_at(&mut self, moment: DateTime<Local>) {
        self.data.start_moments.push(moment);
        self.paused = false;
    }
}