1use core::fmt;
4
5#[derive(Debug, Copy, Clone, PartialEq, Eq)]
7pub enum CodecErrorKind {
8 UnexpectedEof,
10 InvalidValue,
12 LengthOverflow,
14 TrailingBytes,
16 WriteFailed,
18 ReadFailed,
20}
21
22#[derive(Debug, Copy, Clone, PartialEq, Eq)]
24pub struct CodecError {
25 kind: CodecErrorKind,
26 message: &'static str,
27}
28
29impl CodecError {
30 pub const fn new(kind: CodecErrorKind, message: &'static str) -> Self {
32 Self { kind, message }
33 }
34
35 pub const fn kind(&self) -> CodecErrorKind {
37 self.kind
38 }
39
40 pub const fn message(&self) -> &'static str {
42 self.message
43 }
44
45 pub const fn unexpected_eof() -> Self {
47 Self::new(
48 CodecErrorKind::UnexpectedEof,
49 "input ended before the requested bytes could be read",
50 )
51 }
52
53 pub const fn invalid_value(message: &'static str) -> Self {
55 Self::new(CodecErrorKind::InvalidValue, message)
56 }
57
58 pub const fn length_overflow(message: &'static str) -> Self {
60 Self::new(CodecErrorKind::LengthOverflow, message)
61 }
62
63 pub const fn trailing_bytes() -> Self {
65 Self::new(
66 CodecErrorKind::TrailingBytes,
67 "decode completed but trailing bytes remain",
68 )
69 }
70
71 pub const fn write_failed() -> Self {
73 Self::new(CodecErrorKind::WriteFailed, "failed to write encoded bytes")
74 }
75
76 pub const fn read_failed() -> Self {
78 Self::new(CodecErrorKind::ReadFailed, "failed to read encoded bytes")
79 }
80}
81
82impl fmt::Display for CodecError {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 f.write_str(self.message)
85 }
86}
87
88#[cfg(feature = "std")]
89impl std::error::Error for CodecError {}