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
32#[derive(Debug)]
34pub enum DecodeError {
35 Io(std::io::Error),
37
38 Utf8(std::str::Utf8Error),
39
40 InvalidVersion,
41
42 InvalidTag((&'static str, u8)),
44
45 InvalidTrailer,
47
48 InvalidHeader(&'static str),
49}
50
51impl std::fmt::Display for DecodeError {
52 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53 write!(
54 f,
55 "DecodeError({})",
56 match self {
57 Self::Io(e) => e.to_string(),
58 e => format!("{e:?}"),
59 }
60 )
61 }
62}
63
64impl From<std::io::Error> for DecodeError {
65 fn from(value: std::io::Error) -> Self {
66 Self::Io(value)
67 }
68}
69
70impl From<std::str::Utf8Error> for DecodeError {
71 fn from(value: std::str::Utf8Error) -> Self {
72 Self::Utf8(value)
73 }
74}
75
76pub trait Encode {
78 fn encode_into<W: Write>(&self, writer: &mut W) -> Result<(), EncodeError>;
80
81 fn encode_into_vec(&self) -> Vec<u8> {
83 let mut v = vec![];
84
85 #[allow(clippy::expect_used)]
86 self.encode_into(&mut v).expect("cannot fail");
87
88 v
89 }
90}
91
92pub trait Decode {
94 fn decode_from<R: Read>(reader: &mut R) -> Result<Self, DecodeError>
96 where
97 Self: Sized;
98}