puffin/
codec.rs

1use std::fmt::Debug;
2
3use crate::error::Error;
4
5/// Read from a byte slice.
6pub struct Reader<'a> {
7    buf: &'a [u8],
8    offs: usize,
9}
10
11impl<'a> Reader<'a> {
12    #[must_use]
13    pub const fn init(bytes: &[u8]) -> Reader<'_> {
14        Reader {
15            buf: bytes,
16            offs: 0,
17        }
18    }
19
20    pub fn rest(&mut self) -> &[u8] {
21        let ret = &self.buf[self.offs..];
22        self.offs = self.buf.len();
23        ret
24    }
25
26    pub fn take(&mut self, len: usize) -> Option<&[u8]> {
27        if self.left() < len {
28            return None;
29        }
30
31        let current = self.offs;
32        self.offs += len;
33        Some(&self.buf[current..current + len])
34    }
35
36    #[must_use]
37    pub fn peek(&self, len: usize) -> Option<&[u8]> {
38        if self.left() < len {
39            return None;
40        }
41
42        let current = self.offs;
43        Some(&self.buf[current..current + len])
44    }
45
46    #[must_use]
47    pub const fn any_left(&self) -> bool {
48        self.offs < self.buf.len()
49    }
50
51    #[must_use]
52    pub const fn left(&self) -> usize {
53        self.buf.len() - self.offs
54    }
55
56    #[must_use]
57    pub const fn used(&self) -> usize {
58        self.offs
59    }
60
61    pub fn sub(&mut self, len: usize) -> Option<Reader<'_>> {
62        self.take(len).map(Reader::init)
63    }
64}
65
66/// Things we can encode and read from a Reader.
67/// Used by puffin as it does not require to be `Sized` (we rely on `<dyn T>` for `T:CodecP`.
68pub trait CodecP: Debug {
69    /// Encode yourself by appending onto `bytes`.
70    fn encode(&self, bytes: &mut Vec<u8>);
71
72    /// Decode yourself by fiddling with the `Reader`.
73    /// Return Some if it worked, None if not.
74    fn read(&mut self, _: &mut Reader) -> Result<(), Error>;
75
76    /// Convenience function to get the results of `encode()`.
77    fn get_encoding(&self) -> Vec<u8> {
78        let mut ret = Vec::new();
79        self.encode(&mut ret);
80        ret
81    }
82
83    /// Read one of these from the front of `bytes` and
84    /// return it.
85    fn read_bytes(&mut self, bytes: &[u8]) -> Result<(), Error> {
86        let mut rd = Reader::init(bytes);
87        self.read(&mut rd)
88    }
89}
90
91/// Things we can encode and read from a Reader, `Sized` version.
92/// Easier to work with when types are instantiated, for example in protocol crates such as
93/// `tlspuffin`.
94pub trait Codec: Debug + Sized {
95    /// Encode yourself by appending onto `bytes`.
96    fn encode(&self, bytes: &mut Vec<u8>);
97
98    /// Decode yourself by fiddling with the `Reader`.
99    /// Return Some if it worked, None if not.
100    fn read(_: &mut Reader) -> Option<Self>;
101
102    /// Convenience function to get the results of `encode()`.
103    fn get_encoding(&self) -> Vec<u8> {
104        let mut ret = Vec::new();
105        self.encode(&mut ret);
106        ret
107    }
108
109    /// Read one of these from the front of `bytes` and
110    /// return it.
111    #[must_use]
112    fn read_bytes(bytes: &[u8]) -> Option<Self> {
113        let mut rd = Reader::init(bytes);
114        Self::read(&mut rd)
115    }
116}
117
118impl<T: Codec> CodecP for T {
119    fn encode(&self, bytes: &mut Vec<u8>) {
120        T::encode(self, bytes);
121    }
122
123    fn read(&mut self, r: &mut Reader) -> Result<(), Error> {
124        match T::read(r) {
125            None => Err(Error::Codec(format!(
126                "Failed to read for type {}",
127                std::any::type_name::<T>()
128            ))),
129            Some(it) => {
130                *self = it;
131                Ok(())
132            }
133        }
134    }
135}
136
137// Encoding functions.
138fn decode_u8(bytes: &[u8]) -> Option<u8> {
139    let [value]: [u8; 1] = bytes.try_into().ok()?;
140    Some(value)
141}
142
143impl Codec for u8 {
144    fn encode(&self, bytes: &mut Vec<u8>) {
145        bytes.push(*self);
146    }
147
148    fn read(r: &mut Reader) -> Option<Self> {
149        r.take(1).and_then(decode_u8)
150    }
151}
152
153pub fn put_u16(v: u16, out: &mut [u8]) {
154    let out: &mut [u8; 2] = (&mut out[..2]).try_into().unwrap();
155    *out = u16::to_be_bytes(v);
156}
157
158#[must_use]
159pub fn decode_u16(bytes: &[u8]) -> Option<u16> {
160    Some(u16::from_be_bytes(bytes.try_into().ok()?))
161}
162
163impl Codec for u16 {
164    fn encode(&self, bytes: &mut Vec<u8>) {
165        let mut b16 = [0u8; 2];
166        put_u16(*self, &mut b16);
167        bytes.extend_from_slice(&b16);
168    }
169
170    fn read(r: &mut Reader) -> Option<Self> {
171        r.take(2).and_then(decode_u16)
172    }
173}
174
175// Make a distinct type for u24, even though it's a u32 underneath
176#[allow(non_camel_case_types)]
177#[derive(Debug, Copy, Clone)]
178pub struct u24(pub u32);
179
180impl u24 {
181    #[must_use]
182    pub fn decode(bytes: &[u8]) -> Option<Self> {
183        let [a, b, c]: [u8; 3] = bytes.try_into().ok()?;
184        Some(Self(u32::from_be_bytes([0, a, b, c])))
185    }
186}
187
188#[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
189impl From<u24> for usize {
190    #[inline]
191    fn from(v: u24) -> Self {
192        v.0 as Self
193    }
194}
195
196impl Codec for u24 {
197    fn encode(&self, bytes: &mut Vec<u8>) {
198        let be_bytes = u32::to_be_bytes(self.0);
199        bytes.extend_from_slice(&be_bytes[1..]);
200    }
201
202    fn read(r: &mut Reader) -> Option<Self> {
203        r.take(3).and_then(Self::decode)
204    }
205}
206
207#[must_use]
208pub fn decode_u32(bytes: &[u8]) -> Option<u32> {
209    Some(u32::from_be_bytes(bytes.try_into().ok()?))
210}
211
212impl Codec for u32 {
213    fn encode(&self, bytes: &mut Vec<u8>) {
214        bytes.extend(&Self::to_be_bytes(*self));
215    }
216
217    fn read(r: &mut Reader) -> Option<Self> {
218        r.take(4).and_then(decode_u32)
219    }
220}
221
222pub fn put_u64(v: u64, bytes: &mut [u8]) {
223    let bytes: &mut [u8; 8] = (&mut bytes[..8]).try_into().unwrap();
224    *bytes = u64::to_be_bytes(v);
225}
226
227#[must_use]
228pub fn decode_u64(bytes: &[u8]) -> Option<u64> {
229    Some(u64::from_be_bytes(bytes.try_into().ok()?))
230}
231
232impl Codec for u64 {
233    fn encode(&self, bytes: &mut Vec<u8>) {
234        let mut b64 = [0u8; 8];
235        put_u64(*self, &mut b64);
236        bytes.extend_from_slice(&b64);
237    }
238
239    fn read(r: &mut Reader) -> Option<Self> {
240        r.take(8).and_then(decode_u64)
241    }
242}
243
244/// encode a Vec whose length is encoded in 1 byte
245pub fn encode_vec_u8<T: CodecP>(bytes: &mut Vec<u8>, items: &[T]) {
246    let len_offset = bytes.len();
247    bytes.push(0);
248
249    for i in items {
250        i.encode(bytes);
251    }
252
253    let len = bytes.len() - len_offset - 1;
254    bytes[len_offset] = len.min(0xff) as u8;
255}
256
257// We do not put the size of the vector for Vec<u8> as we consider it as plain data
258impl Codec for Vec<u8> {
259    fn encode(&self, bytes: &mut Vec<u8>) {
260        for i in self {
261            bytes.push(*i);
262        }
263    }
264
265    fn read(r: &mut Reader) -> Option<Self> {
266        let mut ret: Self = Self::new();
267
268        while r.any_left() {
269            ret.push(<u8 as Codec>::read(r)?);
270        }
271
272        Some(ret)
273    }
274}
275
276impl<T: Debug + Codec> Codec for Option<T> {
277    fn encode(&self, bytes: &mut Vec<u8>) {
278        if let Some(value) = self {
279            value.encode(bytes);
280        }
281    }
282
283    fn read(r: &mut Reader) -> Option<Self> {
284        if r.any_left() {
285            Some(T::read(r))
286        } else {
287            Some(None)
288        }
289    }
290}
291
292impl Codec for bool {
293    fn encode(&self, bytes: &mut Vec<u8>) {
294        if *self {
295            bytes.push(1);
296        } else {
297            bytes.push(0);
298        }
299    }
300
301    fn read(r: &mut Reader) -> Option<Self> {
302        r.take(1).map(|b| b.len() == 1 && b[0] == 1)
303    }
304}
305
306/// encode a Vec whose length is encoded in 2 bytes
307pub fn encode_vec_u16<T: Codec>(bytes: &mut Vec<u8>, items: &[T]) {
308    let len_offset = bytes.len();
309    bytes.extend(&[0, 0]);
310
311    for i in items {
312        i.encode(bytes);
313    }
314
315    let len = bytes.len() - len_offset - 2;
316    let out: &mut [u8; 2] = (&mut bytes[len_offset..len_offset + 2]).try_into().unwrap();
317    *out = u16::to_be_bytes(len.min(0xffff) as u16);
318}
319
320/// encode a Vec whose length is encoded in 3 bytes
321pub fn encode_vec_u24<T: Codec>(bytes: &mut Vec<u8>, items: &[T]) {
322    let len_offset = bytes.len();
323    bytes.extend(&[0, 0, 0]);
324
325    for i in items {
326        i.encode(bytes);
327    }
328
329    let len = bytes.len() - len_offset - 3;
330    let len_bytes = u32::to_be_bytes(len.min(0xff_ffff) as u32);
331    let out: &mut [u8; 3] = (&mut bytes[len_offset..len_offset + 3]).try_into().unwrap();
332    out.copy_from_slice(&len_bytes[1..]);
333}
334
335pub fn read_vec_u8<T: Codec>(r: &mut Reader) -> Option<Vec<T>> {
336    let mut ret: Vec<T> = Vec::new();
337    let len = usize::from(<u8 as Codec>::read(r)?);
338    let mut sub = r.sub(len)?;
339
340    while sub.any_left() {
341        ret.push(T::read(&mut sub)?);
342    }
343
344    Some(ret)
345}
346
347pub fn read_vec_u16<T: Codec>(r: &mut Reader) -> Option<Vec<T>> {
348    let mut ret: Vec<T> = Vec::new();
349    let len = usize::from(<u16 as Codec>::read(r)?);
350    let mut sub = r.sub(len)?;
351
352    while sub.any_left() {
353        ret.push(T::read(&mut sub)?);
354    }
355
356    Some(ret)
357}
358
359pub fn read_vec_u24_limited<T: Codec>(r: &mut Reader, max_bytes: usize) -> Option<Vec<T>> {
360    let mut ret: Vec<T> = Vec::new();
361    let len = <u24 as Codec>::read(r)?.0 as usize;
362    if len > max_bytes {
363        return None;
364    }
365
366    let mut sub = r.sub(len)?;
367
368    while sub.any_left() {
369        ret.push(T::read(&mut sub)?);
370    }
371
372    Some(ret)
373}
374
375impl Codec for [u8; 16] {
376    fn encode(&self, bytes: &mut Vec<u8>) {
377        bytes.extend_from_slice(self);
378    }
379
380    fn read(r: &mut Reader) -> Option<Self> {
381        <Vec<u8> as Codec>::read(r).map(|v| {
382            let mut ret = [0u8; 16];
383            ret.copy_from_slice(&v);
384            ret
385        })
386    }
387}
388
389impl Codec for String {
390    fn encode(&self, bytes: &mut Vec<u8>) {
391        <Vec<u8> as Codec>::encode(&self.as_bytes().to_vec(), bytes);
392    }
393
394    fn read(r: &mut Reader) -> Option<Self> {
395        <Vec<u8> as Codec>::read(r).map(|v| String::from_utf8_lossy(&v).to_string())
396    }
397}
398
399/// Trait for data whose Vectors are encoded without length prefix
400pub trait VecCodecWoSize {}
401impl VecCodecWoSize for Vec<u8> {}
402
403impl<T: Codec + VecCodecWoSize> Codec for Vec<T> {
404    fn encode(&self, bytes: &mut Vec<u8>) {
405        for i in self {
406            i.encode(bytes);
407        }
408    }
409
410    fn read(r: &mut Reader) -> Option<Self> {
411        let mut ret: Self = Self::new();
412
413        while r.any_left() {
414            ret.push(T::read(r)?);
415        }
416
417        Some(ret)
418    }
419}
420
421pub fn compare_encoding<X: Codec, Y: Codec>(x: &X, y: &Y) -> std::cmp::Ordering {
422    let x_enc = Codec::get_encoding(x);
423    let y_enc = Codec::get_encoding(y);
424
425    if x_enc < y_enc {
426        std::cmp::Ordering::Less
427    } else if x_enc > y_enc {
428        std::cmp::Ordering::Greater
429    } else {
430        std::cmp::Ordering::Equal
431    }
432}