# -*- mode: snippet -*-
# name: Input parser
# contributor: Tanaka Hideyuki
# key: input
# --

/// Input parser.
///
/// # Example
///
/// ```ignore
/// n
/// v_0 v_1 ... v_n-1
/// ```
///
/// This data is parsed by following parser:
///
///
/// ```
/// # #[macro_use] extern crate competitive;
/// input!{
/// # source = "0",
///     n: usize,
///     v: [i64; n],
/// }
/// ```
///
/// # Supported Types
///
/// * FromStr types
/// * `usize1`: 1-origin usize (automatically converted to 0-origin)
/// * (t1, t2, ..., tn): Tuple
/// * `[type; len]`: Array of `type` with `len` (has type Vec<type>)
/// * `chars`: Array of char (converted fron `String`, has type Vec<char>)
/// * `bytes`: Array of byte (converted fron `String`, has type Vec<u8>)
///
#[macro_export]
// #[snippet(name = "input")]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, bytes) => {
        read_value!($next, String).into_bytes()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}
