Skip to main content

dmap/
error.rs

1//! Error type for `dmap`.
2#[cfg(feature = "python")]
3use pyo3::exceptions::{PyIOError, PyValueError};
4#[cfg(feature = "python")]
5use pyo3::PyErr;
6use thiserror::Error;
7
8/// Enum of the possible error variants that may be encountered.
9#[derive(Error, Debug)]
10pub enum DmapError {
11    /// Represents invalid conditions when reading from input.
12    #[error("{0}")]
13    CorruptStream(&'static str),
14
15    /// Unable to read from a buffer.
16    #[error(transparent)]
17    Io(#[from] std::io::Error),
18
19    /// Error casting between Dmap types.
20    #[error(transparent)]
21    BadCast(#[from] std::num::TryFromIntError),
22
23    /// Invalid key for a DMAP type. Valid keys are defined [here](https://github.com/SuperDARN/rst/blob/main/codebase/general/src.lib/dmap.1.25/include/dmap.h)
24    #[error("{0}")]
25    InvalidKey(i8),
26
27    /// An issue with parsing a record. This is a broad error that is returned by higher-level
28    /// functions (ones that are reading/writing files, as opposed to single-record operations).
29    #[error("{0}")]
30    InvalidRecord(String),
31
32    /// Error interpreting data as a valid DMAP scalar.
33    #[error("{0}")]
34    InvalidScalar(String),
35
36    /// Error interpreting data as a valid DMAP vector.
37    #[error("{0}")]
38    InvalidVector(String),
39
40    /// Bytes cannot be interpreted as a DMAP field.
41    #[error("{0}")]
42    InvalidField(String),
43
44    /// Index out of bounds.
45    #[error("{0}")]
46    InvalidIndex(i32),
47
48    /// Errors when reading in multiple records
49    #[error("First error: {1}\nRecords with errors: {0:?}")]
50    BadRecords(Vec<usize>, String),
51}
52
53#[cfg(feature = "python")]
54impl From<DmapError> for PyErr {
55    fn from(value: DmapError) -> Self {
56        let msg = value.to_string();
57        match value {
58            DmapError::CorruptStream(..) => PyIOError::new_err(msg),
59            DmapError::Io(..) => PyIOError::new_err(msg),
60            _ => PyValueError::new_err(msg),
61        }
62    }
63}