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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use std::cell::Cell;
use std::fmt::Display;
use std::io::prelude::*;
use std::io::stdin;
use std::ops::Deref;
use std::str::{from_utf8_unchecked, FromStr};

#[cfg(test)]
mod tests;

/// Simplifies reading and parsing of known input in a speedy fashion.
///
/// Reads all data on standard in into a byte buffer. Provides
/// methods to simplify reading and parsing of lines, specifically
/// aimed to aid in competetive programming where the input is
/// known and correct. Most functions panic if the input is not correct
/// and on the specified format. **Note: FastInput assumes *nix line-endings (`\n`)**.
///
/// FastInput uses interior mutability to allow for zero-copy reading and referencing
/// of string input.
///
/// # Examples
///
/// Creating a new `FastInput` and reading two lines:
///
/// ```no_run
/// // Input:
/// // Hello!
/// // 12 2000
/// use fast_input::{FastInput, FastParse};
///
/// let input = FastInput::new();
/// // Must make into String as next_line returns a slice to the internal buffer
/// // and the second input line advances the internal buffer.
/// let first_line = input.next_line().to_owned();
/// let (a, b): (u32, u32) = input.next();
///
/// println!("First line was: {}, a + b = {}", first_line, a + b);
/// ```
///
/// Mixing `&str` with parseables:
///
/// To facilitate simple, zero-copy reading of string slices, FastInput
/// defines the `Str` type. The following example reads (name, age) (&str, u8) pairs
/// and stores them in a HashMap.
/// ```no_run
/// use fast_input::{FastInput, FastParse, Str};
/// use std::collections::HashMap;
///
/// // Input:
/// // Sven 12
/// // Lorna 22
/// let input = FastInput::new();
/// let mut map = HashMap::new();
/// let (sven, sven_age): (Str, u16) = input.next();
/// let (lorna, lorna_age): (Str, u16) = input.next();
///
/// // Deref the Str to a &str
/// map.insert(*sven, sven_age);
/// map.insert(*lorna, lorna_age);
/// assert_eq!(map["Sven"], 12);
/// ```
pub struct FastInput {
    data: Vec<u8>,
    pos: Cell<usize>,
}

const BUFFER_SIZE: usize = 8196;

#[allow(dead_code)]
impl FastInput {
    /// Creates a new FastInput.
    ///
    /// Upon creation the entire contents of standard input will be read.
    /// The function will block until EOF is reached. If you are using a
    /// terminal you can send EOF using `CTRL + D`. The initial buffer size
    /// is 8196 bytes.
    pub fn new() -> Self {
        FastInput {
            data: FastInput::read_to_end(stdin().lock(), BUFFER_SIZE),
            pos: Cell::new(0),
        }
    }

    /// Creates a new FastInput with a specified buffer size.
    ///
    /// For more information, see [`new`].
    pub fn with_buffer_size(buffer_size: usize) -> Self {
        FastInput {
            data: FastInput::read_to_end(stdin().lock(), buffer_size),
            pos: Cell::new(0),
        }
    }

    /// Creates a new FastInput with a given input that implements
    /// Read
    ///
    /// # Examples
    ///
    /// Creating a FastInput over a byte slice:
    /// ```
    /// use fast_input::{FastInput, FastParse};
    /// use std::io::Read;
    ///
    /// let data = "1 2\n3 4".as_bytes();
    ///
    /// let input = FastInput::with_reader(data);
    ///
    /// let (one, two) = input.next();
    /// let (three, four) = input.next();
    ///
    /// assert_eq!((1, 2), (one, two));
    /// assert_eq!((3, 4), (three, four));
    /// assert_eq!(false, input.has_next_line());
    /// ```
    /// For more information, see [`new`].
    pub fn with_reader<T: Read>(input: T) -> Self {
        FastInput {
            data: FastInput::read_to_end(input, BUFFER_SIZE),
            pos: Cell::new(0),
        }
    }

    /// Reads the next line and returns it.
    ///
    /// # Panics
    ///
    /// The function panics if there is no more data in the buffer.
    /// If you are unsure if there is a next line, see [`has_next_line`].
    pub fn next_line(&self) -> &str {
        if let Some(nline) = self.next_newline() {
            unsafe {
                let pos = self.pos.get();
                let s = from_utf8_unchecked(&self.data[pos..nline]);
                self.pos.set(nline + 1);
                s
            }
        } else {
            unsafe {
                let s = from_utf8_unchecked(&self.data[self.pos.get()..]);
                self.pos.set(self.data.len());
                s
            }
        }
    }

