stdin_helper/
lib.rs

1//! Simplify read_line method
2
3pub mod aliases;
4
5use std::io::{self, Write};
6use std::str::FromStr;
7
8pub use aliases::*;
9
10/// ## Core function
11/// 
12/// Ask user for a input until a valid input is detected
13pub fn get_input<T: FromStr>(msg: &str) -> T {
14    let mut input_buffer = String::new();
15
16    loop {
17        input_buffer.clear();
18
19        print!("{msg}");
20        io::stdout().flush().expect("Error on flush");
21
22        io::stdin().read_line(&mut input_buffer).expect("Error reading line");
23
24        match input_buffer.trim().parse::<T>() {
25            Ok(value) => return value,
26
27            _ => continue
28        }
29    }
30}
31
32/// Ask user for a boolean until a valid boolean is detected
33pub fn get_bool(msg: &str) -> bool {
34    let mut input_buffer = String::new();
35
36    loop {
37        input_buffer.clear();
38
39        print!("{msg}");
40        io::stdout().flush().expect("Error on flush");
41
42        io::stdin().read_line(&mut input_buffer).expect("Error reading line");
43
44        match input_buffer.trim().to_lowercase().as_str() {
45            "y" | "yes" | "s" |"sim" | "true" | "1" => return true,
46            "n" | "no" | "not" |"nao" | "false" | "0" => return false,
47
48            _ => continue
49        }
50    }
51}