stdin_helper/
lib.rs

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