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