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 InvalidVersion,
48
49 InvalidTag((&'static str, u8)),
51
52 InvalidTrailer,
54
55 InvalidHeader(&'static str),
57
58 Utf8(std::str::Utf8Error),
60}
61
62impl std::fmt::Display for DecodeError {
63 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64 write!(
65 f,
66 "DecodeError({})",
67 match self {
68 Self::Io(e) => e.to_string(),
69 e => format!("{e:?}"),
70 }
71 )
72 }
73}
74
75impl From<std::str::Utf8Error> for DecodeError {
76 fn from(value: std::str::Utf8Error) -> Self {
77 Self::Utf8(value)
78 }
79}
80
81impl From<std::io::Error> for DecodeError {
82 fn from(value: std::io::Error) -> Self {
83 Self::Io(value)
84 }
85}
86
87impl std::error::Error for DecodeError {
88 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
89 match self {
90 Self::Io(e) => Some(e),
91 _ => None,
92 }
93 }
94}
95
96pub trait Encode {
98 fn encode_into<W: Write>(&self, writer: &mut W) -> Result<(), EncodeError>;
100
101 #[allow(unused)]
103 fn encode_into_vec(&self) -> Vec<u8> {
104 let mut v = vec![];
105 self.encode_into(&mut v).expect("cannot fail");
106 v
107 }
108}
109
110pub trait Decode {
112 fn decode_from<R: Read>(reader: &mut R) -> Result<Self, DecodeError>
114 where
115 Self: Sized;
116}