1use std::string::FromUtf8Error;
2use thiserror::Error;
3
4use super::{BoundsExceeded, Form, varint};
5
6#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
12pub trait Decode<'a, V>: Sized {
13 fn decode(r: &mut Decoder<'a>, version: V) -> Result<Self, DecodeError>;
15
16 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#[derive(Error, Debug, Clone)]
29#[non_exhaustive]
30pub enum DecodeError {
31 #[error("short buffer")]
33 Short,
34
35 #[error("long buffer")]
37 Long,
38
39 #[error("invalid string")]
41 InvalidString(#[from] FromUtf8Error),
42
43 #[error("invalid message: {0:?}")]
45 InvalidMessage(u64),
46
47 #[error("invalid subscribe location")]
49 InvalidSubscribeLocation,
50
51 #[error("invalid value")]
53 InvalidValue,
54
55 #[error("too many")]
57 TooMany,
58
59 #[error("bounds exceeded")]
61 BoundsExceeded,
62
63 #[error("expected end")]
65 ExpectedEnd,
66
67 #[error("message too large: {size} bytes exceeds {max} byte limit")]
69 MessageTooLarge {
70 size: usize,
72 max: usize,
74 },
75
76 #[error("duplicate")]
78 Duplicate,
79
80 #[error("trailing bytes")]
82 TrailingBytes,
83
84 #[error("unsupported version")]
86 Version,
87
88 #[error(transparent)]
91 Session(crate::SessionError),
92
93 #[error("malformed authorization token")]
96 MalformedAuthToken,
97
98 #[error("multiple authorization tokens")]
101 MultipleAuthTokens,
102}
103
104impl DecodeError {
105 #[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#[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 len: usize,
132 need: usize,
134 pub(crate) control: Option<crate::stats::Message>,
136 pub(crate) uncounted: usize,
139}
140
141impl<'a> Decoder<'a> {
142 #[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 #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
159 pub fn need(&self) -> usize {
160 self.need
161 }
162
163 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 #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
172 pub fn form(&self) -> Form {
173 self.form
174 }
175
176 #[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 #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
184 pub fn remaining(&self) -> usize {
185 self.buf.len()
186 }
187
188 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 Err(DecodeError::Short) => Err(self.short(self.buf.len() + 1)),
250 Err(err) => Err(err),
251 }
252 }
253
254 #[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 #[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 #[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 Err(_) => Err(String::from_utf8(bytes.to_vec()).unwrap_err().into()),
276 }
277 }
278
279 #[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 #[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 #[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}