Skip to main content

moq_net/coding/
encode.rs

1use bytes::Bytes;
2
3use super::{BoundsExceeded, Form, varint};
4
5/// An error that occurs during encoding.
6#[derive(thiserror::Error, Debug, Clone)]
7#[non_exhaustive]
8pub enum EncodeError {
9	/// An integer was too large for the QUIC varint range.
10	#[error("bounds exceeded")]
11	BoundsExceeded,
12	/// The payload exceeds the maximum size the wire format can express.
13	#[error("too large")]
14	TooLarge,
15	/// The destination buffer had no room for the value.
16	#[error("short buffer")]
17	Short,
18	/// The message cannot be encoded from the current session state.
19	#[error("invalid state")]
20	InvalidState,
21	/// A repeated field exceeded the count the wire format permits.
22	#[error("too many")]
23	TooMany,
24	/// The field does not exist in the negotiated protocol version.
25	#[error("unsupported version")]
26	Version,
27	/// The value is well-formed but this implementation cannot put it on the wire.
28	#[error("unsupported")]
29	Unsupported,
30}
31
32impl From<BoundsExceeded> for EncodeError {
33	fn from(_: BoundsExceeded) -> Self {
34		Self::BoundsExceeded
35	}
36}
37
38/// Write the value to an [`Encoder`] using the given version.
39#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
40pub trait Encode<V> {
41	/// Encode the value to the given encoder, which may hold partial output on error.
42	fn encode(&self, w: &mut Encoder<'_>, version: V) -> Result<(), EncodeError>;
43
44	/// Encode the value into a fresh [Bytes] buffer.
45	fn encode_bytes(&self, version: V) -> Result<Bytes, EncodeError>
46	where
47		V: Into<Form> + Copy,
48	{
49		let mut buf = Vec::new();
50		self.encode(&mut Encoder::new(&mut buf, version.into()), version)?;
51		Ok(buf.into())
52	}
53}
54
55/// Appends wire primitives to a byte buffer.
56///
57/// The buffer grows as needed, so only a value the wire cannot express fails.
58#[derive(Debug)]
59pub struct Encoder<'a> {
60	buf: &'a mut Vec<u8>,
61	form: Form,
62	pub(crate) control: Option<crate::stats::Message>,
63}
64
65impl<'a> Encoder<'a> {
66	/// Append to `buf`, with varints in the given form.
67	pub fn new(buf: &'a mut Vec<u8>, form: Form) -> Self {
68		Self {
69			buf,
70			form,
71			control: None,
72		}
73	}
74
75	/// The varint form this encoder writes.
76	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
77	pub fn form(&self) -> Form {
78		self.form
79	}
80
81	/// Write raw bytes.
82	pub fn slice(&mut self, v: &[u8]) {
83		self.buf.extend_from_slice(v);
84	}
85
86	/// Write a single byte.
87	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
88	pub fn u8(&mut self, v: u8) {
89		self.buf.push(v);
90	}
91
92	/// Write a bool as a 0 or 1 byte.
93	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
94	pub fn bool(&mut self, v: bool) {
95		self.buf.push(v as u8);
96	}
97
98	/// Write a varint, or fail with [`EncodeError::BoundsExceeded`] if the form cannot carry it.
99	#[inline(always)]
100	pub fn varint(&mut self, v: u64) -> Result<(), EncodeError> {
101		Ok(varint::write(v, self.form, self.buf)?)
102	}
103
104	/// Write an optional varint: `None` as 0, and `Some(n)` as `n + 1`.
105	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
106	pub fn varint_opt(&mut self, v: Option<u64>) -> Result<(), EncodeError> {
107		let v = match v {
108			Some(v) => v.checked_add(1).ok_or(EncodeError::TooLarge)?,
109			None => 0,
110		};
111		self.varint(v)
112	}
113
114	/// Write a varint length, then the raw bytes.
115	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
116	pub fn bytes(&mut self, v: &[u8]) -> Result<(), EncodeError> {
117		self.varint(v.len() as u64)?;
118		self.slice(v);
119		Ok(())
120	}
121
122	/// Write a varint length, then the UTF-8 bytes.
123	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
124	pub fn string(&mut self, v: &str) -> Result<(), EncodeError> {
125		self.bytes(v.as_bytes())
126	}
127
128	/// Reserve a varint size prefix for the body written next; [`Self::fill`] sizes it.
129	///
130	/// One byte is reserved, which most bodies fit, so they never move.
131	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
132	pub fn prefix_varint(&mut self) -> Prefix {
133		self.buf.push(0);
134		Prefix {
135			body: self.buf.len(),
136			kind: PrefixKind::Varint,
137		}
138	}
139
140	/// Reserve a big-endian `u16` size prefix for the body written next; [`Self::fill`] sizes it.
141	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
142	pub fn prefix_u16(&mut self) -> Prefix {
143		self.buf.extend_from_slice(&[0, 0]);
144		Prefix {
145			body: self.buf.len(),
146			kind: PrefixKind::U16,
147		}
148	}
149
150	/// The number of bytes written since `prefix` was reserved.
151	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
152	pub fn since(&self, prefix: &Prefix) -> usize {
153		self.buf.len() - prefix.body
154	}
155
156	/// Drop a reserved prefix and everything written since, as if neither was written.
157	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
158	pub fn discard(&mut self, prefix: Prefix) {
159		let start = match prefix.kind {
160			PrefixKind::Varint => prefix.body - 1,
161			PrefixKind::U16 => prefix.body - 2,
162		};
163		self.buf.truncate(start);
164	}
165
166	/// Size a reserved prefix to everything written since.
167	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
168	pub fn fill(&mut self, prefix: Prefix) -> Result<(), EncodeError> {
169		let body = prefix.body;
170		let end = self.buf.len();
171
172		match prefix.kind {
173			PrefixKind::U16 => {
174				let size = u16::try_from(end - body).map_err(|_| EncodeError::TooLarge)?;
175				self.buf[body - 2..body].copy_from_slice(&size.to_be_bytes());
176			}
177			PrefixKind::Varint => {
178				// Encode the size past the body, then move it into the reserved byte,
179				// shifting the body up when the size needs more than that one byte.
180				varint::write((end - body) as u64, self.form, self.buf)?;
181				let len = self.buf.len() - end;
182				if len == 1 {
183					self.buf[body - 1] = self.buf[end];
184					self.buf.truncate(end);
185					return Ok(());
186				}
187
188				let mut size = [0u8; 9];
189				size[..len].copy_from_slice(&self.buf[end..]);
190				self.buf.truncate(end + len - 1);
191				self.buf.copy_within(body..end, body + len - 1);
192				self.buf[body - 1..body - 1 + len].copy_from_slice(&size[..len]);
193			}
194		}
195		Ok(())
196	}
197}
198
199/// A size prefix reserved ahead of a body, sized by [`Encoder::fill`] once it is written.
200#[must_use = "an unfilled prefix leaves a zero size on the wire"]
201#[derive(Debug)]
202#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
203pub struct Prefix {
204	/// Where the body starts, just past the reserved bytes.
205	body: usize,
206	kind: PrefixKind,
207}
208
209#[derive(Debug)]
210#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
211enum PrefixKind {
212	Varint,
213	U16,
214}
215
216#[cfg(test)]
217mod tests {
218	use super::*;
219
220	/// The prefix lands before the body, sized to it, even when it outgrows the one byte
221	/// reserved for it.
222	#[test]
223	fn prefix_varint_sizes_the_body() {
224		for size in [0usize, 63, 64, 20_000] {
225			let mut buf = vec![0xaa];
226			let mut w = Encoder::new(&mut buf, Form::Quic);
227			let prefix = w.prefix_varint();
228			w.slice(&vec![0x55; size]);
229			w.fill(prefix).unwrap();
230			w.u8(0xbb);
231
232			let mut r = super::super::Decoder::new(&buf[1..], Form::Quic);
233			assert_eq!(buf[0], 0xaa);
234			assert_eq!(r.varint().unwrap(), size as u64);
235			assert_eq!(r.slice(size).unwrap(), vec![0x55; size]);
236			assert_eq!(r.rest(), [0xbb]);
237		}
238	}
239
240	#[test]
241	fn prefix_u16_sizes_the_body() {
242		let mut buf = Vec::new();
243		let mut w = Encoder::new(&mut buf, Form::Quic);
244		let prefix = w.prefix_u16();
245		w.slice(&[0x55; 300]);
246		w.fill(prefix).unwrap();
247		assert_eq!(buf[..2], 300u16.to_be_bytes());
248		assert_eq!(buf.len(), 302);
249
250		let mut w = Encoder::new(&mut buf, Form::Quic);
251		let prefix = w.prefix_u16();
252		w.slice(&vec![0; 1 << 16]);
253		assert!(matches!(w.fill(prefix), Err(EncodeError::TooLarge)));
254	}
255}