pub struct StopwatchStruct<T>{
pub current_time: u32,
pub status: StopwatchStatus,
pub operation_on_stop: T,
}Expand description
Represents a stopwatch that measures elapsed time.
It takes a generic type T which must be a closure that accepts a u32
(the final current_time when the stopwatch stops).
Fields§
§current_time: u32The current elapsed time in seconds.
status: StopwatchStatusThe current status of the stopwatch (Running or Stopped).
operation_on_stop: TA closure that will be executed when the stopwatch is stopped.
It receives the final current_time as an argument.
Implementations§
Source§impl<T> StopwatchStruct<T>
impl<T> StopwatchStruct<T>
Sourcepub fn new(operation_on_stop: T) -> StopwatchStruct<T>
pub fn new(operation_on_stop: T) -> StopwatchStruct<T>
Creates a new StopwatchStruct instance.
§Arguments
operation_on_stop- A closure that will be called when the stopwatch status is set toStopped. It receives the total elapsed time in seconds as its argument.
§Returns
A new StopwatchStruct initialized with current_time at 0 and status as Running.
§Examples
use clock-timer::stopwatch::{StopwatchStruct, StopwatchStatus}; // Replace clock-timer
let mut stopwatch = StopwatchStruct::new(|time| {
println!("Stopwatch stopped at {} seconds.", time);
});Sourcepub fn start_timer<W: Write>(&mut self, writer: &mut W)
pub fn start_timer<W: Write>(&mut self, writer: &mut W)
Starts the stopwatch.
The stopwatch will increment its current_time every second and print the elapsed time
to the provided writer, overwriting the previous line. The loop continues indefinitely
until the status field of the StopwatchStruct is manually set to StopwatchStatus::Stopped
from outside this function (e.g., from another thread or an external signal).
§Arguments
writer- A mutable reference to any type that implements thestd::io::Writetrait (e.g.,&mut std::io::Stdout).
§Examples
use your_crate_name::stopwatch::{StopwatchStruct, StopwatchStatus}; // Replace your_crate_name
use std::{io::stdout, thread, time::Duration};
let mut stopwatch = StopwatchStruct::new(|time| {
println!("\nStopwatch finished at {} seconds!", time);
});
let mut writer = stdout();
// To stop the stopwatch, you would typically change its status from another thread
// or based on some external event. For demonstration, we'll do it after a delay.
let mut stopwatch_clone = stopwatch.clone(); // Clone to move into another thread
thread::spawn(move || {
thread::sleep(Duration::from_secs(5));
stopwatch_clone.status = StopwatchStatus::Stopped; // Stop after 5 seconds
});
stopwatch.start_timer(&mut writer);
println!("Stopwatch loop ended.");pub fn stop_timer(seconds: u32, reference: &mut StopwatchStruct<T>)
Trait Implementations§
Source§impl<T> Clone for StopwatchStruct<T>
impl<T> Clone for StopwatchStruct<T>
Source§fn clone(&self) -> StopwatchStruct<T>
fn clone(&self) -> StopwatchStruct<T>
1.0.0 · Source§const fn clone_from(&mut self, source: &Self)
const fn clone_from(&mut self, source: &Self)
source. Read more