    /// Reads the next line as a single value and parses it.
    ///
    /// # Examples
    ///
    /// Reading an integer:
    /// ```no_run
    /// //Input:
    /// //123
    /// use fast_input::FastInput;
    ///
    /// let input = FastInput::new();
    /// let number: i32 = input.next_parsed();
    /// println!("{}", number);
    /// ```
    pub fn next_parsed<'a, T: FParse<'a>>(&'a self) -> T {
        let mut it = self.next_as_iter();
        it.next().unwrap()
    }





    /// Reads the next line and returns an iterator over the elements of the line.
    ///
    /// # Examples
    ///
    /// Collecting a line into a [`Vec`] of integers.
    /// ```no_run
    /// use fast_input::FastInput;
    ///
    /// let input = FastInput::new();
    /// let numbers: Vec<u32> = input.next_as_iter().collect();
    /// println!("Last line contained {} numbers!", numbers.len());
    /// ```
    /// # Panics
    /// If there is no more data in the buffer. See [`has_next_line`].
    pub fn next_as_iter<'a, T: FParse<'a>>(&'a self) -> impl Iterator<Item = T> + '_ {
        self.next_line().trim().split(' ').map(|x| T::fparse(x))
    }

    /// Reads the next line and returns an iterator over the elements (no parsing).
    ///
    /// # Examples
    ///
    /// Reading a sentence and printing the individual words:
    /// ```no_run
    /// use fast_input::FastInput;
    ///
    /// let input = FastInput::new();
    /// let words = input.next_split();
    /// for (i, word) in words.enumerate() {
    ///     println!("Word {} was: {}", i, word);
    /// }
    /// ```
    /// # Panics
    /// If there is no more data in the buffer. See [`has_next_line`].
    pub fn next_split<'a>(&'a self) -> impl Iterator<Item = &'a str> + '_ {
        self.next_line().trim().split(' ')
    }

    /// Checks if there is more data available in the buffer.
    ///
    /// # Examples
    ///
    /// Reading until EOF:
    /// ```no_run
    /// use fast_input::FastInput;
    ///
    /// let input = FastInput::new();
    /// while input.has_next_line() {
    ///     println!("{}", input.next_line());
    /// }
    /// ```
    pub fn has_next_line(&self) -> bool {
        self.pos.get() != self.data.len()
    }

    fn read_to_end<T: Read>(mut input: T, buffer_size: usize) -> Vec<u8> {
        let mut data = Vec::with_capacity(buffer_size);
        input.read_to_end(&mut data).unwrap();
        data
    }

    fn next_newline(&self) -> Option<usize> {
        let mut i = self.pos.get();
        while i < self.data.len() && self.data[i] != b'\n' {
            i += 1;
        }
        if i < self.data.len() && self.data[i] == b'\n' {
            Some(i)
        } else {
            None
        }
    }

    /// Returns a (consuming) iterator over all remaining lines.
    ///
    /// # Examples
    ///
    /// Printing all lines:
    /// ```rust
    /// use fast_input::FastInput;
    ///
    /// let data = "First\nSecond\nThird".as_bytes();
    /// let input = FastInput::with_reader(data);
    /// let all_lines: Vec<_> = input.lines().collect();
    ///
    /// assert_eq!(&all_lines, &["First", "Second", "Third"]);
    /// assert_eq!(input.has_next_line(), false);
    /// ```
    ///
    pub fn lines<'a>(&'a self) -> impl Iterator<Item = &str> + 'a {
        (0..).take_while(move |_| self.has_next_line())
            .map(move |_| self.next_line())
    }
}

impl Default for FastInput {
    fn default() -> Self {
        Self::new()
    }
}

pub trait FastParse<'a, T> {
    fn next(&'a self) -> T;
}

