amf_rs/
errors.rs

1use std::error::Error;
2use std::fmt::{Debug, Display, Formatter};
3use std::io;
4
5#[derive(Debug)]
6pub enum AmfError {
7    BufferTooSmall { want: usize, got: usize },
8    StringTooLong { max: usize, got: usize },
9    InvalidUtf8(std::str::Utf8Error),
10    TypeMarkerValueMismatch { want: u8, got: u8 },
11    Custom(String),
12    Io(io::Error),
13}
14
15impl Display for AmfError {
16    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
17        match self {
18            AmfError::BufferTooSmall { want, got } => {
19                write!(f, "Buffer too small: want {} bytes, got {}", want, got)
20            }
21            AmfError::StringTooLong { max, got } => {
22                write!(f, "String too long: max {}, got {}", max, got)
23            }
24            AmfError::InvalidUtf8(err) => {
25                write!(f, "{}", err)
26            }
27            AmfError::TypeMarkerValueMismatch { want, got } => {
28                write!(f, "Type marker value mismatch: want {}, got {}", want, got)
29            }
30            AmfError::Custom(msg) => {
31                write!(f, "{}", msg)
32            }
33            AmfError::Io(err) => {
34                write!(f, "{}", err)
35            }
36        }
37    }
38}
39
40// 用来支持 ? 操作符
41impl From<io::Error> for AmfError {
42    fn from(value: io::Error) -> Self {
43        AmfError::Io(value)
44    }
45}
46
47impl Error for AmfError {
48    // 覆写是为了让错误链可以正常工作
49    fn source(&self) -> Option<&(dyn Error + 'static)> {
50        match self {
51            AmfError::Io(err) => Some(err),
52            _ => None,
53        }
54    }
55}