1use std::io::{Read, Write};
6
7#[derive(Debug)]
9pub enum EncodeError {
10 Io(std::io::Error),
12}
13
14impl std::fmt::Display for EncodeError {
15 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16 write!(
17 f,
18 "EncodeError({})",
19 match self {
20 Self::Io(e) => e.to_string(),
21 }
22 )
23 }
24}
25
26impl From<std::io::Error> for EncodeError {
27 fn from(value: std::io::Error) -> Self {
28 Self::Io(value)
29 }
30}
31
32impl std::error::Error for EncodeError {
33 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
34 match self {
35 Self::Io(e) => Some(e),
36 }
37 }
38}
39
40#[derive(Debug)]
42pub enum DecodeError {
43 Io(std::io::Error),
45
46 Utf8(std::str::Utf8Error),
47
48 InvalidVersion,
49
50 InvalidTag((&'static str, u8)),
52
53 InvalidTrailer,
54
55 InvalidHeader(&'static str),
57}
58
59impl std::fmt::Display for DecodeError {
60 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61 write!(
62 f,
63 "DecodeError({})",
64 match self {
65 Self::Io(e) => e.to_string(),
66 e => format!("{e:?}"),
67 }
68 )
69 }
70}
71
72impl From<std::str::Utf8Error> for DecodeError {
73 fn from(value: std::str::Utf8Error) -> Self {
74 Self::Utf8(value)
75 }
76}
77
78impl From<std::io::Error> for DecodeError {
79 fn from(value: std::io::Error) -> Self {
80 Self::Io(value)
81 }
82}
83
84impl std::error::Error for DecodeError {
85 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
86 match self {
87 Self::Io(e) => Some(e),
88 _ => None,
89 }
90 }
91}
92
93pub trait Encode {
95 fn encode_into<W: Write>(&self, writer: &mut W) -> Result<(), EncodeError>;
97
98 #[allow(unused)]
100 fn encode_into_vec(&self) -> Vec<u8> {
101 let mut v = vec![];
102 self.encode_into(&mut v).expect("cannot fail");
103 v
104 }
105}
106
107pub trait Decode {
109 fn decode_from<R: Read>(reader: &mut R) -> Result<Self, DecodeError>
111 where
112 Self: Sized;
113}