Skip to main content

stdin_helper/
lib.rs

1use std::error::Error;
2use std::io::{self, Write};
3use std::str::FromStr;
4
5mod numeric;
6
7mod erro;
8pub use erro::{InputError, BoolParseError};
9pub mod aliases;
10pub use aliases::*;
11
12pub type InputResult<T> = Result<T, InputError< <T as FromStr>::Err> >;
13
14
15pub fn get_input<T>(msg: &str, repeat_until_valid: bool) -> Result<T, InputError<T::Err>>
16where 
17    T: FromStr,
18    T::Err: Error
19{
20    let mut input_buffer = String::new();
21
22    loop {
23        input_buffer.clear();
24
25        print!("{msg}");
26        io::stdout().flush()?;
27
28        io::stdin().read_line(&mut input_buffer)?;
29        
30        match input_buffer.trim().parse::<T>() {
31            Ok(input) => return Ok(input),
32
33            Err(error_msg) => if repeat_until_valid {continue} else { return Err(InputError::Parse(error_msg))}
34        }
35    }
36}