console_input/
standard.rs

1use std::{
2    io::{self, Write},
3    str::FromStr,
4};
5
6/// Get a standard text input from the user. Appears inline, returns the trimmed user string
7///
8/// # Panics
9/// This function panics if it fails to flush stdout or to read stdin
10#[must_use]
11pub fn get_text_input(prompt: &str) -> String {
12    print!("{prompt}");
13    io::stdout().flush().expect("Failed to flush line");
14
15    let mut input = String::new();
16
17    io::stdin()
18        .read_line(&mut input)
19        .expect("Failed to read line");
20
21    input.trim().to_string()
22}
23
24/// Get a standard text input from the user. Appears inline. Directly passes the result from `str.parse()`. If you want to keep prompting until the user submits a value that fits the chosen type
25///
26/// ## Errors
27/// Returns the result of a parse method, so the error will depend on what you want to parse to
28pub fn get_text_input_as<Output: FromStr>(prompt: &str) -> Result<Output, Output::Err> {
29    get_text_input(prompt).parse()
30}
31
32/// Get a standard text input from the user. Unlike [`get_text_input_as`], this function will continue prompting until the user submits a value that fits the chosen type
33#[must_use]
34pub fn persistent_get_text_input_as<Output: FromStr>(prompt: &str) -> Output {
35    loop {
36        match get_text_input_as::<Output>(prompt) {
37            Ok(user_output) => return user_output,
38            Err(_) => continue,
39        }
40    }
41}