halite3bdk/
input.rs

1use crate::logger;
2use std::io::stdin;
3use std::str::FromStr;
4
5pub struct Input {
6    tokens: Vec<String>,
7    current_index: usize,
8}
9
10impl Input {
11    pub fn new() -> Self {
12        Self {
13            tokens: vec![],
14            current_index: 0,
15        }
16    }
17
18    pub fn read_line(&self) -> String {
19        let mut buffer = String::new();
20
21        match stdin().read_line(&mut buffer) {
22            Ok(_) => logger::info(&format!("read line: {}", &buffer)),
23            Err(_) => logger::abort("server connection closed, exiting"),
24        };
25
26        buffer
27    }
28
29    pub fn parse_line(&mut self) {
30        let line = self.read_line();
31
32        self.tokens = line
33            .split_whitespace()
34            .filter(|c| !c.is_empty())
35            .map(|c| c.to_string())
36            .collect();
37
38        self.current_index = 0;
39    }
40
41    pub fn next<T: FromStr>(&mut self) -> T {
42        let token = &self.tokens[self.current_index];
43        self.current_index += 1;
44
45        let result = token
46            .parse()
47            .unwrap_or_else(|_| logger::abort("server connection closed, exiting"));
48
49        result
50    }
51
52    pub fn next_u32(&mut self) -> u32 {
53        self.next()
54    }
55
56    pub fn next_usize(&mut self) -> usize {
57        self.next()
58    }
59}