Skip to main content

moq_net/coding/
decode.rs

1use std::string::FromUtf8Error;
2use thiserror::Error;
3
4use super::{BoundsExceeded, Form, varint};
5
6/// Read the value from a [`Decoder`] using the given version.
7///
8/// If [DecodeError::Short] is returned, the caller should try again with more data.
9/// The value may borrow from the buffer for `'a`, so only a caller that keeps a field
10/// copies it; an owned value implements this for every `'a`.
11#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
12pub trait Decode<'a, V>: Sized {
13	/// Decode the value from the front of the decoder.
14	fn decode(r: &mut Decoder<'a>, version: V) -> Result<Self, DecodeError>;
15
16	/// Decode the value from the front of `buf`, returning it and the bytes it took.
17	fn decode_slice(buf: &'a [u8], version: V) -> Result<(Self, usize), DecodeError>
18	where
19		V: Into<Form> + Copy,
20	{
21		let mut r = Decoder::new(buf, version.into());
22		let value = Self::decode(&mut r, version)?;
23		Ok((value, buf.len() - r.remaining()))
24	}
25}
26
27/// A decode error.
28#[derive(Error, Debug, Clone)]
29#[non_exhaustive]
30pub enum DecodeError {
31	/// The buffer ran out mid-value. Retry once more bytes arrive.
32	#[error("short buffer")]
33	Short,
34
35	/// The value claims more bytes than the enclosing message allows.
36	#[error("long buffer")]
37	Long,
38
39	/// A string field was not valid UTF-8.
40	#[error("invalid string")]
41	InvalidString(#[from] FromUtf8Error),
42
43	/// The message type ID is unknown for the negotiated version.
44	#[error("invalid message: {0:?}")]
45	InvalidMessage(u64),
46
47	/// A SUBSCRIBE start/end location is malformed or out of order.
48	#[error("invalid subscribe location")]
49	InvalidSubscribeLocation,
50
51	/// A field held a value outside its permitted range.
52	#[error("invalid value")]
53	InvalidValue,
54
55	/// A repeated field exceeded the count this implementation accepts.
56	#[error("too many")]
57	TooMany,
58
59	/// An integer was too large for the field it was read into.
60	#[error("bounds exceeded")]
61	BoundsExceeded,
62
63	/// More data followed where the message was required to end.
64	#[error("expected end")]
65	ExpectedEnd,
66
67	/// A length-prefixed message exceeded the receiver's byte limit.
68	#[error("message too large: {size} bytes exceeds {max} byte limit")]
69	MessageTooLarge {
70		/// The byte length declared by the peer.
71		size: usize,
72		/// The largest message this receiver accepts.
73		max: usize,
74	},
75
76	/// A parameter or field appeared more than once.
77	#[error("duplicate")]
78	Duplicate,
79
80	/// Bytes remained after the value was fully decoded.
81	#[error("trailing bytes")]
82	TrailingBytes,
83
84	/// The field does not exist in the negotiated protocol version.
85	#[error("unsupported version")]
86	Version,
87
88	/// The value is one the draft answers by closing the session with this code, such as an
89	/// `AUTHORIZATION TOKEN` naming an alias.
90	#[error(transparent)]
91	Session(crate::SessionError),
92
93	/// A request's `AUTHORIZATION TOKEN` is well formed but unusable, such as a repeat of
94	/// another, which rejects the request rather than closing the session.
95	#[error("malformed authorization token")]
96	MalformedAuthToken,
97
98	/// A request carries more than one distinct `AUTHORIZATION TOKEN`, which this
99	/// implementation refuses as unsupported rather than closing the session.
100	#[error("multiple authorization tokens")]
101	MultipleAuthTokens,
102}
103
104impl DecodeError {
105	/// A complete frame cannot be extended by reading more stream bytes.
106	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
107	pub(crate) fn complete(self) -> Self {
108		match self {
109			Self::Short => Self::InvalidValue,
110			other => other,
111		}
112	}
113}
114
115impl From<BoundsExceeded> for DecodeError {
116	fn from(_: BoundsExceeded) -> Self {
117		Self::BoundsExceeded
118	}
119}
120
121/// Reads wire primitives from the front of a byte slice.
122///
123/// A read either consumes exactly what it returns or fails and consumes nothing, so a
124/// [`DecodeError::Short`] can be retried once more bytes arrive.
125#[derive(Debug, Clone)]
126#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
127pub struct Decoder<'a> {
128	buf: &'a [u8],
129	form: Form,
130	/// The length of the buffer this decoder started with.
131	len: usize,
132	/// See [`Self::need`].
133	need: usize,
134	/// The control message read, counted once the read is consumed.
135	pub(crate) control: Option<crate::stats::Message>,
136	/// Leading bytes left out of the `control` count: a type selector the sender writes
137	/// apart from the message, and so never counts.
138	pub(crate) uncounted: usize,
139}
140
141impl<'a> Decoder<'a> {
142	/// Read `buf`, with varints in the given form.
143	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
144	pub fn new(buf: &'a [u8], form: Form) -> Self {
145		Self {
146			buf,
147			form,
148			len: buf.len(),
149			need: 0,
150			control: None,
151			uncounted: 0,
152		}
153	}
154
155	/// After a [`DecodeError::Short`], how many bytes from the start the failed read
156	/// needed: at least one more than the buffer when it can't tell, and 0 if no read of
157	/// this decoder ran short.
158	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
159	pub fn need(&self) -> usize {
160		self.need
161	}
162
163	/// Record that a read wanted `more` bytes past the current position.
164	fn short(&mut self, more: usize) -> DecodeError {
165		let need = (self.len - self.buf.len()).saturating_add(more);
166		self.need = self.need.max(need);
167		DecodeError::Short
168	}
169
170	/// The varint form this decoder reads.
171	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
172	pub fn form(&self) -> Form {
173		self.form
174	}
175
176	/// How many bytes have been read.
177	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
178	pub(crate) fn position(&self) -> usize {
179		self.len - self.buf.len()
180	}
181
182	/// The number of unread bytes.
183	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
184	pub fn remaining(&self) -> usize {
185		self.buf.len()
186	}
187
188	/// Whether every byte has been read.
189	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
190	pub fn is_empty(&self) -> bool {
191		self.buf.is_empty()
192	}
193
194	/// Read `len` raw bytes.
195	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
196	pub fn slice(&mut self, len: usize) -> Result<&'a [u8], DecodeError> {
197		let Some((head, rest)) = self.buf.split_at_checked(len) else {
198			return Err(self.short(len));
199		};
200		self.buf = rest;
201		Ok(head)
202	}
203
204	/// Read every remaining byte.
205	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
206	pub fn rest(&mut self) -> &'a [u8] {
207		std::mem::take(&mut self.buf)
208	}
209
210	/// Split off the next `len` bytes as their own decoder, e.g. a size-prefixed body.
211	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
212	pub fn sub(&mut self, len: usize) -> Result<Self, DecodeError> {
213		Ok(Self::new(self.slice(len)?, self.form))
214	}
215
216	/// Read a single byte.
217	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
218	pub fn u8(&mut self) -> Result<u8, DecodeError> {
219		Ok(self.slice(1)?[0])
220	}
221
222	/// Read a big-endian `u16`.
223	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
224	pub fn u16(&mut self) -> Result<u16, DecodeError> {
225		let b = self.slice(2)?;
226		Ok(u16::from_be_bytes([b[0], b[1]]))
227	}
228
229	/// Read a byte that must be 0 or 1.
230	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
231	pub fn bool(&mut self) -> Result<bool, DecodeError> {
232		match self.u8()? {
233			0 => Ok(false),
234			1 => Ok(true),
235			_ => Err(DecodeError::InvalidValue),
236		}
237	}
238
239	/// Read a varint.
240	#[inline(always)]
241	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
242	pub fn varint(&mut self) -> Result<u64, DecodeError> {
243		match varint::read(self.buf, self.form) {
244			Ok((value, rest)) => {
245				self.buf = rest;
246				Ok(value)
247			}
248			// The width is in the first byte, but a byte at a time is short enough.
249			Err(DecodeError::Short) => Err(self.short(self.buf.len() + 1)),
250			Err(err) => Err(err),
251		}
252	}
253
254	/// Read an optional varint: 0 is `None`, and `n + 1` is `Some(n)`.
255	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
256	pub fn varint_opt(&mut self) -> Result<Option<u64>, DecodeError> {
257		Ok(self.varint()?.checked_sub(1))
258	}
259
260	/// Read a varint length, then that many raw bytes.
261	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
262	pub fn bytes(&mut self) -> Result<&'a [u8], DecodeError> {
263		let start = self.buf;
264		let len = usize::try_from(self.varint()?).map_err(|_| DecodeError::BoundsExceeded)?;
265		self.slice(len).inspect_err(|_| self.buf = start)
266	}
267
268	/// Read a varint length, then that many bytes of UTF-8, borrowed from the buffer.
269	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
270	pub fn str(&mut self) -> Result<&'a str, DecodeError> {
271		let bytes = self.bytes()?;
272		match std::str::from_utf8(bytes) {
273			Ok(s) => Ok(s),
274			// The error carries an owned copy, so only invalid input pays for one.
275			Err(_) => Err(String::from_utf8(bytes.to_vec()).unwrap_err().into()),
276		}
277	}
278
279	/// Read a varint length, then that many bytes of UTF-8.
280	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
281	pub fn string(&mut self) -> Result<String, DecodeError> {
282		Ok(self.str()?.to_owned())
283	}
284}
285
286#[cfg(test)]
287mod tests {
288	use super::*;
289
290	/// A short read must leave the decoder where it was, or a retry with more bytes
291	/// would start mid-value.
292	#[test]
293	fn short_consumes_nothing() {
294		let mut r = Decoder::new(&[0x05, b'a', b'b'], Form::Quic);
295		assert!(matches!(r.bytes(), Err(DecodeError::Short)));
296		assert_eq!(r.remaining(), 3);
297
298		let mut r = Decoder::new(&[0x40], Form::Quic);
299		assert!(matches!(r.varint(), Err(DecodeError::Short)));
300		assert_eq!(r.remaining(), 1);
301	}
302
303	/// A short read reports how much it needed from the start, so a reader can wait for
304	/// all of it rather than retry once per byte.
305	#[test]
306	fn short_reports_what_it_needed() {
307		let mut r = Decoder::new(&[0x01, 0x05, b'a', b'b'], Form::Quic);
308		assert_eq!(r.varint().unwrap(), 1);
309		assert!(matches!(r.bytes(), Err(DecodeError::Short)));
310		assert_eq!(r.need(), 7, "a 5 byte body after two prefix bytes");
311
312		let mut r = Decoder::new(&[0x40], Form::Quic);
313		assert!(matches!(r.varint(), Err(DecodeError::Short)));
314		assert_eq!(r.need(), 2);
315	}
316}