s2n-codec 0.77.0

Internal crate used by s2n-quic
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

macro_rules! doc_comment {
    ($($x:expr)*; $($tt:tt)*) => {
        doc_comment!(@doc concat!($($x, "\n",)*), $($tt)*);
    };
    (@doc $x:expr, $($tt:tt)*) => {
        #[doc = $x]
        $($tt)*
    };
}

macro_rules! impl_buffer {
    ($name:ident, $result:ident, $value:ident, $value_call:ident, $parameterized:ident, $parameterized_call:ident, $split:ident) => {
        impl<'a> $name<'a> {
            doc_comment! {
                "Decode a slice of bytes by `count`, removing the slice from the current buffer"

                "```"
                "# use s2n_codec::*;"
                "let mut data = [0, 1, 2, 3, 4];"
                concat!("let buffer = ", stringify!($name), "::new(&mut data);")
                ""
                "let (slice, buffer) = buffer.decode_slice(5).unwrap();"
                "assert_eq!(slice, [0u8, 1, 2, 3, 4][..]);"
                ""
                "assert!(buffer.is_empty());"
                "```";

                #[inline]
                pub fn decode_slice(self, count: usize) -> $result<'a, $name<'a>> {
                    self.ensure_len(count)?;

                    let (slice, remaining) = self.bytes.$split(count);

                    Ok((Self::new(slice), Self::new(remaining)))
                }
            }

            doc_comment! {
                "Decode a value of type `T`, splitting the data from the current buffer"

                "```"
                "# use s2n_codec::*;"
                "let mut data = [0, 1, 2, 3, 4, 5, 6];"
                concat!("let buffer = ", stringify!($name), "::new(&mut data);")
                ""
                "let (value, buffer) = buffer.decode::<u8>().unwrap();"
                "assert_eq!(value, 0);"
                ""
                "let (value, buffer) = buffer.decode::<u16>().unwrap();"
                "assert_eq!(value, 258);"
                ""
                "let (value, buffer) = buffer.decode::<u32>().unwrap();"
                "assert_eq!(value, 50_595_078);"
                ""
                "assert!(buffer.is_empty());"
                "```";

                #[inline]
                pub fn decode<T: $value<'a>>(self) -> $result<'a, T> {
                    T::$value_call(self)
                }
            }

            doc_comment! {
                "Decode a value of type `T` from a buffer that is exactly the length of `T`."
                ""
                "Returns an error if any data remains.";
                #[inline]
                pub fn decode_exact<T: $value<'a>>(self) -> Result<T, DecoderError> {
                    let (value, remaining) = T::$value_call(self)?;
                    if !remaining.is_empty() {
                        Err(DecoderError::UnexpectedBytes(remaining.len()))
                    } else {
                        Ok(value)
                    }
                }
            }

            doc_comment! {
                "Decode a slice prefixed by type `Length`, splitting the data from the"
                "current buffer."

                "With a `Length` as encoded `u8`:"
                "```rust"
                "# use s2n_codec::*;"
                "let mut data = [5, 0, 1, 2, 3, 4];"
                concat!("let buffer = ", stringify!($name), "::new(&mut data);")
                "let (slice, buffer) = buffer.decode_slice_with_len_prefix::<u8>().unwrap();"
                "assert_eq!(slice, [0u8, 1, 2, 3, 4][..]);"
                "assert!(buffer.is_empty())"
                "```"

                "With a `Length` as encoded `u16`:"
                "```rust"
                "# use s2n_codec::*;"
                "let mut data = [0, 5, 0, 1, 2, 3, 4];"
                concat!("let buffer = ", stringify!($name), "::new(&mut data);")
                "let (slice, buffer) = buffer.decode_slice_with_len_prefix::<u16>().unwrap();"
                "assert_eq!(slice, [0u8, 1, 2, 3, 4][..]);"
                "assert!(buffer.is_empty())"
                "```";

                #[inline]
                pub fn decode_slice_with_len_prefix<Length: $value<'a> + core::convert::TryInto<usize>>(
                    self,
                ) -> $result<'a, Self> {
                    let (len, buffer) = self.decode::<Length>()?;
                    let len = len.try_into().map_err(|_| DecoderError::LengthCapacityExceeded)?;
                    buffer.decode_slice(len)
                }
            }

            doc_comment! {
                "Decode a value of type `T` prefixed by type `Length`, splitting the data from the"
                "current buffer."

                "With a `Length` as encoded `u8` and `T` as `u16`:"
                "```rust"
                "# use s2n_codec::*;"
                "let mut data = [2, 0, 1, 2, 3];"
                concat!("let buffer = ", stringify!($name), "::new(&mut data);")
                "let (value, buffer) = buffer.decode_with_len_prefix::<u8, u16>().unwrap();"
                "assert_eq!(value, 1);"
                "assert_eq!(buffer, [2, 3][..])"
                "```"

                concat!("The `", stringify!($value) ,"` implementation of `T` must consume the entire subslice")
                "otherwise an error will be returned."

                "```rust"
                "# use s2n_codec::*;"
                "let mut data = [3, 0, 1, 2];"
                concat!("let buffer = ", stringify!($name), "::new(&mut data);")
                "let result = buffer.decode_with_len_prefix::<u8, u16>();"
                "assert!(result.is_err())"
                "```";

                #[inline]
                pub fn decode_with_len_prefix<Length: $value<'a> + core::convert::TryInto<usize>, T: $value<'a>>(
                    self,
                ) -> $result<'a, T> {
                    let (slice, buffer) = self.decode_slice_with_len_prefix::<Length>()?;
                    let (value, slice) = slice.decode::<T>()?;
                    slice.ensure_empty()?;
                    Ok((value, buffer))
                }
            }

            doc_comment! {
                "Decode a parameterized value of type `T` implementing `"
                stringify!($parameterized) "`";

                #[inline]
                pub fn decode_parameterized<T: $parameterized<'a>>(
                    self,
                    parameter: T::Parameter,
                ) -> $result<'a, T> {
                    T::$parameterized_call(parameter, self)
                }
            }

            doc_comment! {
                "Skip a `count` of bytes, discarding the bytes"

                "```rust"
                "# use s2n_codec::*;"
                "let mut data = [0, 1, 2, 3, 4];"
                concat!("let buffer = ", stringify!($name), "::new(&mut data);")
                "let buffer = buffer.skip(3).unwrap();"
                "assert_eq!(buffer, [3, 4][..]);"
                "```";

                #[inline]
                pub fn skip(self, count: usize) -> Result<$name<'a>, DecoderError> {
                    self.decode_slice(count).map(|(_, buffer)| buffer)
                }
            }

            doc_comment! {
                "Skip a number of bytes encoded as a length prefix of type `Length`"

                "With a `Length` encoded as `u8`:"
                "```rust"
                "# use s2n_codec::*;"
                "let mut data = [5, 0, 1, 2, 3, 4];"
                concat!("let buffer = ", stringify!($name), "::new(&mut data);")
                "let buffer = buffer.skip_with_len_prefix::<u8>().unwrap();"
                "assert!(buffer.is_empty());"
                "```";

                #[inline]
                pub fn skip_with_len_prefix<Length: $value<'a> + core::convert::TryInto<usize>>(
                    self,
                ) -> Result<$name<'a>, DecoderError> {
                    let (len, buffer) = self.decode::<Length>()?;
                    let len = len.try_into().map_err(|_| DecoderError::LengthCapacityExceeded)?;
                    buffer.skip(len)
                }
            }

            doc_comment! {
                "Skip a `count` of bytes, returning a `CheckedRange` for later access";
                // TODO add doctest

                #[inline]
                pub fn skip_into_range(
                    self,
                    count: usize,
                    original_buffer: &crate::DecoderBufferMut,
                ) -> $result<'a, crate::CheckedRange> {
                    let start = original_buffer.len() - self.len();
                    let (slice, buffer) = self.decode_slice(count)?;
                    let end = start + count;
                    Ok((
                        crate::CheckedRange::new(start, end, slice.bytes.as_ptr()),
                        buffer,
                    ))
                }
            }

            doc_comment! {
                "Skip a number of bytes encoded as a length prefix of type `Length`"
                "into a `CheckedRange` for later access";
                // TODO add doctest

                #[inline]
                pub fn skip_into_range_with_len_prefix<Length: $value<'a> + core::convert::TryInto<usize>>(
                    self,
                    original_buffer: &crate::DecoderBufferMut,
                ) -> $result<'a, crate::CheckedRange> {
                    let (len, buffer) = self.decode::<Length>()?;
                    let len = len.try_into().map_err(|_| DecoderError::LengthCapacityExceeded)?;
                    buffer.skip_into_range(len, original_buffer)
                }
            }

            doc_comment! {
                "Reads data from a `CheckedRange`";
                // TODO add doctest

                #[inline]
                pub fn get_checked_range(&self, range: &crate::CheckedRange) -> DecoderBuffer<'_> {
                    range.get(self.bytes).into()
                }
            }

            doc_comment! {
                "Create a peeking `DecoderBuffer` from the current buffer view"

                "```rust"
                "# use s2n_codec::*;"
                "let mut data = [0, 1];"
                concat!("let buffer = ", stringify!($name), "::new(&mut data);")
                ""
                "let peek = buffer.peek();"
                "let (value, peek) = peek.decode::<u16>().unwrap();"
                "assert_eq!(value, 1);"
                "assert!(peek.is_empty());"
                ""
                "// `buffer` still contains the previous view"
                "assert_eq!(buffer, [0, 1][..]);"
                "```";

                #[inline]
                #[must_use]
                pub fn peek(&'a self) -> crate::DecoderBuffer<'a> {
                    crate::DecoderBuffer::new(self.bytes)
                }
            }

            doc_comment! {
                "Returns a single byte at `index`"

                "```rust"
                "# use s2n_codec::*;"
                "let mut data = [0, 1, 2];"
                concat!("let buffer = ", stringify!($name), "::new(&mut data);")
                ""
                "assert_eq!(buffer.peek_byte(0).unwrap(), 0);"
                "assert_eq!(buffer.peek_byte(1).unwrap(), 1);"
                "assert_eq!(buffer.peek_byte(2).unwrap(), 2);"
                ""
                "// `buffer` has not changed"
                "assert_eq!(buffer, [0, 1, 2][..]);"
                "```";

                #[inline]
                pub fn peek_byte(&self, index: usize) -> Result<u8, DecoderError> {
                    self.bytes
                        .get(index)
                        .cloned()
                        .ok_or_else(|| DecoderError::UnexpectedEof(index))
                }
            }

            /// Returns a `PeekBuffer` by `range`
            #[inline]
            pub fn peek_range(
                &self,
                range: core::ops::Range<usize>,
            ) -> Result<crate::DecoderBuffer<'_>, DecoderError> {
                let end = range.end;
                self.bytes
                    .get(range)
                    .map(|bytes| bytes.into())
                    .ok_or_else(|| DecoderError::UnexpectedEof(end))
            }

            doc_comment! {
                "Returns an error if the buffer is not empty."

                "```rust"
                "# use s2n_codec::*;"
                "let mut data = [1];"
                concat!("let buffer = ", stringify!($name), "::new(&mut data);")
                ""
                "assert!(buffer.ensure_empty().is_err());"
                "let (_, buffer) = buffer.decode::<u8>().unwrap();"
                "assert!(buffer.ensure_empty().is_ok());"
                "```";

                #[inline]
                pub fn ensure_empty(&self) -> Result<(), DecoderError> {
                    if !self.is_empty() {
                        Err(DecoderError::UnexpectedBytes(self.len()))
                    } else {
                        Ok(())
                    }
                }
            }

            doc_comment! {
                "Returns an error if the buffer does not have at least `len` bytes."

                "```rust"
                "# use s2n_codec::*;"
                "let mut data = [0, 1, 2];"
                concat!("let buffer = ", stringify!($name), "::new(&mut data);")
                ""
                "assert!(buffer.ensure_len(2).is_ok());"
                "assert!(buffer.ensure_len(5).is_err());"
                "```";

                #[inline]
                pub fn ensure_len(&self, len: usize) -> Result<(), DecoderError> {
                    if self.len() < len {
                        Err(DecoderError::UnexpectedEof(len))
                    } else {
                        Ok(())
                    }
                }
            }

            doc_comment! {
                "Returns the number of bytes in the buffer."

                "```rust"
                "# use s2n_codec::*;"
                "let mut data = [0, 1, 2];"
                concat!("let buffer = ", stringify!($name), "::new(&mut data);")
                ""
                "assert_eq!(buffer.len(), 3);"
                "let (_, buffer) = buffer.decode::<u8>().unwrap();"
                "assert_eq!(buffer.len(), 2);"
                "```";

                #[inline]
                pub fn len(&self) -> usize {
                    self.bytes.len()
                }
            }

            doc_comment! {
                "Returns true if the buffer has a length of 0."

                "```rust"
                "# use s2n_codec::*;"
                "let mut data = [1];"
                concat!("let buffer = ", stringify!($name), "::new(&mut data);")
                ""
                "assert!(!buffer.is_empty());"
                "let (_, buffer) = buffer.decode::<u8>().unwrap();"
                "assert!(buffer.is_empty());"
                "```";

                #[inline]
                pub fn is_empty(&self) -> bool {
                    self.bytes.is_empty()
                }
            }

            /// Borrows the buffer's slice. This should be used with caution, as it
            /// removes any panic protection this struct provides.
            #[inline]
            pub fn as_less_safe_slice(&'a self) -> &'a [u8] {
                self.bytes
            }
        }

        impl<'a> From<&'a mut [u8]> for $name<'a> {
            #[inline]
            fn from(bytes: &'a mut [u8]) -> Self {
                Self::new(bytes)
            }
        }

        impl<'a> PartialEq<[u8]> for $name<'a> {
            #[inline]
            fn eq(&self, rhs: &[u8]) -> bool {
                let bytes: &[u8] = self.bytes.as_ref();
                bytes.eq(rhs)
            }
        }
    };
}

