1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use serde_json::error::Category as JsonErrorCategory;
use std::io;
use thiserror::Error;

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
    #[error("message length exceeded {} bytes", crate::bus::MAX_MESSAGE_SIZE)]
    MessageLengthExceeded,
    #[error("read zero bytes from device bus")]
    ReadZero,
    #[error("I/O error: {0}")]
    Io(io::Error),
    #[error("JSON error: {0}")]
    Json(serde_json::Error),
    #[error("HLAPI error: {0}")]
    Api(String),
}

impl Error {
    fn from_io_error(e: io::Error) -> Self {
        if e.kind() == io::ErrorKind::WriteZero {
            Self::MessageLengthExceeded
        } else {
            Self::Io(e)
        }
    }
}

impl From<serde_json::Error> for Error {
    fn from(value: serde_json::Error) -> Self {
        match value.classify() {
            JsonErrorCategory::Io => Self::from_io_error(value.into()),
            _ => Self::Json(value),
        }
    }
}

impl From<io::Error> for Error {
    fn from(value: io::Error) -> Self {
        Self::Io(value)
    }
}

impl From<String> for Error {
    fn from(value: String) -> Self {
        Self::Api(value)
    }
}

impl From<&str> for Error {
    fn from(value: &str) -> Self {
        Self::Api(value.into())
    }
}