use std::fmt;
use std::path::PathBuf;
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
InvalidConfig(String),
InvalidDump(String),
InvalidFileName(String),
UnsupportedPlatform,
AlreadyRunning,
Spawn(std::io::Error),
WorkerPanicked,
NotRunning,
DumpLimit {
max: usize,
},
DumpTimeout,
Io {
path: PathBuf,
source: std::io::Error,
},
InvalidMap(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidConfig(message) => write!(f, "invalid configuration: {message}"),
Self::InvalidDump(message) => write!(f, "invalid dump request: {message}"),
Self::InvalidFileName(message) => write!(f, "invalid file name: {message}"),
Self::UnsupportedPlatform => f.write_str("the sampler needs Windows on x86-64"),
Self::AlreadyRunning => f.write_str("a sampler is already running in this process"),
Self::Spawn(error) => write!(f, "cannot start the sampler thread: {error}"),
Self::WorkerPanicked => f.write_str("the sampler thread panicked"),
Self::NotRunning => f.write_str("the sampler is not running"),
Self::DumpLimit { max } => write!(f, "the dump budget of {max} per run is spent"),
Self::DumpTimeout => f.write_str("the sampler did not write the dump in time"),
Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
Self::InvalidMap(message) => write!(f, "invalid linker map: {message}"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Spawn(error) | Self::Io { source: error, .. } => Some(error),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::error::Error as _;
#[test]
fn display_and_source() {
let io = Error::Io {
path: PathBuf::from("out/samples.txt"),
source: std::io::Error::other("disk full"),
};
assert_eq!(
io.to_string(),
format!("{}: disk full", PathBuf::from("out/samples.txt").display())
);
assert!(io.source().is_some());
assert!(Error::AlreadyRunning.source().is_none());
assert_eq!(
Error::DumpLimit { max: 8 }.to_string(),
"the dump budget of 8 per run is spent"
);
assert!(Error::UnsupportedPlatform.to_string().contains("x86-64"));
}
#[test]
fn error_is_send_and_sync() {
fn check<T: Send + Sync + 'static>() {}
check::<Error>();
}
}