1use std::{
2 error::Error,
3 fmt::Display,
4 io::{self},
5 num::ParseIntError,
6 str::Utf8Error,
7};
8
9#[derive(Debug)]
11pub enum ReadError {
12 IoError(io::Error),
13 InvalidCommand(String),
14 InvalidCommandPrefix(String),
15 UnsupportedVersion(String),
16 InvalidFormat(String),
17 TooManyBytes { max: usize, got: usize },
18}
19
20impl From<io::Error> for ReadError {
21 fn from(value: io::Error) -> Self {
22 ReadError::IoError(value)
23 }
24}
25
26impl From<Utf8Error> for ReadError {
27 fn from(value: Utf8Error) -> Self {
28 ReadError::InvalidFormat(format!("Invalid UTF8: {}", value))
29 }
30}
31
32impl From<ParseIntError> for ReadError {
33 fn from(value: ParseIntError) -> Self {
34 ReadError::InvalidFormat(format!("Invalid integer: {}", value))
35 }
36}
37
38impl Display for ReadError {
39 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40 match self {
41 ReadError::IoError(error) => write!(f, "{}", error),
42 ReadError::InvalidCommand(cmd) => write!(f, "Received invalid command {}", cmd),
43 ReadError::UnsupportedVersion(version) => write!(f, "Unsupported version {}", version),
44 ReadError::InvalidFormat(format) => write!(f, "{}", format),
45 ReadError::InvalidCommandPrefix(prefix) => {
46 write!(f, "Received invalid command with prefix {}", prefix)
47 }
48 ReadError::TooManyBytes { max, got } => {
49 write!(f, "Message too large! Maximum is {}, but gut {}", max, got)
50 }
51 }
52 }
53}
54
55impl Error for ReadError {}