Created
June 6, 2020 21:47
-
-
Save chiragjn/eecf275ddfa70f4cb3e5be1857e2b732 to your computer and use it in GitHub Desktop.
Some Rust stdin input utils for common input formats in competitive programming. Probably not good code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Sample Usages: | |
// https://codeforces.com/contest/1352/submission/82738753 | |
// https://codeforces.com/contest/1352/submission/82737636 | |
use std::io::{self, BufRead, Read, Stdin}; | |
use std::iter; | |
use std::str::FromStr; | |
struct InputUtils { | |
stream: Stdin, | |
buffer: String, | |
} | |
impl Default for InputUtils { | |
fn default() -> Self { | |
return Self { | |
stream: io::stdin(), | |
buffer: String::new(), | |
}; | |
} | |
} | |
impl Iterator for InputUtils { | |
type Item = String; | |
fn next(&mut self) -> Option<Self::Item> { | |
match self.stream.lock().lines().next() { | |
Some(line) => Some(line.unwrap().trim().to_string()), | |
None => None, | |
} | |
} | |
} | |
impl InputUtils { | |
/// read all input into a String buffer and return a reference to it | |
fn read(&mut self) -> &str { | |
self.buffer.clear(); | |
self.stream | |
.lock() | |
.read_to_string(&mut self.buffer) | |
.expect("Failed to read till EOF"); | |
return self.buffer.trim(); | |
} | |
/// generic over read line + parse | |
fn input<T>(&mut self) -> T | |
where | |
T: FromStr, | |
T::Err: std::fmt::Debug, | |
{ | |
return self | |
.into_iter() | |
.next() | |
.unwrap() | |
.parse::<T>() | |
.expect("Failed to parse line to type"); | |
} | |
/// generic over read line + split + parse | |
fn inputs<T>(&mut self, delimiter: Option<&str>) -> Vec<T> | |
where | |
T: FromStr, | |
T::Err: std::fmt::Debug, | |
{ | |
let line = self.into_iter().next().unwrap(); | |
let parts = match delimiter { | |
Some(delim) => line | |
.split(delim) | |
.map(|part| part.parse::<T>().expect("Failed to parse part")) | |
.collect(), | |
None => line | |
.split_whitespace() | |
.map(|part| part.parse::<T>().expect("Failed to parse part")) | |
.collect(), | |
}; | |
return parts; | |
} | |
} | |
macro_rules! print_vec { | |
($x: expr) => { | |
println!( | |
"{}", | |
$x.iter() | |
.map(|x| x.to_string()) | |
.collect::<Vec<String>>() | |
.join(" ") | |
); | |
}; | |
($x:expr, $y:expr) => { | |
println!( | |
"{}", | |
$x.iter() | |
.map(|x| x.to_string()) | |
.collect::<Vec<String>>() | |
.join($y) | |
); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment