Skip to main content

memory_crystal/
error.rs

1use std::fmt;
2
3/// Core error type for memory-crystal operations.
4#[derive(Debug)]
5pub enum CrystalError {
6    /// I/O error reading or writing tile data.
7    Io(std::io::Error),
8    /// JSON serialization/deserialization error.
9    Json(serde_json::Error),
10    /// A tile was not found in the crystal.
11    TileNotFound(String),
12    /// Invalid argument provided.
13    InvalidArgument(String),
14    /// Corruption detected in tile data.
15    Corruption { tile_id: String, detail: String },
16}
17
18impl fmt::Display for CrystalError {
19    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20        match self {
21            Self::Io(e) => write!(f, "I/O error: {}", e),
22            Self::Json(e) => write!(f, "JSON error: {}", e),
23            Self::TileNotFound(id) => write!(f, "tile not found: {}", id),
24            Self::InvalidArgument(msg) => write!(f, "invalid argument: {}", msg),
25            Self::Corruption { tile_id, detail } => {
26                write!(f, "corruption in tile {}: {}", tile_id, detail)
27            }
28        }
29    }
30}
31
32impl std::error::Error for CrystalError {
33    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
34        match self {
35            Self::Io(e) => Some(e),
36            Self::Json(e) => Some(e),
37            _ => None,
38        }
39    }
40}
41
42impl From<std::io::Error> for CrystalError {
43    fn from(e: std::io::Error) -> Self {
44        Self::Io(e)
45    }
46}
47
48impl From<serde_json::Error> for CrystalError {
49    fn from(e: serde_json::Error) -> Self {
50        Self::Json(e)
51    }
52}
53
54pub type Result<T> = std::result::Result<T, CrystalError>;