verstamp/error.rs
1//! The single error type returned by reads and writes.
2//!
3//! Every failure mode is a variant of [`Error`]. Each variant carries the
4//! context that applies to it: the version found on the wire, the versions the
5//! reader was built to handle, the byte counts from a trailing-byte check, or a
6//! decoder's own error as the [`source`](std::error::Error::source). Not every
7//! variant carries every field; [`Empty`](Error::Empty) and
8//! [`Truncated`](Error::Truncated) fail before any version is known.
9
10use std::error::Error as StdError;
11use std::fmt;
12
13/// A boxed decoder or encoder error, preserved as the [`source`](StdError::source).
14pub type BoxError = Box<dyn StdError + Send + Sync + 'static>;
15
16/// Anything that can go wrong while framing, reading, or migrating a value.
17///
18/// The framing errors ([`Empty`](Error::Empty), [`Truncated`](Error::Truncated))
19/// come from the version tag itself. The routing errors
20/// ([`UnknownVersion`](Error::UnknownVersion),
21/// [`ForwardIncompatible`](Error::ForwardIncompatible)) come from comparing the
22/// tag against the versions a reader was built to handle. The payload errors
23/// ([`Decode`](Error::Decode), [`Encode`](Error::Encode),
24/// [`TrailingBytes`](Error::TrailingBytes)) come from your own format.
25#[non_exhaustive]
26#[derive(Debug)]
27pub enum Error {
28 /// The input held no bytes, so there was no version tag to read.
29 Empty,
30
31 /// The input ended before the whole version tag could be read.
32 Truncated {
33 /// Bytes the tag needs (always [`crate::wire::TAG_LEN`]).
34 needed: usize,
35 /// Bytes actually available.
36 got: usize,
37 },
38
39 /// The tag names a version older than the oldest one the reader handles, or
40 /// one that falls in a gap between the versions it handles.
41 ///
42 /// This is a version the reader has no decoder for. It is distinct from
43 /// [`ForwardIncompatible`](Error::ForwardIncompatible), which is a version
44 /// newer than anything the reader knows.
45 UnknownVersion {
46 /// The version found on the wire.
47 found: u16,
48 /// The versions the reader was built to handle, in registration order.
49 known: Vec<u16>,
50 },
51
52 /// The tag names a version newer than the newest one the reader handles.
53 ///
54 /// The data was written by a later revision of your schema. Reading it here
55 /// would be a downgrade, which this crate does not do. The fix is to run a
56 /// build new enough to know the version.
57 ForwardIncompatible {
58 /// The version found on the wire.
59 found: u16,
60 /// The newest version the reader handles.
61 current: u16,
62 },
63
64 /// The payload decoded, but the decoder did not consume all of it.
65 ///
66 /// This check rejects a decoder that consumed fewer (or more) bytes than the
67 /// payload holds, such as a wrong-length payload that decodes as a prefix and
68 /// stops short.
69 TrailingBytes {
70 /// The version whose decoder ran.
71 version: u16,
72 /// Bytes the decoder reported consuming.
73 consumed: usize,
74 /// Bytes in the payload.
75 total: usize,
76 },
77
78 /// The version's decoder returned an error. The original error is the
79 /// [`source`](StdError::source).
80 Decode {
81 /// The version whose decoder ran.
82 version: u16,
83 /// The decoder's own error.
84 source: BoxError,
85 },
86
87 /// The encoder passed to [`write`](crate::write) returned an error. The
88 /// original error is the [`source`](StdError::source).
89 Encode {
90 /// The version being written.
91 version: u16,
92 /// The encoder's own error.
93 source: BoxError,
94 },
95}
96
97impl fmt::Display for Error {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 match self {
100 Error::Empty => write!(f, "empty input: no version tag"),
101 Error::Truncated { needed, got } => {
102 write!(f, "truncated version tag: need {needed} bytes, got {got}")
103 }
104 Error::UnknownVersion { found, known } => {
105 write!(f, "unknown version {found} (reader handles ")?;
106 write_versions(f, known)?;
107 write!(f, ")")
108 }
109 Error::ForwardIncompatible { found, current } => write!(
110 f,
111 "version {found} is newer than this reader's current version {current}"
112 ),
113 Error::TrailingBytes {
114 version,
115 consumed,
116 total,
117 } => {
118 if consumed <= total {
119 write!(
120 f,
121 "version {version} decoder consumed {consumed} of {total} \
122 payload bytes, leaving {} unconsumed",
123 total - consumed
124 )
125 } else {
126 write!(
127 f,
128 "version {version} decoder reported consuming {consumed} bytes \
129 of a {total}-byte payload"
130 )
131 }
132 }
133 Error::Decode { version, source } => {
134 write!(f, "version {version} failed to decode: {source}")
135 }
136 Error::Encode { version, source } => {
137 write!(f, "version {version} failed to encode: {source}")
138 }
139 }
140 }
141}
142
143impl StdError for Error {
144 fn source(&self) -> Option<&(dyn StdError + 'static)> {
145 match self {
146 Error::Decode { source, .. } | Error::Encode { source, .. } => {
147 Some(&**source as &(dyn StdError + 'static))
148 }
149 _ => None,
150 }
151 }
152}
153
154fn write_versions(f: &mut fmt::Formatter<'_>, versions: &[u16]) -> fmt::Result {
155 for (i, v) in versions.iter().enumerate() {
156 if i > 0 {
157 write!(f, ", ")?;
158 }
159 write!(f, "{v}")?;
160 }
161 Ok(())
162}