Skip to content

Instantly share code, notes, and snippets.

@matematikaadit
Last active March 25, 2017 17:30
Show Gist options
  • Save matematikaadit/6205aa970a8a162df76e183494f7a8ec to your computer and use it in GitHub Desktop.
Save matematikaadit/6205aa970a8a162df76e183494f7a8ec to your computer and use it in GitHub Desktop.
Easy Input Whitespace Sparated.
// token (e.g. integer) sparated by whitespace
mod input {
use std::io::{self, Read};
pub struct Mem {
buf: Vec<u8>,
cur: usize,
}
impl Mem {
pub fn new() -> Self {
let mut buf = Vec::new();
let mut stdin = io::stdin();
let _ = stdin.read_to_end(&mut buf);
Mem { buf: buf, cur: 0 }
}
pub fn get(&mut self) -> i64 {
let mut cur = self.cur;
let mut sign = 1;
let mut result = 0;
while self.buf[cur] < b'0' || self.buf[cur] > b'9' {
if self.buf[cur] == b'-' {
sign = -1;
}
cur += 1;
}
while self.buf[cur] >= b'0' && self.buf[cur] <= b'9' {
result = result * 10 + (self.buf[cur] - b'0') as i64;
cur += 1;
}
self.cur = cur;
sign * result
}
}
}
// token (e.g. integer) sparated by whitespace
mod input {
use std::io::{self, BufRead};
use std::str::FromStr;
use std::collections::VecDeque;
pub struct Input {
buf: VecDeque<String>
}
impl Input {
pub fn new() -> Self {
Input { buf: VecDeque::new() }
}
pub fn get<T: FromStr>(&mut self) -> T {
match self.buf.pop_front() {
None => {
let stdin = io::stdin();
let stdin = stdin.lock();
let mut lines = stdin.lines();
let first_line = lines.next().unwrap().unwrap();
let mut words = first_line.split_whitespace();
let first_word = words.next().unwrap();
let result = first_word.parse().ok().unwrap();
self.buf = words.map(|s| String::from(s)).collect();
result
},
Some(s) => s.parse().ok().unwrap(),
}
}
}
}
// I'm sure this code is inspired by someone's solution in some online judge, tho I can't remember which one.
// credit for that person.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment