use atty::{self, Stream};
use libc::{self, signal};
use std::{fmt::Display, time::SystemTime};
pub fn current_executable() -> String {
std::env::current_exe()
.ok()
.and_then(|abspath| {
abspath
.file_name()
.map(|f| f.to_str().unwrap_or("").to_string())
})
.unwrap_or("".to_string())
}
pub fn panic_on_error<T>(result: std::io::Result<T>) -> T {
result.unwrap_or_else(|error| die!("{}: {}", current_executable(), error))
}
pub fn print_solution(verdict: &str) {
puts!("s {}\n", verdict);
}
pub fn print_key_value(key: &str, value: impl Display) {
requires!(key.len() < 35);
comment!("{:<35} {:>15}", format!("{}:", key), value);
}
pub fn install_signal_handler() {
assert!(unsafe { signal(libc::SIGPIPE, libc::SIG_DFL) } != libc::SIG_ERR);
}
pub fn unreachable() -> ! {
invariant!(false, "unreachable");
unsafe { std::hint::unreachable_unchecked() }
}
pub fn is_a_tty() -> bool {
atty::is(Stream::Stdout)
}
pub struct Timer {
name: &'static str,
start: SystemTime,
pub disabled: bool,
}
impl Timer {
pub fn name(name: &'static str) -> Timer {
Timer {
name,
start: SystemTime::now(),
disabled: false,
}
}
}
impl Drop for Timer {
fn drop(&mut self) {
if self.disabled {
return;
}
let elapsed_time = self.start.elapsed().expect("failed to get time");
print_key_value(
&format!("{} (s)", self.name),
format!(
"{}.{:03}",
elapsed_time.as_secs(),
elapsed_time.subsec_millis()
),
);
}
}