Skip to main content

pc_rl_core/
error.rs

1// Author: Julian Bolivar
2// Version: 1.0.0
3// Date: 2026-03-25
4
5//! Crate-wide error type for `pc_rl_core`.
6
7use std::fmt;
8
9/// Crate-wide error type for `pc_rl_core`.
10///
11/// # Examples
12///
13/// ```
14/// use pc_rl_core::error::PcError;
15///
16/// let err = PcError::ConfigValidation("bad topology".to_string());
17/// assert!(format!("{err}").contains("bad topology"));
18/// ```
19#[derive(Debug)]
20pub enum PcError {
21    /// Matrix or vector dimension mismatch.
22    DimensionMismatch {
23        /// Expected dimension.
24        expected: usize,
25        /// Actual dimension.
26        got: usize,
27        /// Human-readable context.
28        context: &'static str,
29    },
30    /// Configuration validation failure.
31    ConfigValidation(String),
32    /// JSON serialization/deserialization error.
33    Serialization(String),
34    /// File I/O error.
35    Io(std::io::Error),
36}
37
38impl fmt::Display for PcError {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        match self {
41            PcError::DimensionMismatch {
42                expected,
43                got,
44                context,
45            } => write!(
46                f,
47                "dimension mismatch in {context}: expected {expected}, got {got}"
48            ),
49            PcError::ConfigValidation(msg) => write!(f, "config validation: {msg}"),
50            PcError::Serialization(msg) => write!(f, "serialization: {msg}"),
51            PcError::Io(e) => write!(f, "I/O error: {e}"),
52        }
53    }
54}
55
56impl std::error::Error for PcError {
57    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
58        match self {
59            PcError::Io(e) => Some(e),
60            _ => None,
61        }
62    }
63}
64
65impl From<std::io::Error> for PcError {
66    fn from(e: std::io::Error) -> Self {
67        PcError::Io(e)
68    }
69}
70
71impl From<serde_json::Error> for PcError {
72    fn from(e: serde_json::Error) -> Self {
73        PcError::Serialization(e.to_string())
74    }
75}