Skip to content

Instantly share code, notes, and snippets.

@hareeen
Last active February 23, 2024 13:55
Show Gist options
  • Save hareeen/f8cc37b7203c505b1488cd654c4897a3 to your computer and use it in GitHub Desktop.
Save hareeen/f8cc37b7203c505b1488cd654c4897a3 to your computer and use it in GitHub Desktop.
Rust I/O template for competitive programming
// ✦☁️
use std::{
cell::RefCell,
fmt::Debug,
io::{stdin, stdout, BufRead, BufReader, BufWriter, StdinLock, StdoutLock, Write},
mem::transmute,
str::FromStr,
str::{from_utf8_unchecked, SplitWhitespace},
};
thread_local! {
static BUFFER: RefCell<(Vec<u8>, SplitWhitespace<'static>)> = RefCell::new((vec![], "".split_whitespace()));
static READER: RefCell<BufReader<StdinLock<'static>>> = RefCell::new(BufReader::new(stdin().lock()));
static WRITER: RefCell<BufWriter<StdoutLock<'static>>> = RefCell::new(BufWriter::new(stdout().lock()));
}
#[allow(dead_code)]
fn next<T>() -> T
where
T: FromStr,
T::Err: Debug,
{
BUFFER.with(|buffer_cell| loop {
let (raw, stream) = &mut *buffer_cell.borrow_mut();
if let Some(token) = stream.next() {
return token.parse().unwrap();
}
raw.clear();
READER.with(|reader_cell| reader_cell.borrow_mut().read_until(b'\n', raw).unwrap());
*stream = unsafe {
let slice = from_utf8_unchecked(&raw);
transmute(slice.split_whitespace())
};
})
}
#[allow(dead_code)]
fn take<T>(n: usize) -> impl ExactSizeIterator<Item = T> + DoubleEndedIterator<Item = T>
where
T: FromStr,
T::Err: Debug,
{
(0..n).map(|_| next::<T>())
}
#[allow(unused_macros)]
macro_rules! print {
($($arg:tt)*) => {
WRITER.with(|writer_cell| write!(writer_cell.borrow_mut(), $($arg)*).unwrap())
};
}
#[allow(unused_macros)]
macro_rules! println {
($($arg:tt)*) => {
WRITER.with(|writer_cell| writeln!(writer_cell.borrow_mut(), $($arg)*).unwrap())
};
}
#[allow(unused_macros)]
macro_rules! flush {
() => {
WRITER.with(|writer_cell| writer_cell.borrow_mut().flush().unwrap())
};
}
fn main() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment