Browse Source

Add laps

master
Schneider 6 years ago
parent
commit
5c4224b8b0
Signed by: schneider GPG Key ID: 3F50B02A50039F3B
  1. 2
      src/duration.rs
  2. 18
      src/lib.rs
  3. 26
      src/main.rs

2
src/duration.rs

@ -1,7 +1,7 @@
use std::convert::From; use std::convert::From;
use std::{fmt, time}; use std::{fmt, time};
#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct FmtDuration(time::Duration); pub struct FmtDuration(time::Duration);
impl fmt::Display for FmtDuration { impl fmt::Display for FmtDuration {

18
src/lib.rs

@ -2,7 +2,7 @@ use crossbeam_channel::{bounded, Receiver};
use duration::*; use duration::*;
use signal_hook::iterator::Signals; use signal_hook::iterator::Signals;
use signal_hook::SIGINT; use signal_hook::SIGINT;
use std::io::{Result, StdoutLock, Write};
use std::io::{stdin, Result, StdoutLock, Write};
use std::thread; use std::thread;
pub mod duration; pub mod duration;
@ -22,6 +22,22 @@ pub fn signal_handler() -> Result<Receiver<()>> {
Ok(r) Ok(r)
} }
pub fn input_handler() -> Result<Receiver<()>> {
let (s, r) = bounded(1);
let mut buf = String::new();
thread::spawn(move || loop {
if stdin().read_line(&mut buf).is_err() {
break;
}
if s.send(()).is_err() {
break;
}
});
Ok(r)
}
/// Resets the current line on stdout /// Resets the current line on stdout
/// ///
/// # Arguments /// # Arguments

26
src/main.rs

@ -10,22 +10,26 @@ use stopwatch::*;
extern crate crossbeam_channel; extern crate crossbeam_channel;
fn main() { fn main() {
if let Err(err) = run() {
println!("{}", err);
std::process::exit(1);
}
}
fn run() -> std::io::Result<()> {
// 30 fps should be enough // 30 fps should be enough
let step_duration = std::time::Duration::from_millis(1000 / 30); let step_duration = std::time::Duration::from_millis(1000 / 30);
let start = Instant::now(); let start = Instant::now();
let ticker = tick(step_duration); let ticker = tick(step_duration);
let signals = match signal_handler() {
Ok(r) => r,
Err(err) => {
println!("{}", err);
return;
}
};
let signals = signal_handler()?;
let input = input_handler()?;
let out = stdout(); let out = stdout();
let mut out = out.lock(); let mut out = out.lock();
let mut elapsed = FmtDuration::from(start.elapsed()); let mut elapsed = FmtDuration::from(start.elapsed());
let mut last_round = start.clone();
let mut round: u32 = 1;
loop { loop {
select! { select! {
@ -38,7 +42,13 @@ fn main() {
recv(signals) -> _ => { recv(signals) -> _ => {
reset_line(&mut out).unwrap(); reset_line(&mut out).unwrap();
writeln!(out, "Total time: {}", elapsed).unwrap(); writeln!(out, "Total time: {}", elapsed).unwrap();
return;
return Ok(());
}
recv(input) -> _ => {
reset_line(&mut out)?;
writeln!(out, "Lap {}: {}", round, FmtDuration::from(last_round.elapsed()))?;
last_round = Instant::now();
round +=1;
} }
} }
} }

Loading…
Cancel
Save