impl<'a, T1, T2> FastParse<'a, (T1, T2)> for FastInput
where
    T1: FParse<'a>,
    T2: FParse<'a>
{
    /// Reads two elements separated by a space, and returns them parsed as a tuple.
    ///
    /// # Examples
    ///
    /// Reading an `i32` and a `f64`:
    /// ```no_run
    /// use fast_input::{FastInput, FastParse};
    ///
    /// let input = FastInput::new();
    /// let (age, length): (i32, f64) = input.next();
    /// println!("{} {}", age, length);
    /// ```
    /// # Panics
    /// If there is no more data in the buffer. See [`has_next_line`].
    fn next(&'a self) -> (T1, T2) {
        let mut it = self.next_split();
        (
            T1::fparse(it.next().unwrap()),
            T2::fparse(it.next().unwrap()),
        )
    }
}

impl<'a, T1, T2, T3> FastParse<'a, (T1, T2, T3)> for FastInput
where
    T1: FParse<'a>,
    T2: FParse<'a>,
    T3: FParse<'a>
{
    /// Reads three elements separated by a space, and returns them as a triple.
    ///
    /// # Panics
    /// If there is no more data in the buffer. See [`has_next_line`].
    fn next(&'a self) -> (T1, T2, T3) {
        let mut it = self.next_split();
        (
            T1::fparse(it.next().unwrap()),
            T2::fparse(it.next().unwrap()),
            T3::fparse(it.next().unwrap()),
        )
    }
}

impl<'a, T1, T2, T3, T4> FastParse<'a, (T1, T2, T3, T4)> for FastInput
where
    T1: FParse<'a>,
    T2: FParse<'a>,
    T3: FParse<'a>,
    T4: FParse<'a>
{
    /// Reads four elements separated by a space, and returns them as a quad-tuple.
    ///
    /// # Panics
    /// If there is no more data in the buffer. See [`has_next_line`].
    fn next(&'a self) -> (T1, T2, T3, T4) {
        let mut it = self.next_split();
        (
            T1::fparse(it.next().unwrap()),
            T2::fparse(it.next().unwrap()),
            T3::fparse(it.next().unwrap()),
            T4::fparse(it.next().unwrap()),
        )
    }
}

impl<'a, T1, T2, T3, T4, T5> FastParse<'a, (T1, T2, T3, T4, T5)> for FastInput
where
    T1: FParse<'a>,
    T2: FParse<'a>,
    T3: FParse<'a>,
    T4: FParse<'a>,
    T5: FParse<'a>
{
    /// Reads five elements separated by a space, and returns them as a quintuple.
    ///
    /// # Panics
    /// If there is no more data in the buffer. See [`has_next_line`].
    fn next(&'a self) -> (T1, T2, T3, T4, T5) {
        let mut it = self.next_split();
        (
            T1::fparse(it.next().unwrap()),
            T2::fparse(it.next().unwrap()),
            T3::fparse(it.next().unwrap()),
            T4::fparse(it.next().unwrap()),
            T5::fparse(it.next().unwrap()),
        )
    }
}


/// Helper trait for parsing.
/// Mainly used to avoid repeating type constraints.
pub trait FParse<'a> {
    /// Parses a type from a string slice
    fn fparse(s: &'a str) -> Self;
}

impl<'a, T: FromStr> FParse<'a> for T
where
    <T as FromStr>::Err: std::fmt::Debug,
{
    fn fparse(s: &'a str) -> Self {
        s.parse().unwrap()
    }
}

/// Allows reading of string slices (`&str`).
/// The standard library does not provide a `FromStr` implementation
/// for `&str`. The `Str` type newtypes `&str` and implements `FParse`
/// and `Deref<Target = &str>`.
///
/// # Examples
///
/// Reading (name, age, city) triples using `Str` and `FastInput`:
/// ```rust
/// use fast_input::{FastInput, FastParse, Str};
/// let data = "Jakub 26 Mora".as_bytes();
/// let input = FastInput::with_reader(data);
/// let (name, age, city): (Str, u8, Str) = input.next();
/// // Str implements Display
/// println!("The person is called {}, is {} years old and lives in {}", name, age, city);
///
/// //To use any functions related to `&str`, dereference the `Str` into a `&str`
/// let name: &str = *name;
///
/// ```
pub struct Str<'a>(&'a str);

impl<'a> FParse<'a> for Str<'a> {
    fn fparse(s: &'a str) -> Self {
        Str::<'a>(s)
    }
}

impl<'a> Deref for Str<'a> {
    type Target = &'a str;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Display for Str<'_> {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(fmt)
    }
}