Skip to main content

imping_ir/
error.rs

1//! The error type returned when reading or writing IR.
2
3use crate::FormatVersion;
4use core::fmt;
5
6/// A `Result` with this crate's [`Error`].
7pub type Result<T> = core::result::Result<T, Error>;
8
9/// An error reading or writing an IR file.
10#[derive(Debug)]
11#[non_exhaustive]
12pub enum Error {
13    /// The IR couldn't be parsed from, or written to, JSON.
14    Json(serde_json::Error),
15    /// The file's major format version isn't [`SUPPORTED_MAJOR`](crate::SUPPORTED_MAJOR).
16    ///
17    /// A different major may be structurally incompatible; see [`FormatVersion`].
18    UnsupportedVersion {
19        /// The version found in the file.
20        found: FormatVersion,
21        /// The major version this crate supports.
22        supported_major: u16,
23    },
24}
25
26impl fmt::Display for Error {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        match self {
29            Error::Json(_) => f.write_str("the IR could not be read or written as JSON"),
30            Error::UnsupportedVersion {
31                found,
32                supported_major,
33            } => write!(
34                f,
35                "unsupported IR format version {}.{} (this reader supports major version {})",
36                found.major, found.minor, supported_major
37            ),
38        }
39    }
40}
41
42impl core::error::Error for Error {
43    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
44        match self {
45            Error::Json(error) => Some(error),
46            Error::UnsupportedVersion { .. } => None,
47        }
48    }
49}
50
51impl From<serde_json::Error> for Error {
52    fn from(error: serde_json::Error) -> Self {
53        Error::Json(error)
54    }
55}