rust_prompt/
lib.rs

1use std::io::{self, Write};
2use std::str::FromStr;
3
4/// Custom error type for input parsing.
5pub enum InputError {
6    IoError(io::Error),
7    ParseError(String),
8}
9
10/// Function to get input and parse it into the desired type.
11pub fn parse_input<T: FromStr>(prompt: &str) -> Result<T, InputError>
12where
13    <T as FromStr>::Err: ToString,
14{
15    print!("{}", prompt);
16    io::stdout().flush().map_err(InputError::IoError)?;
17
18    let mut input = String::new();
19    io::stdin().read_line(&mut input).map_err(InputError::IoError)?;
20
21    input.trim().parse::<T>().map_err(|e| InputError::ParseError(e.to_string()))
22}
23
24/// Macro to simplify calling the parse_input function.
25#[macro_export]
26macro_rules! parse_input {
27    ($prompt:expr) => {
28        $crate::parse_input::<_>($prompt)
29    };
30}
31
32#[cfg(test)]
33mod tests {
34    // Example test for successful parsing
35    #[test]
36    fn test_parse_input_success() {
37        let result = "42".parse::<f64>();
38        assert_eq!(result, Ok(42.));
39    }
40
41    // Example test for failed parsing
42    #[test]
43    fn test_parse_input_failure() {
44        let result = "abc".parse::<i32>();
45        assert!(result.is_err());
46    }
47
48}