1use serde_json::error::Category as JsonErrorCategory;
2use std::io;
3use thiserror::Error;
4
5pub type Result<T> = std::result::Result<T, Error>;
6
7#[derive(Debug, Error)]
8#[non_exhaustive]
9pub enum Error {
10 #[error("message length exceeded {} bytes", crate::bus::MAX_MESSAGE_SIZE)]
11 MessageLengthExceeded,
12 #[error("read zero bytes from device bus")]
13 ReadZero,
14 #[error("I/O error: {0}")]
15 Io(io::Error),
16 #[error("JSON error: {0}")]
17 Json(serde_json::Error),
18 #[error("HLAPI error: {0}")]
19 Api(String),
20}
21
22impl Error {
23 fn from_io_error(e: io::Error) -> Self {
24 if e.kind() == io::ErrorKind::WriteZero {
25 Self::MessageLengthExceeded
26 } else {
27 Self::Io(e)
28 }
29 }
30}
31
32impl From<serde_json::Error> for Error {
33 fn from(value: serde_json::Error) -> Self {
34 match value.classify() {
35 JsonErrorCategory::Io => Self::from_io_error(value.into()),
36 _ => Self::Json(value),
37 }
38 }
39}
40
41impl From<io::Error> for Error {
42 fn from(value: io::Error) -> Self {
43 Self::Io(value)
44 }
45}
46
47impl From<String> for Error {
48 fn from(value: String) -> Self {
49 Self::Api(value)
50 }
51}
52
53impl From<&str> for Error {
54 fn from(value: &str) -> Self {
55 Self::Api(value.into())
56 }
57}