Skip to main content

reliakit_codec/
error.rs

1//! Error types returned by canonical encoding and decoding.
2
3use core::fmt;
4
5/// High-level category for a codec error.
6#[derive(Debug, Copy, Clone, PartialEq, Eq)]
7pub enum CodecErrorKind {
8    /// The input ended before the requested bytes could be read.
9    UnexpectedEof,
10    /// A value used a byte or tag that is not valid for its type.
11    InvalidValue,
12    /// A decoded length cannot be represented or safely processed.
13    LengthOverflow,
14    /// A decoded value left trailing bytes in an exact decode operation.
15    TrailingBytes,
16    /// The writer failed to accept bytes.
17    WriteFailed,
18    /// The reader failed for a reason other than end of input.
19    ReadFailed,
20}
21
22/// Error returned by canonical encoding and decoding operations.
23#[derive(Debug, Copy, Clone, PartialEq, Eq)]
24pub struct CodecError {
25    kind: CodecErrorKind,
26    message: &'static str,
27}
28
29impl CodecError {
30    /// Creates a new codec error with a stable kind and actionable message.
31    pub const fn new(kind: CodecErrorKind, message: &'static str) -> Self {
32        Self { kind, message }
33    }
34
35    /// Returns the stable error category.
36    pub const fn kind(&self) -> CodecErrorKind {
37        self.kind
38    }
39
40    /// Returns a human-readable error message.
41    pub const fn message(&self) -> &'static str {
42        self.message
43    }
44
45    /// Input ended before the requested bytes could be read.
46    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    /// Value used an invalid byte or tag.
54    pub const fn invalid_value(message: &'static str) -> Self {
55        Self::new(CodecErrorKind::InvalidValue, message)
56    }
57
58    /// Decoded length cannot be represented or safely processed.
59    pub const fn length_overflow(message: &'static str) -> Self {
60        Self::new(CodecErrorKind::LengthOverflow, message)
61    }
62
63    /// Exact decode found bytes after the decoded value.
64    pub const fn trailing_bytes() -> Self {
65        Self::new(
66            CodecErrorKind::TrailingBytes,
67            "decode completed but trailing bytes remain",
68        )
69    }
70
71    /// Writer failed to accept bytes.
72    pub const fn write_failed() -> Self {
73        Self::new(CodecErrorKind::WriteFailed, "failed to write encoded bytes")
74    }
75
76    /// Reader failed for a reason other than end of input.
77    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 {}