pub mod buffer;
pub mod buffer_mut;
pub mod checked_range;
#[macro_use]
pub mod value;

pub use buffer::*;
pub use buffer_mut::*;
pub use checked_range::*;
pub use value::*;

#[derive(Clone, Copy, Debug)]
pub enum DecoderError {
    UnexpectedEof(usize),
    UnexpectedBytes(usize),
    LengthCapacityExceeded,
    InvariantViolation(&'static str), // TODO replace with a &'static Invariant
}

impl core::error::Error for DecoderError {}

use core::fmt;
impl fmt::Display for DecoderError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // https://github.com/model-checking/kani/issues/1767#issuecomment-1275449305
        if cfg!(kani) {
            return Ok(());
        }

        match self {
            Self::UnexpectedEof(len) => write!(f, "unexpected eof: {len}"),
            Self::UnexpectedBytes(len) => write!(f, "unexpected bytes: {len}"),
            Self::LengthCapacityExceeded => write!(
                f,
                "length could not be represented in platform's usize type"
            ),
            Self::InvariantViolation(msg) => write!(f, "{msg}"),
        }
    }
}

impl From<DecoderError> for &'static str {
    fn from(error: DecoderError) -> Self {
        match error {
            DecoderError::UnexpectedEof(_len) => "unexpected eof",
            DecoderError::UnexpectedBytes(_len) => "unexpected bytes",
            DecoderError::LengthCapacityExceeded => {
                "length could not be represented in platform's usize type"
            }
            DecoderError::InvariantViolation(msg) => msg,
        }
    }
}

