cli_helper 0.1.7

Helper for capturing CLI input
Documentation
use std::io::stdin;
use std::str::FromStr;


/// Get line as [`std::string::String`]
///
/// # Example - Echo utf-8 text
/// ```
/// use cli_helper::cli::get_line;
///
/// fn echo() {
///     println!("Echo: {}", get_line().expect("Your input was likely not UTF-8"))
/// }
/// ```
pub fn get_line() -> Option<String> {
    let mut s = String::new();
    let res = stdin().read_line(&mut s);
    s.pop();
    match res {
        Ok(_) => Some(s),
        Err(_) => None
    }
}

/// Get line of any type that can be [`std::str::parse`]d
///
/// # Example - Echo signed 32bit integer
/// ```
/// use cli_helper::cli::get_line_as;
///
/// fn echo_integer() {
///     println!("Echo: {}", get_line_as::<i32>().expect("Your input was likely not an integer or was larger than {2^31-1}"))
/// }
/// ```
pub fn get_line_as<T: FromStr>() -> Option<T> {
    match get_line() {
        Some(s) => {
            match s.parse::<T>() {
                Ok(t) => Some(t),
                _ => None
            }
        }
        _ => None
    }
}