1use bytes::Bytes;
2
3use super::{BoundsExceeded, Form, varint};
4
5#[derive(thiserror::Error, Debug, Clone)]
7#[non_exhaustive]
8pub enum EncodeError {
9 #[error("bounds exceeded")]
11 BoundsExceeded,
12 #[error("too large")]
14 TooLarge,
15 #[error("short buffer")]
17 Short,
18 #[error("invalid state")]
20 InvalidState,
21 #[error("too many")]
23 TooMany,
24 #[error("unsupported version")]
26 Version,
27 #[error("unsupported")]
29 Unsupported,
30}
31
32impl From<BoundsExceeded> for EncodeError {
33 fn from(_: BoundsExceeded) -> Self {
34 Self::BoundsExceeded
35 }
36}
37
38#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
40pub trait Encode<V> {
41 fn encode(&self, w: &mut Encoder<'_>, version: V) -> Result<(), EncodeError>;
43
44 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#[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 pub fn new(buf: &'a mut Vec<u8>, form: Form) -> Self {
68 Self {
69 buf,
70 form,
71 control: None,
72 }
73 }
74
75 #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
77 pub fn form(&self) -> Form {
78 self.form
79 }
80
81 pub fn slice(&mut self, v: &[u8]) {
83 self.buf.extend_from_slice(v);
84 }
85
86 #[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 #[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 #[inline(always)]
100 pub fn varint(&mut self, v: u64) -> Result<(), EncodeError> {
101 Ok(varint::write(v, self.form, self.buf)?)
102 }
103
104 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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#[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 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 #[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}