Created
March 28, 2021 01:00
-
-
Save qnighy/0fa9dce8ec04973e8bf5d61646ac7e46 to your computer and use it in GitHub Desktop.
stdin.scan() for competitive programming
This file contains 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
use std::io::{self, BufRead}; | |
use std::str::{self, FromStr}; | |
fn from_buf<T: FromStr>(buf: &[u8]) -> io::Result<T> | |
where | |
T::Err: std::error::Error + Send + Sync + 'static, | |
{ | |
let s = str::from_utf8(buf).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; | |
T::from_str(s).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e)) | |
} | |
trait BufReadExt: BufRead { | |
fn skip(&mut self) -> io::Result<()> { | |
loop { | |
let buf = self.fill_buf()?; | |
if buf.is_empty() { | |
return Ok(()); | |
} | |
if let Some(pos) = buf.iter().position(|&c| !c.is_ascii_whitespace()) { | |
self.consume(pos); | |
break; | |
} else { | |
let len = buf.len(); | |
self.consume(len); | |
}; | |
} | |
Ok(()) | |
} | |
fn scan<T: FromStr>(&mut self) -> io::Result<T> | |
where | |
T::Err: std::error::Error + Send + Sync + 'static, | |
{ | |
self.skip()?; | |
let buf = self.fill_buf()?; | |
if let Some(pos) = buf.iter().position(|&c| c.is_ascii_whitespace()) { | |
let x = from_buf(&buf[..pos])?; | |
self.consume(pos); | |
Ok(x) | |
} else { | |
self.scan_slow() | |
} | |
} | |
fn scan_slow<T: FromStr>(&mut self) -> io::Result<T> | |
where | |
T::Err: std::error::Error + Send + Sync + 'static, | |
{ | |
let mut buf = Vec::<u8>::new(); | |
loop { | |
let next = self.fill_buf()?; | |
if next.is_empty() { | |
break; | |
} | |
if let Some(pos) = next.iter().position(|&c| c.is_ascii_whitespace()) { | |
buf.extend_from_slice(&next[..pos]); | |
self.consume(pos); | |
break; | |
} else { | |
buf.extend_from_slice(next); | |
let len = next.len(); | |
self.consume(len); | |
}; | |
} | |
from_buf(&buf) | |
} | |
} | |
impl<T: BufRead + ?Sized> BufReadExt for T {} | |
fn main() -> io::Result<()> { | |
let stdin = std::io::stdin(); | |
let mut stdin = stdin.lock(); | |
let n = stdin.scan::<i32>()?; | |
eprintln!("n = {}", n); | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment