Skip to main content

simput/
lib.rs

1#[doc(hidden)]
2pub fn _read_stdin_until_delim() -> std::io::Result<Vec<u8>> {
3    use std::io::BufRead;
4    let mut buffer = Vec::new();
5    let stdin_raw = std::io::stdin();
6    let mut stdin = stdin_raw.lock();
7    loop {
8        let (done, used) = {
9            let available = match stdin.fill_buf() {
10                Ok(n) => n,
11                Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
12                Err(e) => return Err(e),
13            };
14            let space = memchr::memchr(b' ', available);
15            let newline = memchr::memchr(b'\n', available);
16            let count = match (space, newline) {
17                (Some(s), Some(n)) => {
18                    let i = std::cmp::min(s, n);
19                    Some(i)
20                }
21                _ => space.or(newline),
22            };
23            if let Some(count) = count {
24                buffer.extend_from_slice(&available[..count]);
25                (true, count + 1)
26            } else {
27                buffer.extend_from_slice(available);
28                (false, available.len())
29            }
30        };
31        stdin.consume(used);
32        if done || used == 0 {
33            return Ok(buffer);
34        }
35    }
36}
37
38/// Reads input from standard input, split by ascii space and newline character
39///
40/// # Example
41///
42/// ```
43/// use simput::input;
44/// let (line_of_string, string_piece, integer, decimal) = input!(Line, String, i32, f32);
45#[macro_export]
46macro_rules! input {
47    (inner Line) => {{
48        use std::io::BufRead;
49        let mut buffer = Vec::new();
50        std::io::stdin().lock().read_until(b'\n', &mut buffer).unwrap();
51        std::str::from_utf8(&buffer).unwrap().trim_end().to_string()
52    }};
53    (inner $t:ty) => {{
54        let buffer = simput::_read_stdin_until_delim().unwrap();
55        std::str::from_utf8(&buffer).unwrap().parse::<$t>().unwrap()
56    }};
57    ($($t:tt),*) => (($(simput::input!(inner $t)),*));
58}