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
use crate::error::{Error, Result};
/// Input is a helper struct for parsing input.
/// It is used by the generators to parse the input string.
/// It ignores different kinds of whitespace.
pub struct Input {
iter: std::vec::IntoIter<String>,
}
impl Input {
pub(super) fn new(input_str: &str) -> Self {
Self {
iter: input_str.split_whitespace().map(std::borrow::ToOwned::to_owned).collect::<Vec<_>>().into_iter(),
}
}
/// This function returns the next integer in the input.
/// If there is no next integer, it returns an error.
pub fn get_int(&mut self) -> Result<i32> {
self.iter
.next()
.ok_or(Error::InputExpectedInteger)
.and_then(|s| s.parse().map_err(|_err| Error::InputExpectedInteger))
}
/// This function returns the next float in the input.
/// If there is no next float, it returns an error.
pub fn get_float(&mut self) -> Result<f32> {
self.iter
.next()
.ok_or(Error::InputExpectedFloat)
.and_then(|s| s.parse().map_err(|_err| Error::InputExpectedFloat))
}
/// This function returns the next string in the input.
/// If there is no next string, it returns an error.
pub fn get_string(&mut self) -> Result<String> {
self.iter.next().ok_or(Error::InputExpectedString)
}
/// This function expects the end of the input.
/// If the input didn't end yet it returns an error.
pub fn expect_end(&mut self) -> Result<()> {
self.iter.clone().peekable().peek().is_none().then_some(()).ok_or(Error::InputExpectedEnd)
}
/// This function returns the next n integers in the input.
/// If there are less than n integers in the input, it returns an error.
pub fn get_ints(&mut self, n: i32) -> Result<Vec<i32>> {
let mut result = Vec::new();
for _ in 0..n {
let next = self.get_int();
if let Ok(next) = next {
result.push(next);
} else {
return Err(Error::ExpectedIntegers { n });
}
}
Ok(result)
}
/// This function reads the first integer in the input and returns the next n integers in the input.
/// If there are less than n integers in the input or no integer in the beginning, it returns an error.
pub fn get_array(&mut self) -> Result<Vec<i32>> {
let n = self.get_int()?;
self.get_ints(n)
}
}