use std::{
fmt::Debug,
io::{stdin, stdout, Write},
str::FromStr,
};
pub fn input(output: &str) -> String {
print!("{}", output);
stdout().flush().expect("Flush Failed");
let mut input = String::new();
stdin().read_line(&mut input).expect("Unable to read line!");
input
}
pub fn input_trim(output: &str) -> String {
let str = input(output);
str.trim().to_string()
}
pub fn input_other<T>(output: &str) -> T
where
T: FromStr,
T::Err: Debug,
{
input(output)
.trim()
.parse::<T>()
.expect("Failed to convert value!")
}
pub fn input_other_repeat<T>(output: &str) -> T
where
T: FromStr,
{
let mut input_str = input(output);
loop {
match input_str.trim().parse::<T>() {
Ok(value) => return value,
Err(_) => {
input_str = input(
format!("{} is not a valid input! Try again: ", input_str).as_str(),
);
continue;
}
}
}
}
pub fn input_other_or<T>(output: &str, default: T) -> T
where
T: FromStr,
{
input(output).trim().parse::<T>().unwrap_or(default)
}
pub fn input_other_or_else<T, F: FnOnce() -> T>(output: &str, func: F) -> T
where
T: FromStr,
{
input_other_or(output, func())
}
pub fn input_optional_repeat<T>(output: &str, default: T) -> T
where
T: FromStr,
{
let input = input_trim(output);
loop {
let value: T = match (input.parse(), input.is_empty()) {
(Ok(v), _) => v,
(Err(_), true) => default,
(Err(_), false) => {
println!("Invalid Input!");
continue;
}
};
return value;
}
}