monoio_thrift/
error.rs

1use std::{
2    borrow::Cow,
3    fmt::{self, Display, Formatter},
4};
5
6#[derive(Debug)]
7pub struct CodecError {
8    pub kind: CodecErrorKind,
9    pub message: Cow<'static, str>,
10}
11
12impl CodecError {
13    pub fn new<S: Into<Cow<'static, str>>>(kind: CodecErrorKind, message: S) -> CodecError {
14        CodecError {
15            message: message.into(),
16            kind,
17        }
18    }
19
20    pub const fn invalid_data() -> CodecError {
21        CodecError {
22            message: Cow::Borrowed("invalid data"),
23            kind: CodecErrorKind::InvalidData,
24        }
25    }
26}
27
28impl Display for CodecError {
29    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
30        use CodecErrorKind::*;
31
32        write!(f, "{}", self.message)?;
33        if !matches!(
34            self.kind,
35            BadVersion | InvalidData | NegativeSize | NotImplemented | UnknownMethod
36        ) {
37            write!(f, ", caused by {}", self.kind)?;
38        }
39        Ok(())
40    }
41}
42
43impl std::error::Error for CodecError {}
44
45impl From<std::io::Error> for CodecError {
46    fn from(value: std::io::Error) -> Self {
47        CodecError::new(CodecErrorKind::IOError(value), "")
48    }
49}
50
51#[derive(Debug)]
52pub enum CodecErrorKind {
53    InvalidData,
54    NegativeSize,
55    BadVersion,
56    NotImplemented,
57    DepthLimit,
58    UnknownMethod,
59    IOError(std::io::Error),
60}
61
62impl Display for CodecErrorKind {
63    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
64        match self {
65            CodecErrorKind::IOError(e) => write!(f, "IOError: {}", e),
66            CodecErrorKind::InvalidData => write!(f, "InvalidData"),
67            CodecErrorKind::NegativeSize => write!(f, "NegativeSize"),
68            CodecErrorKind::BadVersion => write!(f, "BadVersion"),
69            CodecErrorKind::NotImplemented => write!(f, "NotImplemented"),
70            CodecErrorKind::DepthLimit => write!(f, "DepthLimit"),
71            CodecErrorKind::UnknownMethod => write!(f, "UnknownMethod"),
72        }
73    }
74}