mapsample 0.1.0

In-process Windows x64 stack sampler with a rolling stall recorder, P/E-core placement readings, and an MSVC /MAP symbolizer
Documentation
//! The crate's error type.

use std::fmt;
use std::path::PathBuf;

/// Everything that can go wrong in this crate.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    /// A configuration value (a spec, a window, a placement mode, an environment variable) is
    /// malformed. The message names the value.
    InvalidConfig(String),
    /// A dump request is malformed (an empty or path-like name, a non-positive duration).
    InvalidDump(String),
    /// An output name is not a plain file name ([`Profile::write_named`](crate::Profile::write_named)).
    InvalidFileName(String),
    /// The sampler needs Windows on x86-64.
    UnsupportedPlatform,
    /// Another [`Sampler`](crate::Sampler) is running in this process.
    AlreadyRunning,
    /// The sampler thread could not be started.
    Spawn(std::io::Error),
    /// The sampler thread panicked; its profile is lost.
    WorkerPanicked,
    /// The sampler has stopped (or is stopping) and takes no more requests.
    NotRunning,
    /// The per-run dump budget is spent.
    DumpLimit {
        /// The budget ([`Config::max_dumps`](crate::Config::max_dumps)).
        max: usize,
    },
    /// The sampler thread did not answer a blocking dump request in time.
    DumpTimeout,
    /// A file could not be read or written.
    Io {
        /// The file.
        path: PathBuf,
        /// The cause.
        source: std::io::Error,
    },
    /// A linker map could not be parsed.
    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>();
    }
}