yuno 0.1.0

A declarative UI layout and rendering framework powered by Skia.
use std::time::{Duration, Instant};

pub struct Stopwatch {
    beginning: Instant,
    elapsed: Duration,
    is_running: bool,
}

impl Default for Stopwatch {
    fn default() -> Self {
        Self::new()
    }
}

impl Stopwatch {
    pub fn new() -> Self {
        Self {
            beginning: Instant::now(),
            elapsed: Duration::ZERO,
            is_running: false,
        }
    }

    /// Start or resume the stopwatch from the current position
    pub fn start(&mut self) {
        if !self.is_running {
            self.beginning = Instant::now();
            self.is_running = true;
        }
    }

    /// Pause/stop the stopwatch, keeping the current elapsed time status
    pub fn stop(&mut self) {
        if self.is_running {
            self.elapsed += self.beginning.elapsed();
            self.is_running = false;
        }
    }

    /// Reset the elapsed time back to 0 and stop the stopwatch
    pub fn reset(&mut self) {
        self.elapsed = Duration::ZERO;
        self.is_running = false;
        self.beginning = Instant::now();
    }

    /// Forcefully set the stopwatch's elapsed time to a specific duration
    pub fn seek(&mut self, t: &Duration) {
        self.elapsed = *t;
        if self.is_running {
            self.beginning = Instant::now();
        }
    }

    /// Get the current accumulated duration
    pub fn value(&self) -> Duration {
        if self.is_running {
            self.elapsed + self.beginning.elapsed()
        } else {
            self.elapsed
        }
    }
}