Skip to main content

rust_hdf5/
error.rs

1//! Error types for the hdf5 public API crate.
2
3/// Errors that can occur when using the HDF5 public API.
4#[derive(Debug)]
5pub enum Hdf5Error {
6    /// An I/O error from the operating system.
7    Io(std::io::Error),
8    /// A low-level format encoding/decoding error.
9    Format(crate::format::FormatError),
10    /// An I/O-layer error from hdf5-io.
11    IoLayer(crate::io::IoError),
12    /// A requested object (dataset, group, attribute) was not found.
13    ///
14    /// The string contains the name of the missing object (e.g., dataset name).
15    NotFound(String),
16    /// The file or object is in an invalid state for the requested operation.
17    InvalidState(String),
18    /// A type mismatch between the Rust type and the HDF5 datatype.
19    TypeMismatch(String),
20}
21
22impl From<std::io::Error> for Hdf5Error {
23    fn from(e: std::io::Error) -> Self {
24        Self::Io(e)
25    }
26}
27
28impl From<crate::format::FormatError> for Hdf5Error {
29    fn from(e: crate::format::FormatError) -> Self {
30        Self::Format(e)
31    }
32}
33
34impl From<crate::io::IoError> for Hdf5Error {
35    fn from(e: crate::io::IoError) -> Self {
36        Self::IoLayer(e)
37    }
38}
39
40impl std::fmt::Display for Hdf5Error {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match self {
43            Self::Io(e) => write!(f, "I/O error: {}", e),
44            Self::Format(e) => write!(f, "format error: {}", e),
45            Self::IoLayer(e) => write!(f, "hdf5-io error: {}", e),
46            Self::NotFound(s) => write!(f, "dataset '{}' not found", s),
47            Self::InvalidState(s) => write!(f, "invalid state: {}", s),
48            Self::TypeMismatch(s) => write!(f, "type mismatch: {}", s),
49        }
50    }
51}
52
53impl std::error::Error for Hdf5Error {}
54
55/// A specialized `Result` type for HDF5 operations.
56pub type Result<T> = std::result::Result<T, Hdf5Error>;
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn display_not_found() {
64        let err = Hdf5Error::NotFound("my_dataset".into());
65        assert!(format!("{}", err).contains("my_dataset"));
66    }
67
68    #[test]
69    fn display_invalid_state() {
70        let err = Hdf5Error::InvalidState("file already closed".into());
71        assert!(format!("{}", err).contains("file already closed"));
72    }
73
74    #[test]
75    fn display_type_mismatch() {
76        let err = Hdf5Error::TypeMismatch("expected f64, got u8".into());
77        assert!(format!("{}", err).contains("expected f64, got u8"));
78    }
79
80    #[test]
81    fn from_io_error() {
82        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "gone");
83        let err: Hdf5Error = io_err.into();
84        match err {
85            Hdf5Error::Io(_) => {}
86            other => panic!("expected Io variant, got: {:?}", other),
87        }
88    }
89}