Skip to main content

automotive_wire_codec/
error.rs

1//! Primitive decode error fragments. An L1 error implements `From` of each so shared
2//! trait defaults and leaf helpers can construct errors generically.
3
4/// A read ran out of bytes: `needed` were required, only `available` present.
5#[derive(Clone, Copy, Debug, Eq, PartialEq)]
6pub struct Incomplete {
7    /// Number of bytes the read required.
8    pub needed: usize,
9    /// Number of bytes actually available.
10    pub available: usize,
11}
12
13/// Bytes remained after a `decode_exact` that should have consumed the whole buffer.
14#[derive(Clone, Copy, Debug, Eq, PartialEq)]
15pub struct TrailingBytes(pub usize);
16
17impl core::fmt::Display for Incomplete {
18    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
19        write!(
20            f,
21            "incomplete input: needed {} bytes, {} available",
22            self.needed, self.available
23        )
24    }
25}
26impl core::error::Error for Incomplete {}
27
28impl core::fmt::Display for TrailingBytes {
29    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
30        write!(f, "{} trailing bytes after decode", self.0)
31    }
32}
33impl core::error::Error for TrailingBytes {}
34
35/// A variable-width read/write was requested with an out-of-range byte width.
36///
37/// Returned (via [`ReadUintError`](crate::ReadUintError)) instead of
38/// panicking, so a wire-controlled width is a recoverable *data* error, not a
39/// programming error.
40#[derive(Clone, Copy, Debug, Eq, PartialEq)]
41pub struct InvalidWidth {
42    /// Maximum width the operation supports.
43    pub max: usize,
44    /// Width actually requested.
45    pub got: usize,
46}
47
48/// An output slice was too small for the bytes an encode needed to write.
49///
50/// Encode-side mirror of [`Incomplete`]. Carried by
51/// [`WriteError::Insufficient`](crate::WriteError::Insufficient) from any sink
52/// that knows its capacity — [`SliceSink`](crate::SliceSink), or anything
53/// wrapped in [`Limited`](crate::Limited).
54#[derive(Clone, Copy, Debug, Eq, PartialEq)]
55pub struct InsufficientBuffer {
56    /// Bytes required to complete the write that failed, including those
57    /// already written.
58    ///
59    /// A **lower bound** on the encode's total size: the encode stopped at
60    /// this write, so whatever remained was never measured. For an exact
61    /// total, call [`Encode::encoded_size`](crate::Encode::encoded_size).
62    pub needed_at_least: usize,
63    /// Total capacity the sink had.
64    pub available: usize,
65}
66
67impl core::fmt::Display for InvalidWidth {
68    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
69        write!(f, "invalid width: got {}, max {}", self.got, self.max)
70    }
71}
72impl core::error::Error for InvalidWidth {}
73
74impl core::fmt::Display for InsufficientBuffer {
75    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
76        write!(
77            f,
78            "insufficient buffer: needed at least {} bytes, {} available",
79            self.needed_at_least, self.available
80        )
81    }
82}
83impl core::error::Error for InsufficientBuffer {}
84
85#[cfg(test)]
86mod tests {
87    use super::*;
88    use std::string::ToString;
89
90    #[test]
91    fn incomplete_display() {
92        let e = Incomplete {
93            needed: 4,
94            available: 1,
95        };
96        assert_eq!(
97            e.to_string(),
98            "incomplete input: needed 4 bytes, 1 available"
99        );
100    }
101
102    #[test]
103    fn trailing_display() {
104        assert_eq!(
105            TrailingBytes(3).to_string(),
106            "3 trailing bytes after decode"
107        );
108    }
109
110    fn assert_is_error<T: core::error::Error>() {}
111
112    #[test]
113    fn impl_core_error() {
114        assert_is_error::<Incomplete>();
115        assert_is_error::<TrailingBytes>();
116    }
117
118    #[test]
119    fn invalid_width_display() {
120        let e = InvalidWidth { max: 16, got: 255 };
121        assert_eq!(e.to_string(), "invalid width: got 255, max 16");
122    }
123
124    #[test]
125    fn insufficient_buffer_display() {
126        let e = InsufficientBuffer {
127            needed_at_least: 8,
128            available: 4,
129        };
130        assert_eq!(
131            e.to_string(),
132            "insufficient buffer: needed at least 8 bytes, 4 available"
133        );
134    }
135
136    #[test]
137    fn new_fragments_impl_core_error() {
138        assert_is_error::<InvalidWidth>();
139        assert_is_error::<InsufficientBuffer>();
140    }
141}