catch_input/
lib.rs

1//! Library giving an easy way to fetch input from the standard input through the exported [`input`] macro.
2//! 
3//! # Example
4//! ```rust
5//! use catch_input::input;
6//! 
7//! fn main() {
8//!     let input_a = input!("What's your favorite food? ");
9//!     let input_b = input!(|| { print!("What's your favorite drink? ") });
10//!     
11//!     assert!(input_a, String::from("Oatmeal"));
12//!     assert!(input_b, String::from("Water"));
13//!     
14//!     // $ cargo run
15//!     // What's your favorite food? Oatmeal
16//!     // What's your favorite drink? Water
17//! }
18//! ```
19
20use std::io::{self, Write};
21use std::ops::FnOnce;
22
23
24/// Returns a trimmed [`String`] containing the user input from standard input.
25/// You may pass a function that is meant to work as the input prompt.
26/// 
27/// ### **This is meant for implementation in the [`input`] macro, not for external use.**
28/// 
29/// # Example
30/// ```rust
31/// let inp = _get_input_with(|| { print!("Input => "); });
32/// assert!(inp, String::from("Hello, World!"));
33/// ```
34/// The application input would like this...
35/// ```txt
36/// Input => Hello, World!
37/// ```
38#[doc(hidden)]
39pub fn _get_input_with<F: FnOnce()>(prompt: F) -> String {
40    let mut result = String::new(); prompt();
41
42    io::stdout().flush().unwrap();
43    io::stdin().read_line(&mut result)
44        .expect("Failed to read line from Standard Input.");
45    
46    return result.trim().to_string()
47}
48
49
50/// Macro that returns a trimmed [`String`] containing the user input from standard input.
51/// You may pass an argument to be used as a prompt, you may use a [`FnOnce`] or a type with the [`Display`] trait implemented.
52/// 
53/// # Example
54/// ```rust
55/// let input_a = input!("InputA => ");
56/// let input_b = input!(|| { print!("InputB => "); });
57/// 
58/// assert!(input_a, String::from("Hello"))
59/// assert!(input_b, String::from("World"))
60/// 
61/// /*
62/// $ cargo run
63/// InputA => Hello
64/// InputB => World
65/// */
66/// ```
67#[macro_export]
68macro_rules! input {
69    ($x:tt) => { $crate::_get_input_with(|| { print!("{}", $x); }) };
70    ($x:expr) => { $crate::_get_input_with($x) };
71}