lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Plot construction, layout, rendering, and output errors.

use crate::errors::{Diagnostic, OperationFailure};

/// Error returned by plotting operations.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// Filesystem input or output failed.
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),
    /// An adopted local input failed, retaining its actual path and OS cause.
    #[error("{context}: I/O error at {}: {source}", path.display())]
    InputIo {
        /// Actual declaration context, when known.
        context: String,
        /// Local input path.
        path: std::path::PathBuf,
        /// Original I/O error, including its OS error number.
        #[source]
        source: std::io::Error,
    },
    /// Input data or a data-bound visual option is invalid.
    #[error("data error: {0}")]
    Data(Diagnostic),
    /// Layout, backend, font, or output rendering failed.
    #[error("render error: {0}")]
    Render(Diagnostic),
    /// A failure with a separately observable external effect.
    #[error(transparent)]
    Operation(Box<OperationFailure>),
    /// The requested operation was cancelled before completion.
    #[error("operation cancelled")]
    Cancelled,
}

impl Error {
    pub(crate) fn with_prefix(self, prefix: &str) -> Self {
        match self {
            Self::Data(diagnostic) => Self::Data(diagnostic.with_prefix(prefix)),
            Self::Render(diagnostic) => Self::Render(diagnostic.with_prefix(prefix)),
            Self::InputIo {
                context,
                path,
                source,
            } => Self::InputIo {
                context: format!("{prefix}: {context}"),
                path,
                source,
            },
            // The original OS error, cancellation and external effect retain
            // their own identity and error chain.
            other => other,
        }
    }

    pub(crate) fn with_input_path(self, path: &std::path::Path) -> Self {
        match self {
            Self::Io(source) => Self::InputIo {
                context: "reading local input".to_owned(),
                path: path.to_owned(),
                source,
            },
            other => other.with_prefix(&path.display().to_string()),
        }
    }

    /// Inspect the original diagnostic of a data or rendering error.
    pub fn diagnostic(&self) -> Option<&Diagnostic> {
        match self {
            Self::Data(diagnostic) | Self::Render(diagnostic) => Some(diagnostic),
            Self::Operation(failure) => failure.cause().diagnostic(),
            _ => None,
        }
    }
}

impl From<std::convert::Infallible> for Error {
    fn from(value: std::convert::Infallible) -> Self {
        match value {}
    }
}

/// Result returned by plotting operations.
pub type Result<T> = std::result::Result<T, Error>;