1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
//! Provides `input!` macro.
//!
//! # Example
//!
//! ```no_run
//! #[macro_use]
//! extern crate input as _;
//!
//! use input::Usize1;
//!
//! fn main() {
//!     // https://atcoder.jp/contests/abc166/tasks/abc166_b
//!
//!     input! {
//!         n: usize,
//!         //ass: [[{ |n: usize| n - 1 }]],
//!         ass: [[Usize1]],
//!     }
//!
//!     let _: usize = n;
//!     let _: Vec<Vec<usize>> = ass;
//! }
//! ```

use std::{
    cell::RefCell,
    fmt::Debug,
    io::{self, BufRead, Read},
    rc::Rc,
    str::{FromStr, SplitWhitespace},
};

/// A `input!` macro.
#[macro_export]
macro_rules! input {
    (from $scanner:ident; $($tt:tt)*) => {
        $crate::__input_inner!(@scanner($scanner), @tts($($tt)*))
    };
    ($($tt:tt)*) => {
        let __scanner = $crate::DEFAULT_SCANNER.with(|__scanner| __scanner.clone());
        let mut __scanner_ref = __scanner.borrow_mut();
        if let $crate::Scanner::Uninited = *__scanner_ref {
            *__scanner_ref = $crate::Scanner::stdin_auto().unwrap();
        }
        $crate::__input_inner!(@scanner(__scanner_ref), @tts($($tt)*));
        ::std::mem::drop(__scanner_ref);
        ::std::mem::drop(__scanner);
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __input_inner {
    (@scanner($scanner:ident), @tts()) => {};
    (@scanner($scanner:ident), @tts(mut $single_tt_pat:tt : $readable:tt)) => {
        let mut $single_tt_pat = $crate::__read!(from $scanner { $readable });
    };
    (@scanner($scanner:ident), @tts($single_tt_pat:tt : $readable:tt)) => {
        let $single_tt_pat = $crate::__read!(from $scanner { $readable });
    };
    (@scanner($scanner:ident), @tts(mut $single_tt_pat:tt : $readable:tt, $($rest:tt)*)) => {
        $crate::__input_inner!(@scanner($scanner), @tts(mut $single_tt_pat: $readable));
        $crate::__input_inner!(@scanner($scanner), @tts($($rest)*));
    };
    (@scanner($scanner:ident), @tts($single_tt_pat:tt : $readable:tt, $($rest:tt)*)) => {
        $crate::__input_inner!(@scanner($scanner), @tts($single_tt_pat: $readable));
        $crate::__input_inner!(@scanner($scanner), @tts($($rest)*));
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __read {
    (from $scanner:ident { [$tt:tt] }) => {
        $crate::__read!(from $scanner { [$tt; $crate::__read!(from $scanner { usize })] })
    };
    (from $scanner:ident  { [$tt:tt; $n:expr] }) => {
        (0..$n).map(|_| $crate::__read!(from $scanner { $tt })).collect::<Vec<_>>()
    };
    (from $scanner:ident { ($($tt:tt),+) }) => {
        ($($crate::__read!(from $scanner { $tt })),*)
    };
    (from $scanner:ident { { $f:expr } }) => {
        $crate::FnOnceExt::<_>::call_once_from_reader($f, &mut $scanner)
    };
    (from $scanner:ident { $ty:ty }) => {
        <$ty as $crate::Readable>::read(|| $scanner.next_unwrap())
    };
}

#[deprecated(note = "Use `Usize1` instead")]
#[inline]
pub fn usize1(n: usize) -> usize {
    n - 1
}

#[deprecated(note = "Use `Bytes` instead")]
#[inline]
pub fn bytes(s: String) -> Vec<u8> {
    s.into()
}

#[doc(hidden)]
pub trait FnOnceExt<A> {
    type Output;
    fn call_once_from_reader(this: Self, scanner: &mut Scanner) -> Self::Output;
}

impl<A, O, F> FnOnceExt<A> for F
where
    A: FromStr,
    A::Err: Debug,
    F: FnOnce(A) -> O,
{
    type Output = O;

    #[inline]
    fn call_once_from_reader(this: Self, scanner: &mut Scanner) -> O {
        this(scanner.next_unwrap().parse().unwrap())
    }
}

#[doc(hidden)]
pub enum Scanner {
    Uninited,
    Once {
        words: SplitWhitespace<'static>,
    },
    Lines {
        rdr: Box<dyn BufRead>,
        words: SplitWhitespace<'static>,
    },
}

impl Scanner {
    pub fn stdin_auto() -> io::Result<Self> {
        if cfg!(debug_assertions) {
            Ok(Self::lines(Box::leak(Box::new(io::stdin())).lock()))
        } else {
            Self::once(io::stdin())
        }
    }

    pub fn once<R: Read>(mut rdr: R) -> io::Result<Self> {
        let mut buf = String::with_capacity(1024);
        rdr.read_to_string(&mut buf)?;
        let words = Box::leak(buf.into_boxed_str()).split_whitespace();
        Ok(Self::Once { words })
    }

    pub fn lines<R: BufRead + 'static>(rdr: R) -> Self {
        Self::Lines {
            rdr: Box::new(rdr),
            words: "".split_whitespace(),
        }
    }

    pub fn next_unwrap(&mut self) -> &'static str {
        match self {
            Self::Uninited => None,
            Self::Once { words } => words.next(),
            Self::Lines { rdr, words } => words.next().or_else(|| {
                let mut line = "".to_owned();
                rdr.read_line(&mut line).unwrap();
                *words = Box::leak(line.into_boxed_str()).split_whitespace();
                words.next()
            }),
        }
        .expect("reached EOF")
    }
}

thread_local! {
    #[doc(hidden)]
    pub static DEFAULT_SCANNER: Rc<RefCell<Scanner>> = Rc::new(RefCell::new(Scanner::Uninited));
}

/// A trait representing which type can be read.
pub trait Readable {
    type Output;

    fn read<'a, F: FnMut() -> &'a str>(get: F) -> Self::Output;
}

impl<T: FromStr> Readable for T
where
    T::Err: Debug,
{
    type Output = Self;

    fn read<'a, F: FnMut() -> &'a str>(mut get: F) -> Self {
        get().parse().unwrap()
    }
}

/// 1-based index.
pub enum Usize1 {}

impl Readable for Usize1 {
    type Output = usize;

    fn read<'a, F: FnMut() -> &'a str>(get: F) -> usize {
        usize::read(get) - 1
    }
}

/// Reads a string as `Vec<u8>`.
pub enum Bytes {}

impl Readable for Bytes {
    type Output = Vec<u8>;

    fn read<'a, F: FnMut() -> &'a str>(mut get: F) -> Vec<u8> {
        get().into()
    }
}