rustls/msgs/
codec.rs

1use std::fmt::Debug;
2
3/// Read from a byte slice.
4pub struct Reader<'a> {
5    buf: &'a [u8],
6    offs: usize,
7}
8
9impl<'a> Reader<'a> {
10    pub fn init(bytes: &[u8]) -> Reader {
11        Reader {
12            buf: bytes,
13            offs: 0,
14        }
15    }
16
17    pub fn rest(&mut self) -> &[u8] {
18        let ret = &self.buf[self.offs..];
19        self.offs = self.buf.len();
20        ret
21    }
22
23    pub fn take(&mut self, len: usize) -> Option<&[u8]> {
24        if self.left() < len {
25            return None;
26        }
27
28        let current = self.offs;
29        self.offs += len;
30        Some(&self.buf[current..current + len])
31    }
32
33    pub fn any_left(&self) -> bool {
34        self.offs < self.buf.len()
35    }
36
37    pub fn left(&self) -> usize {
38        self.buf.len() - self.offs
39    }
40
41    pub fn used(&self) -> usize {
42        self.offs
43    }
44
45    pub fn sub(&mut self, len: usize) -> Option<Reader> {
46        self.take(len).map(Reader::init)
47    }
48}
49
50/// Things we can encode and read from a Reader.
51pub trait Codec: Debug + Sized {
52    /// Encode yourself by appending onto `bytes`.
53    fn encode(&self, bytes: &mut Vec<u8>);
54
55    /// Decode yourself by fiddling with the `Reader`.
56    /// Return Some if it worked, None if not.
57    fn read(_: &mut Reader) -> Option<Self>;
58
59    /// Convenience function to get the results of `encode()`.
60    fn get_encoding(&self) -> Vec<u8> {
61        let mut ret = Vec::new();
62        self.encode(&mut ret);
63        ret
64    }
65
66    /// Read one of these from the front of `bytes` and
67    /// return it.
68    fn read_bytes(bytes: &[u8]) -> Option<Self> {
69        let mut rd = Reader::init(bytes);
70        Self::read(&mut rd)
71    }
72}
73
74// Encoding functions.
75pub fn decode_u8(bytes: &[u8]) -> Option<u8> {
76    Some(bytes[0])
77}
78
79impl Codec for u8 {
80    fn encode(&self, bytes: &mut Vec<u8>) {
81        bytes.push(*self);
82    }
83    fn read(r: &mut Reader) -> Option<u8> {
84        r.take(1).and_then(decode_u8)
85    }
86}
87
88pub fn put_u16(v: u16, out: &mut [u8]) {
89    out[0] = (v >> 8) as u8;
90    out[1] = v as u8;
91}
92
93pub fn decode_u16(bytes: &[u8]) -> Option<u16> {
94    Some((u16::from(bytes[0]) << 8) | u16::from(bytes[1]))
95}
96
97impl Codec for u16 {
98    fn encode(&self, bytes: &mut Vec<u8>) {
99        let mut b16 = [0u8; 2];
100        put_u16(*self, &mut b16);
101        bytes.extend_from_slice(&b16);
102    }
103
104    fn read(r: &mut Reader) -> Option<u16> {
105        r.take(2).and_then(decode_u16)
106    }
107}
108
109// Make a distinct type for u24, even though it's a u32 underneath
110#[allow(non_camel_case_types)]
111#[derive(Debug)]
112pub struct u24(pub u32);
113
114impl u24 {
115    pub fn decode(bytes: &[u8]) -> Option<u24> {
116        Some(u24((u32::from(bytes[0]) << 16)
117            | (u32::from(bytes[1]) << 8)
118            | u32::from(bytes[2])))
119    }
120}
121
122impl Codec for u24 {
123    fn encode(&self, bytes: &mut Vec<u8>) {
124        bytes.push((self.0 >> 16) as u8);
125        bytes.push((self.0 >> 8) as u8);
126        bytes.push(self.0 as u8);
127    }
128
129    fn read(r: &mut Reader) -> Option<u24> {
130        r.take(3).and_then(u24::decode)
131    }
132}
133
134pub fn decode_u32(bytes: &[u8]) -> Option<u32> {
135    Some(
136        (u32::from(bytes[0]) << 24)
137            | (u32::from(bytes[1]) << 16)
138            | (u32::from(bytes[2]) << 8)
139            | u32::from(bytes[3]),
140    )
141}
142
143impl Codec for u32 {
144    fn encode(&self, bytes: &mut Vec<u8>) {
145        bytes.push((*self >> 24) as u8);
146        bytes.push((*self >> 16) as u8);
147        bytes.push((*self >> 8) as u8);
148        bytes.push(*self as u8);
149    }
150
151    fn read(r: &mut Reader) -> Option<u32> {
152        r.take(4).and_then(decode_u32)
153    }
154}
155
156pub fn put_u64(v: u64, bytes: &mut [u8]) {
157    bytes[0] = (v >> 56) as u8;
158    bytes[1] = (v >> 48) as u8;
159    bytes[2] = (v >> 40) as u8;
160    bytes[3] = (v >> 32) as u8;
161    bytes[4] = (v >> 24) as u8;
162    bytes[5] = (v >> 16) as u8;
163    bytes[6] = (v >> 8) as u8;
164    bytes[7] = v as u8;
165}
166
167pub fn decode_u64(bytes: &[u8]) -> Option<u64> {
168    Some(
169        (u64::from(bytes[0]) << 56)
170            | (u64::from(bytes[1]) << 48)
171            | (u64::from(bytes[2]) << 40)
172            | (u64::from(bytes[3]) << 32)
173            | (u64::from(bytes[4]) << 24)
174            | (u64::from(bytes[5]) << 16)
175            | (u64::from(bytes[6]) << 8)
176            | u64::from(bytes[7]),
177    )
178}
179
180impl Codec for u64 {
181    fn encode(&self, bytes: &mut Vec<u8>) {
182        let mut b64 = [0u8; 8];
183        put_u64(*self, &mut b64);
184        bytes.extend_from_slice(&b64);
185    }
186
187    fn read(r: &mut Reader) -> Option<u64> {
188        r.take(8).and_then(decode_u64)
189    }
190}
191
192pub fn encode_vec_u8<T: Codec>(bytes: &mut Vec<u8>, items: &[T]) {
193    let mut sub: Vec<u8> = Vec::new();
194    for i in items {
195        i.encode(&mut sub);
196    }
197
198    debug_assert!(sub.len() <= 0xff);
199    (sub.len() as u8).encode(bytes);
200    bytes.append(&mut sub);
201}
202
203pub fn encode_vec_u16<T: Codec>(bytes: &mut Vec<u8>, items: &[T]) {
204    let mut sub: Vec<u8> = Vec::new();
205    for i in items {
206        i.encode(&mut sub);
207    }
208
209    debug_assert!(sub.len() <= 0xffff);
210    (sub.len() as u16).encode(bytes);
211    bytes.append(&mut sub);
212}
213
214pub fn encode_vec_u24<T: Codec>(bytes: &mut Vec<u8>, items: &[T]) {
215    let mut sub: Vec<u8> = Vec::new();
216    for i in items {
217        i.encode(&mut sub);
218    }
219
220    debug_assert!(sub.len() <= 0xff_ffff);
221    u24(sub.len() as u32).encode(bytes);
222    bytes.append(&mut sub);
223}
224
225pub fn read_vec_u8<T: Codec>(r: &mut Reader) -> Option<Vec<T>> {
226    let mut ret: Vec<T> = Vec::new();
227    let len = usize::from(u8::read(r)?);
228    let mut sub = r.sub(len)?;
229
230    while sub.any_left() {
231        ret.push(T::read(&mut sub)?);
232    }
233
234    Some(ret)
235}
236
237pub fn read_vec_u16<T: Codec>(r: &mut Reader) -> Option<Vec<T>> {
238    let mut ret: Vec<T> = Vec::new();
239    let len = usize::from(u16::read(r)?);
240    let mut sub = r.sub(len)?;
241
242    while sub.any_left() {
243        ret.push(T::read(&mut sub)?);
244    }
245
246    Some(ret)
247}
248
249pub fn read_vec_u24_limited<T: Codec>(r: &mut Reader, max_bytes: usize) -> Option<Vec<T>> {
250    let mut ret: Vec<T> = Vec::new();
251    let len = u24::read(r)?.0 as usize;
252    if len > max_bytes {
253        return None;
254    }
255
256    let mut sub = r.sub(len)?;
257
258    while sub.any_left() {
259        ret.push(T::read(&mut sub)?);
260    }
261
262    Some(ret)
263}