#[macro_export]
macro_rules! decoder_invariant {
    ($expr:expr, $invariant:expr) => {
        if !($expr) {
            return ::core::result::Result::Err(
                $crate::decoder::DecoderError::InvariantViolation($invariant).into(),
            );
        }
    };
}

#[cfg(test)]
mod tests {
    use super::*;

    // === decode_exact tests ===

    #[test]
    fn decode_exact_success() {
        let buf = DecoderBuffer::new(&[0, 42]);
        let val: u16 = buf.decode_exact().unwrap();
        assert_eq!(val, 42);
    }

    #[test]
    fn decode_exact_trailing_bytes_error() {
        let buf = DecoderBuffer::new(&[1, 2, 3]);
        assert!(buf.decode_exact::<u8>().is_err());
    }

    #[test]
    fn decode_exact_too_short_error() {
        let buf = DecoderBuffer::new(&[1]);
        assert!(buf.decode_exact::<u32>().is_err());
    }

    #[test]
    fn decode_exact_empty_buffer_error() {
        let buf = DecoderBuffer::new(&[]);
        assert!(buf.decode_exact::<u8>().is_err());
    }

    // === DecoderError as std::error::Error ===

    #[test]
    fn decoder_error_implements_std_error() {
        fn takes_error(_: &dyn std::error::Error) {}
        let err = DecoderError::UnexpectedEof(0);
        takes_error(&err);
    }

    #[test]
    fn decoder_error_display() {
        let err = DecoderError::UnexpectedEof(5);
        assert_eq!(format!("{err}"), "unexpected eof: 5");

        let err = DecoderError::UnexpectedBytes(3);
        assert_eq!(format!("{err}"), "unexpected bytes: 3");

        let err = DecoderError::InvariantViolation("bad");
        assert_eq!(format!("{err}"), "bad");
    }

    #[test]
    fn decoder_error_in_box_dyn() -> Result<(), Box<dyn std::error::Error>> {
        let buf = DecoderBuffer::new(&[0, 1]);
        let _: u16 = buf.decode_exact()?;
        Ok(())
    }
}