Skip to content

Commit

Permalink
Step 5 - Nicely format stats output
Browse files Browse the repository at this point in the history
We implemant a `fmt::Display` trait to own the final representation of
the Stats struct and add kilobytes processed.
  • Loading branch information
Scott Pierce committed Mar 17, 2018
1 parent e15502b commit d2c5ef1
Showing 1 changed file with 30 additions and 6 deletions.
36 changes: 30 additions & 6 deletions stream_stats.rs
@@ -1,12 +1,15 @@
use std::fmt;
use std::fs::{File, OpenOptions}; use std::fs::{File, OpenOptions};
use std::io::{self, BufRead, BufReader, BufWriter, Write}; use std::io::{self, BufRead, BufReader, BufWriter, Write};
use std::time::Instant; use std::time::Instant;


static READ_BUF_SIZE: usize = 1024 * 1024; static READ_BUF_SIZE: usize = 1024 * 1024;
static CLEAR_LINE: &str = "\x1B[1G\x1B[2K";


struct Stats { struct Stats {
started: Instant, started: Instant,
lines: usize, lines: usize,
bytes: usize,
tty: File, tty: File,
} }


Expand All @@ -15,6 +18,7 @@ impl Stats {
Stats { Stats {
started: Instant::now(), started: Instant::now(),
lines: 0, lines: 0,
bytes: 0,
tty: OpenOptions::new() tty: OpenOptions::new()
.write(true) .write(true)
.append(true) .append(true)
Expand All @@ -24,6 +28,30 @@ impl Stats {
} }
} }


impl fmt::Display for Stats {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {

let elapsed = self.started.elapsed();
let seconds: f64 = elapsed.as_secs() as f64 + elapsed.subsec_nanos() as f64 * 1e-9;
if seconds == 0.0 {
return write!(f, "");
}
let kb = self.bytes as f64 / 1024 as f64;
let kb_per_sec = kb / seconds;
let lines_per_sec = self.lines as f64 / seconds;
write!(
f,
"{}{:.1} sec | {:.0} kb [ {:.1}/s ] | {} lines [ {:.0}/s ]",
CLEAR_LINE,
seconds,
kb,
kb_per_sec,
self.lines,
lines_per_sec
)
}
}

fn main() { fn main() {
let mut reader = BufReader::with_capacity(READ_BUF_SIZE, io::stdin()); let mut reader = BufReader::with_capacity(READ_BUF_SIZE, io::stdin());
let mut writer = BufWriter::new(io::stdout()); let mut writer = BufWriter::new(io::stdout());
Expand All @@ -33,13 +61,9 @@ fn main() {
while reader.read_until(b'\n', &mut buffer).unwrap() > 0 { while reader.read_until(b'\n', &mut buffer).unwrap() > 0 {
writer.write(&buffer).unwrap(); writer.write(&buffer).unwrap();
stats.lines += 1; stats.lines += 1;
stats.bytes += &buffer.len();
buffer.clear(); buffer.clear();
} }
writer.flush().unwrap(); writer.flush().unwrap();
writeln!( writeln!(&stats.tty, "{}", &stats).expect("Could not write to tty!");
stats.tty,
"lines: {}, {:?}",
stats.lines,
stats.started.elapsed()
).expect("Could not write to tty!");
} }

0 comments on commit d2c5ef1

Please sign in to comment.