Skip to main content

recern_vector/
error.rs

1use std::fmt;
2use std::io;
3use std::path::PathBuf;
4
5pub type Result<T> = std::result::Result<T, Error>;
6
7#[derive(Debug)]
8pub enum Error {
9    Io(io::Error),
10    /// The file exists but is not a valid Recern Vector database.
11    Corrupt(String),
12    /// The file was written by a newer, incompatible format version.
13    UnsupportedVersion(u32),
14    FileExists(PathBuf),
15    CollectionExists(String),
16    CollectionNotFound(String),
17    DimensionMismatch {
18        expected: usize,
19        actual: usize,
20    },
21    InvalidVector(String),
22    InvalidArgument(String),
23}
24
25impl fmt::Display for Error {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        match self {
28            Error::Io(err) => write!(f, "I/O error: {err}"),
29            Error::Corrupt(reason) => write!(f, "corrupt database file: {reason}"),
30            Error::UnsupportedVersion(version) => {
31                write!(f, "unsupported file format version {version}")
32            }
33            Error::FileExists(path) => write!(f, "file already exists: {}", path.display()),
34            Error::CollectionExists(name) => write!(f, "collection already exists: {name}"),
35            Error::CollectionNotFound(name) => write!(f, "collection not found: {name}"),
36            Error::DimensionMismatch { expected, actual } => {
37                write!(
38                    f,
39                    "expected a vector with {expected} dimensions, got {actual}"
40                )
41            }
42            Error::InvalidVector(reason) => write!(f, "invalid vector: {reason}"),
43            Error::InvalidArgument(reason) => write!(f, "invalid argument: {reason}"),
44        }
45    }
46}
47
48impl std::error::Error for Error {
49    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
50        match self {
51            Error::Io(err) => Some(err),
52            _ => None,
53        }
54    }
55}
56
57impl From<io::Error> for Error {
58    fn from(err: io::Error) -> Self {
59        Error::Io(err)
60    }
61}