From ba84ec2aa315ee53c7dde49256eb1f353f0e877b Mon Sep 17 00:00:00 2001 From: Henrique Kirch Heck <86362827+henriquekirchheck@users.noreply.github.com> Date: Tue, 10 Sep 2024 23:51:01 -0300 Subject: [PATCH] Make code smaller and easier to understand --- src/main.rs | 31 ++++++++++++------------------- 1 file changed, 12 insertions(+), 19 deletions(-) diff --git a/src/main.rs b/src/main.rs index 2a1a409..9c221da 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,9 +6,9 @@ use std::io::{stdin, BufRead, Result}; #[derive(FromArgs)] /// Sample stdin struct SampCli { - #[argh(option, short = 'r')] + #[argh(option, short = 'r', default = "0.5")] /// sample ratio - ratio: Option, + ratio: f32, #[argh(option, short = 's')] /// seed string @@ -18,25 +18,18 @@ struct SampCli { fn main() -> Result<()> { let args: SampCli = argh::from_env(); - let sample_ratio = args.ratio.unwrap_or(0.5); - - let mut rng = if let Some(seed) = args.seed { - Seeder::from(seed).make_rng() - } else { - SipHasher::new().into_rng() + let mut rng = match args.seed { + Some(seed) => Seeder::from(seed).make_rng(), + None => SipHasher::new().into_rng(), }; - let stdin = stdin(); - let mut lines = stdin.lock().lines(); - while let Some(line) = lines.next() { - if let Ok(line) = line { - let dice: f32 = rng.gen(); - if dice < sample_ratio { - println!("{}", line); - } - } else { - break; - } + for line in stdin() + .lock() + .lines() + .filter(|_| rng.gen::() < args.ratio) + { + println!("{}", line?) } + Ok(()) }