From 84b8328d312ba0f4f4211afba7f7d5689fa01d0d Mon Sep 17 00:00:00 2001 From: runebaas Date: Mon, 28 Oct 2019 00:19:43 +0100 Subject: [PATCH] Add the -w flag --- src/main.rs | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/src/main.rs b/src/main.rs index ab7ad73..233f7b6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,11 +1,13 @@ -use std::fs; +use std::{fs, thread, time}; +use std::convert::TryFrom; use rand::prelude::*; use clap::{Arg, App}; struct Options { filename: String, length: usize, - long_fortunes: bool + long_fortunes: bool, + wait: bool } fn main() { @@ -23,6 +25,7 @@ fn main() { .value_name("file")) .arg(Arg::with_name("length") .short("n") + .long("length") .default_value("160") .help("Set the longest fortune length (in characters) considered to be 'short'. All fortunes longer than this are considered 'long'.") .takes_value(true) @@ -31,7 +34,11 @@ fn main() { .short("l") .long("long") .help("only return long fortunes") - .takes_value(false)); + .takes_value(false)) + .arg(Arg::with_name("wait") + .short("w") + .long("wait") + .help("Wait before termination for an amount of time calculated from the number of characters in the message. (20 characters = 1 second, mim 6 seconds)")); let options = parse_options(app); // get fortunes @@ -47,6 +54,10 @@ fn main() { // get a random one let the_fortune = get_random_fortune(filtered); println!("{}", the_fortune); + + if options.wait { + wait(the_fortune) + } } fn filter_long(x: &str, max_length: usize) -> bool { @@ -62,7 +73,8 @@ fn parse_options(app: App) -> Options { let options: Options = Options { filename: matches.value_of("file").unwrap().to_owned(), length: matches.value_of("length").unwrap().parse::().expect("Length is not a valid number"), - long_fortunes: matches.is_present("long") + long_fortunes: matches.is_present("long"), + wait: matches.is_present("wait") }; return options; @@ -81,3 +93,17 @@ fn get_random_fortune(fortunes: Vec) -> String { return fortunes.get(random_fortune).unwrap().trim().to_owned(); } + +fn wait(fortune: String) { + let characters_per_second = 20; // as defined in the original fortune command + let minimum_wait = 6; // seconds + let mut time_to_wait = fortune.len() / characters_per_second; + if time_to_wait < minimum_wait { + time_to_wait = minimum_wait; + } + + let fortune_length = u64::try_from(time_to_wait).unwrap(); + let time_to_wait = time::Duration::from_secs(fortune_length); + + thread::sleep(time_to_wait); +}