|
| 1 | +/// Reads numbers from stdin, one per line, and writes them to a serialized histogram on stdout. |
| 2 | +
|
| 3 | +extern crate hdrsample; |
| 4 | +extern crate clap; |
| 5 | + |
| 6 | +use std::io::BufRead; |
| 7 | + |
| 8 | +use clap::{App, Arg, SubCommand}; |
| 9 | + |
| 10 | +use hdrsample::Histogram; |
| 11 | +use hdrsample::serialization::{V2Serializer, V2DeflateSerializer}; |
| 12 | + |
| 13 | +fn main() { |
| 14 | + let default_max = format!("{}", u64::max_value()); |
| 15 | + let matches = App::new("hdrsample cli") |
| 16 | + .subcommand(SubCommand::with_name("serialize") |
| 17 | + .arg(Arg::with_name("min") |
| 18 | + .long("min") |
| 19 | + .help("Minimum discernible value") |
| 20 | + .takes_value(true) |
| 21 | + .default_value("1")) |
| 22 | + .arg(Arg::with_name("max") |
| 23 | + .long("max") |
| 24 | + .help("Maximum trackable value") |
| 25 | + .takes_value(true) |
| 26 | + .default_value(default_max.as_str())) |
| 27 | + .arg(Arg::with_name("sigfig") |
| 28 | + .long("sigfig") |
| 29 | + .help("Number of significant digits") |
| 30 | + .takes_value(true) |
| 31 | + .default_value("3")) |
| 32 | + .arg(Arg::with_name("compression") |
| 33 | + .short("c") |
| 34 | + .long("compression") |
| 35 | + .help("Enable compression")) |
| 36 | + .arg(Arg::with_name("resize") |
| 37 | + .short("r") |
| 38 | + .long("resize") |
| 39 | + .help("Enable auto resize"))) |
| 40 | + .get_matches(); |
| 41 | + |
| 42 | + match matches.subcommand_name() { |
| 43 | + Some("serialize") => { |
| 44 | + let sub_matches = matches.subcommand_matches("serialize").unwrap(); |
| 45 | + let min = sub_matches.value_of("min").unwrap().parse().unwrap(); |
| 46 | + let max = sub_matches.value_of("max").unwrap().parse().unwrap(); |
| 47 | + let sigfig = sub_matches.value_of("sigfig").unwrap().parse().unwrap(); |
| 48 | + |
| 49 | + let mut h: Histogram<u64> = Histogram::new_with_bounds(min, max, sigfig).unwrap(); |
| 50 | + |
| 51 | + if sub_matches.is_present("resize") { |
| 52 | + h.auto(true); |
| 53 | + } |
| 54 | + |
| 55 | + serialize(h, sub_matches.is_present("compression")); |
| 56 | + }, |
| 57 | + _ => unreachable!() |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +fn serialize(mut h: Histogram<u64>, compression: bool) { |
| 62 | + let stdin = std::io::stdin(); |
| 63 | + let stdin_handle = stdin.lock(); |
| 64 | + |
| 65 | + for num in stdin_handle.lines() |
| 66 | + .map(|l| l.expect("Should be able to read stdin")) |
| 67 | + .map(|s| s.parse().expect("Each line must be a u64")) { |
| 68 | + h.record(num).unwrap(); |
| 69 | + } |
| 70 | + |
| 71 | + let stdout = std::io::stdout(); |
| 72 | + let mut stdout_handle = stdout.lock(); |
| 73 | + |
| 74 | + if compression { |
| 75 | + V2DeflateSerializer::new().serialize(&h, &mut stdout_handle).unwrap(); |
| 76 | + } else { |
| 77 | + V2Serializer::new().serialize(&h, &mut stdout_handle).unwrap(); |
| 78 | + } |
| 79 | +} |
0 commit comments