py_like/
io.rs

1#![allow(unused)]
2
3use std::error::Error;
4use std::fmt::{Debug, Display};
5use std::io::{self, Write};
6use std::str::FromStr;
7
8pub fn input() -> String {
9    let mut inner = String::new();
10    std::io::stdin()
11        .read_line(&mut inner)
12        .expect("Failed to read from stdin");
13    inner
14}
15
16/// Yandros - users.rust-lang.org
17/// https://users.rust-lang.org/t/why-is-it-so-difficult-to-get-user-input-in-rust/27444/3
18///
19/// # Usage
20pub fn input_prompt(prompt: &'_ impl Display) -> String {
21    print!("{}", prompt);
22    std::io::stdout().flush().expect("Flush failed");
23    let mut ret = String::new();
24    std::io::stdin()
25        .read_line(&mut ret)
26        .expect("Failed to read from stdin");
27    ret
28}
29
30/// alice - users.rust-lang.org
31/// https://users.rust-lang.org/t/why-is-it-so-difficult-to-get-user-input-in-rust/27444/3
32pub fn input_ok<T: FromStr>() -> Result<T, Box<dyn Error>>
33where
34    <T as FromStr>::Err: Error + 'static,
35{
36    let mut input = String::new();
37    io::stdin().read_line(&mut input)?;
38    // Handle the errors outside
39    Ok(input.trim().parse()?)
40}
41
42pub fn input_from<T: FromStr>() -> T
43where
44    <T as FromStr>::Err: Debug + 'static,
45{
46    let mut input = String::new();
47    io::stdin()
48        .read_line(&mut input)
49        .expect("Failed to read from stdin");
50    input.trim().parse().unwrap()
51}
52
53/// coder3101 - stackoverflow.com
54/// https://stackoverflow.com/questions/30355185/how-to-read-an-integer-input-from-the-user-in-rust-1-0
55#[macro_export] // export to the root of the crate
56macro_rules! read {
57    ($out:ident as $type:ty) => {
58        let $out = {
59            let mut inner = String::new();
60            std::io::stdin().read_line(&mut inner).expect("a String");
61            inner.trim().parse::<$type>().expect("Parsable")
62        };
63    };
64}
65
66#[macro_export]
67macro_rules! read_str {
68    ($out:ident) => {
69        let $out = {
70            let mut inner = String::new();
71            std::io::stdin().read_line(&mut inner).expect("a String");
72            inner.trim().to_string()
73        };
74    };
75}
76
77#[macro_export]
78macro_rules! read_vec {
79    ($out:ident as $type:ty) => {
80        let $out = {
81            let mut inner = String::new();
82            std::io::stdin().read_line(&mut inner).unwrap();
83            inner
84                .trim()
85                .split_whitespace()
86                .map(|s| s.parse::<$type>().unwrap())
87                .collect::<Vec<$type>>()
88        };
89    };
90}