Skip to main content

esoc_chart/
error.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Error types for esoc-chart.
3
4use std::fmt;
5
6/// Errors produced by esoc-chart operations.
7#[derive(Debug)]
8#[non_exhaustive]
9pub enum ChartError {
10    /// No data provided.
11    EmptyData,
12
13    /// Mismatched array lengths.
14    LengthMismatch {
15        /// Expected length.
16        expected: usize,
17        /// Actual length.
18        got: usize,
19    },
20
21    /// Layer contains invalid data (NaN, Inf, etc.).
22    InvalidData {
23        /// Layer index.
24        layer: usize,
25        /// Description of the problem.
26        detail: String,
27    },
28
29    /// X and Y data have different lengths in a layer.
30    DimensionMismatch {
31        /// Layer index.
32        layer: usize,
33        /// X data length.
34        x_len: usize,
35        /// Y data length.
36        y_len: usize,
37    },
38
39    /// Invalid chart parameter.
40    InvalidParameter(String),
41
42    /// Underlying graphics error.
43    Gfx(esoc_gfx::error::GfxError),
44
45    /// I/O error.
46    Io(std::io::Error),
47}
48
49impl fmt::Display for ChartError {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        match self {
52            Self::EmptyData => f.write_str("no data provided"),
53            Self::LengthMismatch { expected, got } => {
54                write!(f, "length mismatch: expected {expected}, got {got}")
55            }
56            Self::InvalidData { layer, detail } => {
57                write!(f, "layer {layer}: {detail}")
58            }
59            Self::DimensionMismatch {
60                layer,
61                x_len,
62                y_len,
63            } => {
64                write!(f, "layer {layer}: x has {x_len} elements but y has {y_len}")
65            }
66            Self::InvalidParameter(msg) => write!(f, "invalid parameter: {msg}"),
67            Self::Gfx(err) => write!(f, "graphics error: {err}"),
68            Self::Io(err) => write!(f, "I/O error: {err}"),
69        }
70    }
71}
72
73impl std::error::Error for ChartError {
74    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
75        match self {
76            Self::Gfx(err) => Some(err),
77            Self::Io(err) => Some(err),
78            _ => None,
79        }
80    }
81}
82
83impl From<esoc_gfx::error::GfxError> for ChartError {
84    fn from(err: esoc_gfx::error::GfxError) -> Self {
85        Self::Gfx(err)
86    }
87}
88
89impl From<std::io::Error> for ChartError {
90    fn from(err: std::io::Error) -> Self {
91        Self::Io(err)
92    }
93}
94
95/// Convenience type alias.
96pub type Result<T> = std::result::Result<T, ChartError>;