use opts;
use std::{borrow::Cow, fmt, time::SystemTime};
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Success {
Bytes {
bytes: usize,
start: SystemTime,
},
Unblock {
blocks: usize,
block_size: usize,
start: SystemTime,
},
Block {
lines: usize,
truncated: usize,
padded: usize,
block_size: usize,
start: SystemTime,
},
}
#[derive(Debug)]
pub enum Error {
IO(std::io::Error),
Opt(opts::Error),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::IO(err) => write!(f, "io error: {}", err),
Error::Opt(err) => write!(f, "command line argument error: {}", err),
}
}
}
impl From<std::io::Error> for Error {
fn from(err: ::std::io::Error) -> Self { Error::IO(err) }
}
impl From<opts::Error> for Error {
fn from(err: opts::Error) -> Self { Error::Opt(err) }
}
impl std::error::Error for Error {}
impl fmt::Display for Success {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Success::Bytes { bytes, start } => write!(f, "wrote {} bytes in {}", bytes, elapsed(start)),
Success::Block {
lines,
truncated,
padded,
block_size,
start,
} => write!(
f,
concat!(
"Wrote {lines} lines of length {len} in {seconds}.\n",
"Padded {padded}/{len} lines\n",
"Truncated {truncated}/{len} lines\n"
),
lines = lines,
truncated = truncated,
len = block_size,
padded = padded,
seconds = elapsed(start),
),
Success::Unblock {
blocks,
block_size,
start,
} => write!(
f,
"wrote {} records of fixed size {} in {}",
blocks,
block_size,
elapsed(start)
),
}
}
}
pub fn elapsed(start: &SystemTime) -> Cow<'static, str> {
match start.elapsed() {
Ok(elapsed) => Cow::Owned(format!("{}.{:03} seconds", elapsed.as_secs(), elapsed.subsec_millis())),
_ => Cow::Borrowed("<error obtaining elapsed time>"),
}
}