Skip to main content

packet/
lib.rs

1// Copyright 2018 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Parsing and serialization of (network) packets.
6//!
7//! `packet` is a library to help with the parsing and serialization of nested
8//! packets. Network packets are the most common use case, but it supports any
9//! packet structure with headers, footers, and nesting.
10//!
11//! # Model
12//!
13//! The core components of `packet` are the various buffer traits (`XxxBuffer`
14//! and `XxxBufferMut`). A buffer is a byte buffer with a prefix, a body, and a
15//! suffix. The size of the buffer is referred to as its "capacity", and the
16//! size of the body is referred to as its "length". Depending on which traits
17//! are implemented, the body of the buffer may be able to shrink or grow as
18//! allowed by the capacity as packets are parsed or serialized.
19//!
20//! ## Parsing
21//!
22//! When parsing packets, the body of the buffer stores the next packet to be
23//! parsed. When a packet is parsed from the buffer, any headers, footers, and
24//! padding are "consumed" from the buffer. Thus, after a packet has been
25//! parsed, the body of the buffer is equal to the body of the packet, and the
26//! next call to `parse` will pick up where the previous call left off, parsing
27//! the next encapsulated packet.
28//!
29//! Packet objects - the Rust objects which are the result of a successful
30//! parsing operation - are advised to simply keep references into the buffer
31//! for the header, footer, and body. This avoids any unnecessary copying.
32//!
33//! For example, consider the following packet structure, in which a TCP segment
34//! is encapsulated in an IPv4 packet, which is encapsulated in an Ethernet
35//! frame. In this example, we omit the Ethernet Frame Check Sequence (FCS)
36//! footer. If there were any footers, they would be treated the same as
37//! headers, except that they would be consumed from the end and working towards
38//! the beginning, as opposed to headers, which are consumed from the beginning
39//! and working towards the end.
40//!
41//! Also note that, in order to satisfy Ethernet's minimum body size
42//! requirement, padding is added after the IPv4 packet. The IPv4 packet and
43//! padding together are considered the body of the Ethernet frame. If we were
44//! to include the Ethernet FCS footer in this example, it would go after the
45//! padding.
46//!
47//! ```text
48//! |-------------------------------------|++++++++++++++++++++|-----| TCP segment
49//! |-----------------|++++++++++++++++++++++++++++++++++++++++|-----| IPv4 packet
50//! |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| Ethernet frame
51//!
52//! |-----------------|-------------------|--------------------|-----|
53//!   Ethernet header      IPv4 header         TCP segment      Padding
54//! ```
55//!
56//! At first, the buffer's body would be equal to the bytes of the Ethernet
57//! frame (although depending on how the buffer was initialized, it might have
58//! extra capacity in addition to the body):
59//!
60//! ```text
61//! |-------------------------------------|++++++++++++++++++++|-----| TCP segment
62//! |-----------------|++++++++++++++++++++++++++++++++++++++++|-----| IPv4 packet
63//! |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| Ethernet frame
64//!
65//! |-----------------|-------------------|--------------------|-----|
66//!   Ethernet header      IPv4 header         TCP segment      Padding
67//!
68//! |----------------------------------------------------------------|
69//!                             Buffer Body
70//! ```
71//!
72//! First, the Ethernet frame is parsed. This results in a hypothetical
73//! `EthernetFrame` object (this library does not provide any concrete parsing
74//! implementations) with references into the buffer, and updates the body of
75//! the buffer to be equal to the body of the Ethernet frame:
76//!
77//! ```text
78//! |-------------------------------------|++++++++++++++++++++|-----| TCP segment
79//! |-----------------|++++++++++++++++++++++++++++++++++++++++|-----| IPv4 packet
80//! |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| Ethernet frame
81//!
82//! |-----------------|----------------------------------------------|
83//!   Ethernet header                  Ethernet body
84//!          |                                 |
85//!          +--------------------------+      |
86//!                                     |      |
87//!                   EthernetFrame { header, body }
88//!
89//! |-----------------|----------------------------------------------|
90//!    buffer prefix                   buffer body
91//! ```
92//!
93//! The `EthernetFrame` object mutably borrows the buffer. So long as it exists,
94//! the buffer cannot be used directly (although the `EthernetFrame` object may
95//! be used to access or modify the contents of the buffer). In order to parse
96//! the body of the Ethernet frame, we have to drop the `EthernetFrame` object
97//! so that we can call methods on the buffer again. \[1\]
98//!
99//! After dropping the `EthernetFrame` object, the IPv4 packet is parsed. Recall
100//! that the Ethernet body contains both the IPv4 packet and some padding. Since
101//! IPv4 packets encode their own length, the IPv4 packet parser is able to
102//! detect that some of the bytes it's operating on are padding bytes. It is the
103//! parser's responsibility to consume and discard these bytes so that they are
104//! not erroneously treated as part of the IPv4 packet's body in subsequent
105//! parsings.
106//!
107//! This parsing results in a hypothetical `Ipv4Packet` object with references
108//! into the buffer, and updates the body of the buffer to be equal to the body
109//! of the IPv4 packet:
110//!
111//! ```text
112//! |-------------------------------------|++++++++++++++++++++|-----| TCP segment
113//! |-----------------|++++++++++++++++++++++++++++++++++++++++|-----| IPv4 packet
114//! |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| Ethernet frame
115//!
116//! |-----------------|-------------------|--------------------|-----|
117//!                        IPv4 header          IPv4 body
118//!                             |                   |
119//!                             +-----------+       |
120//!                                         |       |
121//!                          Ipv4Packet { header, body }
122//!
123//! |-------------------------------------|--------------------|-----|
124//!              buffer prefix                 buffer body       buffer suffix
125//! ```
126//!
127//! We can continue this process as long as we like, repeatedly parsing
128//! subsequent packet bodies until there are no more packets to parse.
129//!
130//! \[1\] It is also possible to treat the `EthernetFrame`'s `body` field as a
131//! buffer and parse from it directly. However, this has the disadvantage that
132//! if parsing is spread across multiple functions, the functions which parse
133//! the inner packets only see part of the buffer, and so if they wish to later
134//! re-use the buffer for serializing new packets (see the "Serialization"
135//! section of this documentation), they are limited to doing so in a smaller
136//! buffer, making it more likely that a new buffer will need to be allocated.
137//!
138//! ## Serialization
139//!
140//! In this section, we will illustrate serialization using the same packet
141//! structure that was used to illustrate parsing - a TCP segment in an IPv4
142//! packet in an Ethernet frame.
143//!
144//! Serialization comprises two tasks:
145//! - First, given a buffer with sufficient capacity, and part of the packet
146//!   already serialized, serialize the next layer of the packet. For example,
147//!   given a buffer with a TCP segment already serialized in it, serialize the
148//!   IPv4 header, resulting in an IPv4 packet containing a TCP segment.
149//! - Second, given a description of a nested sequence of packets, figure out
150//!   the constraints that a buffer must satisfy in order to be able to fit the
151//!   entire sequence, and allocate a buffer which satisfies those constraints.
152//!   This buffer is then used to serialize one layer at a time, as described in
153//!   the previous bullet.
154//!
155//! ### Serializing into a buffer
156//!
157//! The [`PacketBuilder`] trait is implemented by types which are capable of
158//! serializing a new layer of a packet into an existing buffer. For example, we
159//! might define an `Ipv4PacketBuilder` type, which describes the source IP
160//! address, destination IP address, and any other metadata required to generate
161//! the header of an IPv4 packet. Importantly, a `PacketBuilder` does *not*
162//! define any encapsulated packets. In order to construct a TCP segment in an
163//! IPv4 packet, we would need a separate `TcpSegmentBuilder` to describe the
164//! TCP segment.
165//!
166//! A `PacketBuilder` exposes the number of bytes it requires for headers,
167//! footers, and minimum and maximum body lengths via the `constraints` method.
168//! It serializes via the `serialize` method.
169//!
170//! In order to serialize a `PacketBuilder`, a [`SerializeTarget`] must first be
171//! constructed. A `SerializeTarget` is a view into a buffer used for
172//! serialization, and it is initialized with the proper number of bytes for the
173//! header, footer, and body. The number of bytes required for these is
174//! discovered through calls to the `PacketBuilder`'s `constraints` method.
175//!
176//! The `PacketBuilder`'s `serialize` method serializes the headers and footers
177//! of the packet into the buffer. It expects that the `SerializeTarget` is
178//! initialized with a body equal to the body which will be encapsulated. For
179//! example, imagine that we are trying to serialize a TCP segment in an IPv4
180//! packet in an Ethernet frame, and that, so far, we have only serialized the
181//! TCP segment:
182//!
183//! ```text
184//! |-------------------------------------|++++++++++++++++++++|-----| TCP segment
185//! |-----------------|++++++++++++++++++++++++++++++++++++++++|-----| IPv4 packet
186//! |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| Ethernet frame
187//!
188//! |-------------------------------------|--------------------|-----|
189//!                                             TCP segment
190//!
191//! |-------------------------------------|--------------------|-----|
192//!              buffer prefix                 buffer body       buffer suffix
193//! ```
194//!
195//! Note that the buffer's body is currently equal to the TCP segment, and the
196//! contents of the body are already initialized to the segment's contents.
197//!
198//! Given an `Ipv4PacketBuilder`, we call the appropriate methods to discover
199//! that it requires 20 bytes for its header. Thus, we modify the buffer by
200//! extending the body by 20 bytes, and constructing a `SerializeTarget` whose
201//! header references the newly-added 20 bytes, and whose body references the
202//! old contents of the body, corresponding to the TCP segment.
203//!
204//! ```text
205//! |-------------------------------------|++++++++++++++++++++|-----| TCP segment
206//! |-----------------|++++++++++++++++++++++++++++++++++++++++|-----| IPv4 packet
207//! |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| Ethernet frame
208//!
209//! |-----------------|-------------------|--------------------|-----|
210//!                        IPv4 header          IPv4 body
211//!                             |                   |
212//!                             +-----------+       |
213//!                                         |       |
214//!                      SerializeTarget { header, body }
215//!
216//! |-----------------|----------------------------------------|-----|
217//!    buffer prefix                 buffer body                 buffer suffix
218//! ```
219//!
220//! We then pass the `SerializeTarget` to a call to the `Ipv4PacketBuilder`'s
221//! `serialize` method, and it serializes the IPv4 header in the space provided.
222//! When the call to `serialize` returns, the `SerializeTarget` and
223//! `Ipv4PacketBuilder` have been discarded, and the buffer's body is now equal
224//! to the bytes of the IPv4 packet.
225//!
226//! ```text
227//! |-------------------------------------|++++++++++++++++++++|-----| TCP segment
228//! |-----------------|++++++++++++++++++++++++++++++++++++++++|-----| IPv4 packet
229//! |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| Ethernet frame
230//!
231//! |-----------------|----------------------------------------|-----|
232//!                                  IPv4 packet
233//!
234//! |-----------------|----------------------------------------|-----|
235//!    buffer prefix                 buffer body                 buffer suffix
236//! ```
237//!
238//! Now, we are ready to repeat the same process with the Ethernet layer of the
239//! packet.
240//!
241//! ### Constructing a buffer for serialization
242//!
243//! Now that we know how, given a buffer with a subset of a packet serialized
244//! into it, we can serialize the next layer of the packet, we need to figure
245//! out how to construct such a buffer in the first place.
246//!
247//! The primary challenge here is that we need to be able to commit to what
248//! we're going to serialize before we actually serialize it. For example,
249//! consider sending a TCP segment to the network. From the perspective of the
250//! TCP module of our code, we don't know how large the buffer needs to be
251//! because don't know what packet layers our TCP segment will be encapsulated
252//! inside of. If the IP layer decides to route our segment over an Ethernet
253//! link, then we'll need to have a buffer large enough for a TCP segment in an
254//! IPv4 packet in an Ethernet segment. If, on the other hand, the IP layer
255//! decides to route our segment through a GRE tunnel, then we'll need to have a
256//! buffer large enough for a TCP segment in an IPv4 packet in a GRE packet in
257//! an IP packet in an Ethernet segment.
258//!
259//! We accomplish this commit-before-serializing via the [`Serializer`] trait. A
260//! `Serializer` describes a packet which can be serialized in the future, but
261//! which has not yet been serialized. Unlike a `PacketBuilder`, a `Serializer`
262//! describes all layers of a packet up to a certain point. For example, a
263//! `Serializer` might describe a TCP segment, or it might describe a TCP
264//! segment in an IP packet, or it might describe a TCP segment in an IP packet
265//! in an Ethernet frame, etc.
266//!
267//! #### Constructing a `Serializer`
268//!
269//! `Serializer`s are recursive - a `Serializer` combined with a `PacketBuilder`
270//! yields a new `Serializer` which describes encapsulating the original
271//! `Serializer` in a new packet layer. For example, a `Serializer` describing a
272//! TCP segment combined with an `Ipv4PacketBuilder` yields a `Serializer` which
273//! describes a TCP segment in an IPv4 packet. Concretely, given a `Serializer`,
274//! `s`, and a `PacketBuilder`, `b`, a new `Serializer` can be constructed by
275//! calling `b.wrap_body(s)` or `s.wrap_in(b)`. These methods consume both the
276//! `Serializer` and the `PacketBuilder` by value, and returns a new
277//! `Serializer`.
278//!
279//! Note that, while `Serializer`s are passed around by value, they are only as
280//! large in memory as the `PacketBuilder`s they're constructed from, and those
281//! should, in most cases, be quite small. If size is a concern, the
282//! `PacketBuilder` trait can be implemented for a reference type (e.g.,
283//! `&Ipv4PacketBuilder`), and references passed around instead of values.
284//!
285//! #### Constructing a buffer from a `Serializer`
286//!
287//! If `Serializer`s are constructed by starting at the innermost packet layer
288//! and working outwards, adding packet layers, then in order to turn a
289//! `Serializer` into a buffer, they are consumed by starting at the outermost
290//! packet layer and working inwards.
291//!
292//! In order to construct a buffer, the [`Serializer::serialize`] method is
293//! provided. It takes a [`NestedPacketBuilder`], which describes one or more
294//! encapsulating packet layers. For example, when serializing a TCP segment in
295//! an IP packet in an Ethernet frame, the `serialize` call on the IP packet
296//! `Serializer` would be given a `NestedPacketBuilder` describing the Ethernet
297//! frame. This call would then compute a new `NestedPacketBuilder` describing
298//! the combined IP packet and Ethernet frame, and would pass this to a call to
299//! `serialize` on the TCP segment `Serializer`.
300//!
301//! When the innermost call to `serialize` is reached, it is that call's
302//! responsibility to produce a buffer which satisfies the constraints passed to
303//! it, and to initialize that buffer's body with the contents of its packet.
304//! For example, the TCP segment `Serializer` from the preceding example would
305//! need to produce a buffer with 38 bytes of prefix for the IP and Ethernet
306//! headers, and whose body was initialized to the bytes of the TCP segment.
307//!
308//! We can now see how `Serializer`s and `PacketBuilder`s compose - the buffer
309//! returned from a call to `serialize` satisfies the requirements of the
310//! `PacketBuilder::serialize` method - its body is initialized to the packet to
311//! be encapsulated, and enough prefix and suffix space exist to serialize this
312//! layer's header and footer. For example, the call to `Serializer::serialize`
313//! on the TCP segment serializer would return a buffer with 38 bytes of prefix
314//! and a body initialized to the bytes of the TCP segment. The call to
315//! `Serializer::serialize` on the IP packet would then pass this buffer to a
316//! call to `PacketBuilder::serialize` on its `Ipv4PacketBuilder`, resulting in
317//! a buffer with 18 bytes of prefix and a body initialized to the bytes of the
318//! entire IP packet. This buffer would then be suitable to return from the call
319//! to `Serializer::serialize`, allowing the Ethernet layer to continue
320//! operating on the buffer, and so on.
321//!
322//! Note in particular that, throughout this entire process of constructing
323//! `Serializer`s and `PacketBuilder`s and then consuming them, a buffer is only
324//! allocated once, and each byte of the packet is only serialized once. No
325//! temporary buffers or copying between buffers are required.
326//!
327//! #### Reusing buffers
328//!
329//! Another important property of the `Serializer` trait is that it can be
330//! implemented by buffers. Since buffers contain prefixes, bodies, and
331//! suffixes, and since the `Serializer::serialize` method consumes the
332//! `Serializer` by value and returns a buffer by value, a buffer is itself a
333//! valid `Serializer`. When `serialize` is called, so long as it already
334//! satisfies the constraints requested, it can simply return itself by value.
335//! If the constraints are not satisfied, it may need to produce a different
336//! buffer through some user-defined mechanism (see the [`BufferProvider`] trait
337//! for details).
338//!
339//! This allows existing buffers to be reused in many cases. For example,
340//! consider receiving a packet in a buffer, and then responding to that packet
341//! with a new packet. The buffer that the original packet was stored in can be
342//! used to serialize the new packet, avoiding any unnecessary allocation.
343
344#![no_std]
345
346extern crate alloc;
347
348/// Emits method impls for [`FragmentedBuffer`] which assume that the type is
349/// a contiguous buffer which implements [`AsRef`].
350macro_rules! fragmented_buffer_method_impls {
351    () => {
352        fn len(&self) -> usize {
353            self.as_ref().len()
354        }
355
356        fn with_bytes<'macro_a, R, F>(&'macro_a self, f: F) -> R
357        where
358            F: for<'macro_b> FnOnce(FragmentedBytes<'macro_b, 'macro_a>) -> R,
359        {
360            let mut bs = [AsRef::<[u8]>::as_ref(self)];
361            f(FragmentedBytes::new(&mut bs))
362        }
363
364        fn to_flattened_vec(&self) -> Vec<u8> {
365            self.as_ref().to_vec()
366        }
367    };
368}
369
370/// Emits method impls for [`FragmentedBufferMut`] which assume that the type is
371/// a contiguous buffer which implements [`AsMut`].
372macro_rules! fragmented_buffer_mut_method_impls {
373    () => {
374        fn with_bytes_mut<'macro_a, R, F>(&'macro_a mut self, f: F) -> R
375        where
376            F: for<'macro_b> FnOnce(FragmentedBytesMut<'macro_b, 'macro_a>) -> R,
377        {
378            let mut bs = [AsMut::<[u8]>::as_mut(self)];
379            f(FragmentedBytesMut::new(&mut bs))
380        }
381
382        fn zero_range<R>(&mut self, range: R)
383        where
384            R: RangeBounds<usize>,
385        {
386            let len = FragmentedBuffer::len(self);
387            let range = crate::canonicalize_range(len, &range);
388            crate::zero(&mut self.as_mut()[range.start..range.end]);
389        }
390
391        fn copy_within<R: RangeBounds<usize>>(&mut self, src: R, dest: usize) {
392            self.as_mut().copy_within(src, dest);
393        }
394    };
395}
396
397mod fragmented;
398pub mod records;
399pub mod serialize;
400mod util;
401
402pub use crate::fragmented::*;
403pub use crate::serialize::*;
404pub use crate::util::*;
405
406use alloc::vec::Vec;
407use core::ops::{Bound, Range, RangeBounds};
408use core::{cmp, mem};
409
410use zerocopy::{
411    FromBytes, FromZeros as _, Immutable, IntoBytes, KnownLayout, Ref, SplitByteSlice,
412    SplitByteSliceMut, Unaligned,
413};
414
415/// A buffer that may be fragmented in multiple parts which are discontiguous in
416/// memory.
417pub trait FragmentedBuffer {
418    /// Gets the total length, in bytes, of this `FragmentedBuffer`.
419    fn len(&self) -> usize;
420
421    /// Returns `true` if this `FragmentedBuffer` is empty.
422    fn is_empty(&self) -> bool {
423        self.len() == 0
424    }
425
426    /// Invokes a callback on a view into this buffer's contents as
427    /// [`FragmentedBytes`].
428    fn with_bytes<'a, R, F>(&'a self, f: F) -> R
429    where
430        F: for<'b> FnOnce(FragmentedBytes<'b, 'a>) -> R;
431
432    /// Returns a flattened version of this buffer, copying its contents into a
433    /// [`Vec`].
434    fn to_flattened_vec(&self) -> Vec<u8> {
435        self.with_bytes(|b| b.to_flattened_vec())
436    }
437}
438
439/// A [`FragmentedBuffer`] with mutable access to its contents.
440pub trait FragmentedBufferMut: FragmentedBuffer {
441    /// Invokes a callback on a mutable view into this buffer's contents as
442    /// [`FragmentedBytesMut`].
443    fn with_bytes_mut<'a, R, F>(&'a mut self, f: F) -> R
444    where
445        F: for<'b> FnOnce(FragmentedBytesMut<'b, 'a>) -> R;
446
447    /// Sets all bytes in `range` to zero.
448    ///
449    /// # Panics
450    ///
451    /// Panics if the provided `range` is not within the bounds of this
452    /// `FragmentedBufferMut`, or if the range is nonsensical (the end precedes
453    /// the start).
454    fn zero_range<R>(&mut self, range: R)
455    where
456        R: RangeBounds<usize>,
457    {
458        let len = self.len();
459        let range = canonicalize_range(len, &range);
460        self.with_bytes_mut(|mut b| {
461            zero_iter(b.iter_mut().skip(range.start).take(range.end - range.start))
462        })
463    }
464
465    /// Copies elements from one part of the `FragmentedBufferMut` to another
466    /// part of itself.
467    ///
468    /// `src` is the range within `self` to copy from. `dst` is the starting
469    /// index of the range within `self` to copy to, which will have the same
470    /// length as `src`. The two ranges may overlap. The ends of the two ranges
471    /// must be less than or equal to `self.len()`.
472    ///
473    /// # Panics
474    ///
475    /// Panics if either the source or destination range is out of bounds, or if
476    /// `src` is nonsensical (its end precedes its start).
477    fn copy_within<R: RangeBounds<usize>>(&mut self, src: R, dst: usize) {
478        self.with_bytes_mut(|mut b| b.copy_within(src, dst));
479    }
480
481    /// Copies all the bytes from another `FragmentedBuffer` `other` into
482    /// `self`.
483    ///
484    /// # Panics
485    ///
486    /// Panics if `self.len() != other.len()`.
487    fn copy_from<B: FragmentedBuffer>(&mut self, other: &B) {
488        self.with_bytes_mut(|dst| {
489            other.with_bytes(|src| {
490                let dst = dst.try_into_contiguous();
491                let src = src.try_into_contiguous();
492                match (dst, src) {
493                    (Ok(dst), Ok(src)) => {
494                        dst.copy_from_slice(src);
495                    }
496                    (Ok(dst), Err(src)) => {
497                        src.copy_into_slice(dst);
498                    }
499                    (Err(mut dst), Ok(src)) => {
500                        dst.copy_from_slice(src);
501                    }
502                    (Err(mut dst), Err(src)) => {
503                        dst.copy_from(&src);
504                    }
505                }
506            });
507        });
508    }
509}
510
511/// A buffer that is contiguous in memory.
512///
513/// If the implementing type is a buffer which exposes a prefix and a suffix,
514/// the [`AsRef`] implementation provides access only to the body. If [`AsMut`]
515/// is also implemented, it must provide access to the same bytes as [`AsRef`].
516pub trait ContiguousBuffer: FragmentedBuffer + AsRef<[u8]> {}
517
518/// A mutable buffer that is contiguous in memory.
519///
520/// If the implementing type is a buffer which exposes a prefix and a suffix,
521/// the [`AsMut`] implementation provides access only to the body.
522///
523/// `ContiguousBufferMut` is shorthand for `ContiguousBuffer +
524/// FragmentedBufferMut + AsMut<[u8]>`.
525pub trait ContiguousBufferMut: ContiguousBuffer + FragmentedBufferMut + AsMut<[u8]> {}
526impl<B: ContiguousBuffer + FragmentedBufferMut + AsMut<[u8]>> ContiguousBufferMut for B {}
527
528/// A buffer that can reduce its size.
529///
530/// A `ShrinkBuffer` is a buffer that can be reduced in size without the
531/// guarantee that the prefix or suffix will be retained. This is typically
532/// sufficient for parsing, but not for serialization.
533///
534/// # Notable implementations
535///
536/// `ShrinkBuffer` is implemented for byte slices - `&[u8]` and `&mut [u8]`.
537/// These types do not implement [`GrowBuffer`]; once bytes are consumed from
538/// their bodies, those bytes are discarded and cannot be recovered.
539pub trait ShrinkBuffer: FragmentedBuffer {
540    /// Shrinks the front of the body towards the end of the buffer.
541    ///
542    /// `shrink_front` consumes the `n` left-most bytes of the body, and adds
543    /// them to the prefix.
544    ///
545    /// # Panics
546    ///
547    /// Panics if `n` is larger than the body.
548    fn shrink_front(&mut self, n: usize);
549
550    /// Shrinks the buffer to be no larger than `len` bytes, consuming from the
551    /// front.
552    ///
553    /// `shrink_front_to` consumes as many of the left-most bytes of the body as
554    /// necessary to ensure that the buffer is no longer than `len` bytes. It
555    /// adds any bytes consumed to the prefix. If the body is already not longer
556    /// than `len` bytes, `shrink_front_to` does nothing.
557    fn shrink_front_to(&mut self, len: usize) {
558        let old_len = self.len();
559        let new_len = cmp::min(old_len, len);
560        self.shrink_front(old_len - new_len);
561    }
562
563    /// Shrinks the back of the body towards the beginning of the buffer.
564    ///
565    /// `shrink_back` consumes the `n` right-most bytes of the body, and adds
566    /// them to the suffix.
567    ///
568    /// # Panics
569    ///
570    /// Panics if `n` is larger than the body.
571    fn shrink_back(&mut self, n: usize);
572
573    /// Shrinks the buffer to be no larger than `len` bytes, consuming from the
574    /// back.
575    ///
576    /// `shrink_back_to` consumes as many of the right-most bytes of the body as
577    /// necessary to ensure that the buffer is no longer than `len` bytes.
578    /// It adds any bytes consumed to the suffix. If the body is already no
579    /// longer than `len` bytes, `shrink_back_to` does nothing.
580    fn shrink_back_to(&mut self, len: usize) {
581        let old_len = self.len();
582        let new_len = cmp::min(old_len, len);
583        self.shrink_back(old_len - new_len);
584    }
585
586    /// Shrinks the body.
587    ///
588    /// `shrink` shrinks the body to be equal to `range` of the previous body.
589    /// Any bytes preceding the range are added to the prefix, and any bytes
590    /// following the range are added to the suffix.
591    ///
592    /// # Panics
593    ///
594    /// Panics if `range` is out of bounds of the body, or if the range
595    /// is nonsensical (the end precedes the start).
596    fn shrink<R: RangeBounds<usize>>(&mut self, range: R) {
597        let len = self.len();
598        let range = canonicalize_range(len, &range);
599        self.shrink_front(range.start);
600        self.shrink_back(len - range.end);
601    }
602}
603
604/// A byte buffer used for parsing.
605///
606/// A `ParseBuffer` is a [`ContiguousBuffer`] that can shrink in size.
607///
608/// While a `ParseBuffer` allows the ranges covered by its prefix, body, and
609/// suffix to be modified, it only provides immutable access to their contents.
610/// For mutable access, see [`ParseBufferMut`].
611///
612/// # Notable implementations
613///
614/// `ParseBuffer` is implemented for byte slices - `&[u8]` and `&mut [u8]`.
615/// These types do not implement [`GrowBuffer`]; once bytes are consumed from
616/// their bodies, those bytes are discarded and cannot be recovered.
617pub trait ParseBuffer: ShrinkBuffer + ContiguousBuffer {
618    /// Parses a packet from the body.
619    ///
620    /// `parse` parses a packet from the body by invoking [`P::parse`] on a
621    /// [`BufferView`] into this buffer. Any bytes consumed from the
622    /// `BufferView` are also consumed from the body, and added to the prefix or
623    /// suffix. After `parse` has returned, the buffer's body will contain only
624    /// those bytes which were not consumed by the call to `P::parse`.
625    ///
626    /// See the [`BufferView`] and [`ParsablePacket`] documentation for more
627    /// details.
628    ///
629    /// [`P::parse`]: ParsablePacket::parse
630    fn parse<'a, P: ParsablePacket<&'a [u8], ()>>(&'a mut self) -> Result<P, P::Error> {
631        self.parse_with(())
632    }
633
634    /// Parses a packet with arguments.
635    ///
636    /// `parse_with` is like [`parse`], but it accepts arguments to pass to
637    /// [`P::parse`].
638    ///
639    /// [`parse`]: ParseBuffer::parse
640    /// [`P::parse`]: ParsablePacket::parse
641    fn parse_with<'a, ParseArgs, P: ParsablePacket<&'a [u8], ParseArgs>>(
642        &'a mut self,
643        args: ParseArgs,
644    ) -> Result<P, P::Error>;
645}
646
647/// A [`ParseBuffer`] which provides mutable access to its contents.
648///
649/// While a [`ParseBuffer`] allows the ranges covered by its prefix, body, and
650/// suffix to be modified, it only provides immutable access to their contents.
651/// A `ParseBufferMut`, on the other hand, provides mutable access to the
652/// contents of its prefix, body, and suffix.
653///
654/// # Notable implementations
655///
656/// `ParseBufferMut` is implemented for mutable byte slices - `&mut [u8]`.
657/// Mutable byte slices do not implement [`GrowBuffer`] or [`GrowBufferMut`];
658/// once bytes are consumed from their bodies, those bytes are discarded and
659/// cannot be recovered.
660pub trait ParseBufferMut: ParseBuffer + ContiguousBufferMut {
661    /// Parses a mutable packet from the body.
662    ///
663    /// `parse_mut` is like [`ParseBuffer::parse`], but instead of calling
664    /// [`P::parse`] on a [`BufferView`], it calls [`P::parse_mut`] on a
665    /// [`BufferViewMut`]. The effect is that the parsed packet can contain
666    /// mutable references to the buffer. This can be useful if you want to
667    /// modify parsed packets in-place.
668    ///
669    /// Depending on the implementation of [`P::parse_mut`], the contents
670    /// of the buffer may be modified during parsing.
671    ///
672    /// See the [`BufferViewMut`] and [`ParsablePacket`] documentation for more
673    /// details.
674    ///
675    /// [`P::parse`]: ParsablePacket::parse
676    /// [`P::parse_mut`]: ParsablePacket::parse_mut
677    fn parse_mut<'a, P: ParsablePacket<&'a mut [u8], ()>>(&'a mut self) -> Result<P, P::Error> {
678        self.parse_with_mut(())
679    }
680
681    /// Parses a mutable packet with arguments.
682    ///
683    /// `parse_with_mut` is like [`parse_mut`], but it accepts arguments to pass
684    /// to [`P::parse_mut`].
685    ///
686    /// [`parse_mut`]: ParseBufferMut::parse_mut
687    /// [`P::parse_mut`]: ParsablePacket::parse_mut
688    fn parse_with_mut<'a, ParseArgs, P: ParsablePacket<&'a mut [u8], ParseArgs>>(
689        &'a mut self,
690        args: ParseArgs,
691    ) -> Result<P, P::Error>;
692}
693
694/// A buffer that can grow its body by taking space from its prefix and suffix.
695///
696/// A `GrowBuffer` is a byte buffer with a prefix, a body, and a suffix. The
697/// size of the buffer is referred to as its "capacity", and the size of the
698/// body is referred to as its "length". The body of the buffer can shrink or
699/// grow as allowed by the capacity as packets are parsed or serialized.
700///
701/// A `GrowBuffer` guarantees never to discard bytes from the prefix or suffix,
702/// which is an important requirement for serialization. \[1\] For parsing, this
703/// guarantee is not needed. The subset of methods which do not require this
704/// guarantee are defined in the [`ShrinkBuffer`] trait, which does not have
705/// this requirement.
706///
707/// While a `GrowBuffer` allows the ranges covered by its prefix, body, and
708/// suffix to be modified, it only provides immutable access to their contents.
709/// For mutable access, see [`GrowBufferMut`].
710///
711/// If a type implements `GrowBuffer`, then its implementations of the methods
712/// on [`FragmentedBuffer`] provide access only to the buffer's body. In
713/// particular, [`len`] returns the body's length, [`with_bytes`] provides
714/// access to the body, and [`to_flattened_vec`] returns a copy of the body.
715///
716/// \[1\] If `GrowBuffer`s could shrink their prefix or suffix, then it would
717/// not be possible to guarantee that a call to [`undo_parse`] wouldn't panic.
718/// `undo_parse` is used when retaining previously-parsed packets for
719/// serialization, which is useful in scenarios such as packet forwarding.
720///
721/// [`len`]: FragmentedBuffer::len
722/// [`with_bytes`]: FragmentedBuffer::with_bytes
723/// [`to_flattened_vec`]: FragmentedBuffer::to_flattened_vec
724/// [`undo_parse`]: GrowBuffer::undo_parse
725pub trait GrowBuffer: FragmentedBuffer {
726    /// Gets a view into the parts of this `GrowBuffer`.
727    ///
728    /// Calls `f`, passing the prefix, body, and suffix as arguments (in that
729    /// order).
730    fn with_parts<'a, O, F>(&'a self, f: F) -> O
731    where
732        F: for<'b> FnOnce(&'a [u8], FragmentedBytes<'b, 'a>, &'a [u8]) -> O;
733
734    /// The capacity of the buffer.
735    ///
736    /// `b.capacity()` is equivalent to `b.prefix_len() + b.len() +
737    /// b.suffix_len()`.
738    fn capacity(&self) -> usize {
739        self.with_parts(|prefix, body, suffix| prefix.len() + body.len() + suffix.len())
740    }
741
742    /// The length of the prefix.
743    fn prefix_len(&self) -> usize {
744        self.with_parts(|prefix, _body, _suffix| prefix.len())
745    }
746
747    /// The length of the suffix.
748    fn suffix_len(&self) -> usize {
749        self.with_parts(|_prefix, _body, suffix| suffix.len())
750    }
751
752    /// Grows the front of the body towards Growf the buffer.
753    ///
754    /// `grow_front` consumes the right-most `n` bytes of the prefix, and adds
755    /// them to the body.
756    ///
757    /// # Panics
758    ///
759    /// Panics if `n` is larger than the prefix.
760    fn grow_front(&mut self, n: usize);
761
762    /// Grows the back of the body towards the end of the buffer.
763    ///
764    /// `grow_back` consumes the left-most `n` bytes of the suffix, and adds
765    /// them to the body.
766    ///
767    /// # Panics
768    ///
769    /// Panics if `n` is larger than the suffix.
770    fn grow_back(&mut self, n: usize);
771
772    /// Resets the body to be equal to the entire buffer.
773    ///
774    /// `reset` consumes the entire prefix and suffix, adding them to the body.
775    fn reset(&mut self) {
776        self.grow_front(self.prefix_len());
777        self.grow_back(self.suffix_len());
778    }
779
780    /// Undoes the effects of a previous parse in preparation for serialization.
781    ///
782    /// `undo_parse` undoes the effects of having previously parsed a packet by
783    /// consuming the appropriate number of bytes from the prefix and suffix.
784    /// After a call to `undo_parse`, the buffer's body will contain the bytes
785    /// of the previously-parsed packet, including any headers or footers. This
786    /// allows a previously-parsed packet to be used in serialization.
787    ///
788    /// `undo_parse` takes a [`ParseMetadata`], which can be obtained from
789    /// [`ParsablePacket::parse_metadata`].
790    ///
791    /// `undo_parse` must always be called starting with the most recently
792    /// parsed packet, followed by the second most recently parsed packet, and
793    /// so on. Otherwise, it may panic, and in any case, almost certainly won't
794    /// produce the desired buffer contents.
795    ///
796    /// # Padding
797    ///
798    /// If, during parsing, a packet encountered post-packet padding that was
799    /// discarded (see the documentation on [`ParsablePacket::parse`]), calling
800    /// `undo_parse` on the `ParseMetadata` from that packet will not undo the
801    /// effects of consuming and discarding that padding. The reason for this is
802    /// that the padding is not considered part of the packet itself (the body
803    /// it was parsed from can be thought of comprising the packet and
804    /// post-packet padding back-to-back).
805    ///
806    /// Calling `undo_parse` on the next encapsulating packet (the one whose
807    /// body contained the padding) will undo those effects.
808    ///
809    /// # Panics
810    ///
811    /// `undo_parse` may panic if called in the wrong order. See the first
812    /// section of this documentation for details.
813    fn undo_parse(&mut self, meta: ParseMetadata) {
814        if self.len() < meta.body_len {
815            // There were padding bytes which were stripped when parsing the
816            // encapsulated packet. We need to add them back in order to restore
817            // the original packet.
818            let len = self.len();
819            self.grow_back(meta.body_len - len);
820        }
821        self.grow_front(meta.header_len);
822        self.grow_back(meta.footer_len);
823    }
824}
825
826/// A [`GrowBuffer`] which provides mutable access to its contents.
827///
828/// While a [`GrowBuffer`] allows the ranges covered by its prefix, body, and
829/// suffix to be modified, it only provides immutable access to their contents.
830/// A `GrowBufferMut`, on the other hand, provides mutable access to the
831/// contents of its prefix, body, and suffix.
832pub trait GrowBufferMut: GrowBuffer + FragmentedBufferMut {
833    /// Gets a mutable view into the parts of this `GrowBufferMut`.
834    ///
835    /// Calls `f`, passing the prefix, body, and suffix as arguments (in that
836    /// order).
837    fn with_parts_mut<'a, O, F>(&'a mut self, f: F) -> O
838    where
839        F: for<'b> FnOnce(&'a mut [u8], FragmentedBytesMut<'b, 'a>, &'a mut [u8]) -> O;
840
841    /// Gets a mutable view into the entirety of this `GrowBufferMut`.
842    ///
843    /// This provides an escape to the requirement that `GrowBufferMut`'s
844    /// [`FragmentedBufferMut`] implementation only provides views into the
845    /// body.
846    ///
847    /// Implementations provide the entirety of the buffer's contents as a
848    /// single [`FragmentedBytesMut`] with the _least_ amount of fragments
849    /// possible. That is, if the prefix or suffix are contiguous slices with
850    /// the head or tail of the body, these slices are merged in the provided
851    /// argument to the callback.
852    fn with_all_contents_mut<'a, O, F>(&'a mut self, f: F) -> O
853    where
854        F: for<'b> FnOnce(FragmentedBytesMut<'b, 'a>) -> O;
855
856    /// Extends the front of the body towards the beginning of the buffer,
857    /// zeroing the new bytes.
858    ///
859    /// `grow_front_zero` calls [`GrowBuffer::grow_front`] and sets the
860    /// newly-added bytes to 0. This can be useful when serializing to ensure
861    /// that the contents of packets previously stored in the buffer are not
862    /// leaked.
863    fn grow_front_zero(&mut self, n: usize) {
864        self.grow_front(n);
865        self.zero_range(..n);
866    }
867
868    /// Extends the back of the body towards the end of the buffer, zeroing the
869    /// new bytes.
870    ///
871    /// `grow_back_zero` calls [`GrowBuffer::grow_back`] and sets the
872    /// newly-added bytes to 0. This can be useful when serializing to ensure
873    /// that the contents of packets previously stored in the buffer are not
874    /// leaked.
875    fn grow_back_zero(&mut self, n: usize) {
876        let old_len = self.len();
877        self.grow_back(n);
878        self.zero_range(old_len..);
879    }
880
881    /// Resets the body to be equal to the entire buffer, zeroing the new bytes.
882    ///
883    /// Like [`GrowBuffer::reset`], `reset_zero` consumes the entire prefix and
884    /// suffix, adding them to the body. It sets these bytes to 0. This can be
885    /// useful when serializing to ensure that the contents of packets
886    /// previously stored in the buffer are not leaked.
887    fn reset_zero(&mut self) {
888        self.grow_front_zero(self.prefix_len());
889        self.grow_back_zero(self.suffix_len());
890    }
891
892    /// Serializes a packet in the buffer.
893    ///
894    /// *This method is usually called by this crate during the serialization of
895    /// a [`Serializer`], not directly by the user.*
896    ///
897    /// `serialize` serializes the packet described by `builder` into the
898    /// buffer. The body of the buffer is used as the body of the packet, and
899    /// the prefix and suffix of the buffer are used to serialize the packet's
900    /// header and footer.
901    ///
902    /// If `builder` has a minimum body size which is larger than the current
903    /// body, then `serialize` first grows the body to the right (towards the
904    /// end of the buffer) with padding bytes in order to meet the minimum body
905    /// size. This is transparent to the `builder` - it always just sees a body
906    /// which meets the minimum body size requirement.
907    ///
908    /// The added padding is zeroed in order to avoid leaking the contents of
909    /// packets previously stored in the buffer.
910    ///
911    /// # Panics
912    ///
913    /// `serialize` panics if there are not enough prefix or suffix bytes to
914    /// serialize the packet. In particular, `b.serialize(builder)` with `c =
915    /// builder.constraints()` panics if either of the following hold:
916    /// - `b.prefix_len() < c.header_len()`
917    /// - `b.len() + b.suffix_len() < c.min_body_bytes() + c.footer_len()`
918    #[doc(hidden)]
919    fn serialize<C: SerializationContext, B: PacketBuilder<C>>(
920        &mut self,
921        context: &mut C,
922        builder: B,
923    ) {
924        let c = builder.constraints();
925        if self.len() < c.min_body_len() {
926            // The body isn't large enough to satisfy the minimum body length
927            // requirement, so we add padding.
928
929            // SECURITY: Use _zero to ensure we zero padding bytes to prevent
930            // leaking information from packets previously stored in this
931            // buffer.
932            let len = self.len();
933            self.grow_back_zero(c.min_body_len() - len);
934        }
935
936        // These aren't necessary for correctness (grow_xxx_zero will panic
937        // under the same conditions that these assertions will fail), but they
938        // provide nicer error messages for debugging.
939        debug_assert!(
940            self.prefix_len() >= c.header_len(),
941            "prefix ({} bytes) too small to serialize header ({} bytes)",
942            self.prefix_len(),
943            c.header_len()
944        );
945        debug_assert!(
946            self.suffix_len() >= c.footer_len(),
947            "suffix ({} bytes) too small to serialize footer ({} bytes)",
948            self.suffix_len(),
949            c.footer_len()
950        );
951
952        self.with_parts_mut(|prefix, body, suffix| {
953            let header = prefix.len() - c.header_len();
954            let header = &mut prefix[header..];
955            let footer = &mut suffix[..c.footer_len()];
956            // SECURITY: zero here is technically unnecessary since it's
957            // PacketBuilder::serialize's responsibility to zero/initialize the
958            // header and footer, but we do it anyway to hedge against
959            // non-compliant PacketBuilder::serialize implementations. If this
960            // becomes a performance issue, we can revisit it, but the optimizer
961            // will probably take care of it for us.
962            zero(header);
963            zero(footer);
964            builder.serialize(context, &mut SerializeTarget { header, footer }, body);
965        });
966
967        self.grow_front(c.header_len());
968        self.grow_back(c.footer_len());
969    }
970}
971
972/// A byte buffer that can be serialized into multiple times.
973///
974/// `ReusableBuffer` is a shorthand for `GrowBufferMut + ShrinkBuffer`. A
975/// `ReusableBuffer` can be serialized into multiple times - the
976/// [`ShrinkBuffer`] implementation allows the buffer's capacity to be reclaimed
977/// for a new serialization pass.
978pub trait ReusableBuffer: GrowBufferMut + ShrinkBuffer {}
979impl<B> ReusableBuffer for B where B: GrowBufferMut + ShrinkBuffer {}
980
981/// A byte buffer used for parsing that can grow back to its original size.
982///
983/// `Buffer` owns its backing memory and so implies `GrowBuffer + ParseBuffer`.
984/// A `Buffer` can be used for parsing (via [`ParseBuffer`]) and then grow back
985/// to its original size (via [`GrowBuffer`]). Since it owns the backing memory,
986/// it also provides the ability to provide both a parsed and un-parsed view
987/// into a packet via [`Buffer::parse_with_view`].
988pub trait Buffer: GrowBuffer + ParseBuffer {
989    /// Like [`ParseBuffer::parse_with`] but additionally provides an
990    /// un-structured view into the parsed data on successful parsing.
991    fn parse_with_view<'a, ParseArgs, P: ParsablePacket<&'a [u8], ParseArgs>>(
992        &'a mut self,
993        args: ParseArgs,
994    ) -> Result<(P, &'a [u8]), P::Error>;
995}
996
997/// A byte buffer used for parsing and serialization.
998///
999/// `BufferMut` is a shorthand for `GrowBufferMut + ParseBufferMut`. A
1000/// `BufferMut` can be used for parsing (via [`ParseBufferMut`]) and
1001/// serialization (via [`GrowBufferMut`]).
1002pub trait BufferMut: GrowBufferMut + ParseBufferMut + Buffer {}
1003impl<B> BufferMut for B where B: GrowBufferMut + ParseBufferMut + Buffer {}
1004
1005/// An empty buffer.
1006///
1007/// An `EmptyBuf` is a buffer with 0 bytes of length or capacity. It implements
1008/// all of the buffer traits (`XxxBuffer` and `XxxBufferMut`) and both buffer
1009/// view traits ([`BufferView`] and [`BufferViewMut`]).
1010#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1011pub struct EmptyBuf;
1012
1013impl AsRef<[u8]> for EmptyBuf {
1014    #[inline]
1015    fn as_ref(&self) -> &[u8] {
1016        &[]
1017    }
1018}
1019impl AsMut<[u8]> for EmptyBuf {
1020    #[inline]
1021    fn as_mut(&mut self) -> &mut [u8] {
1022        &mut []
1023    }
1024}
1025impl FragmentedBuffer for EmptyBuf {
1026    fragmented_buffer_method_impls!();
1027}
1028impl FragmentedBufferMut for EmptyBuf {
1029    fragmented_buffer_mut_method_impls!();
1030}
1031impl ContiguousBuffer for EmptyBuf {}
1032impl ShrinkBuffer for EmptyBuf {
1033    #[inline]
1034    fn shrink_front(&mut self, n: usize) {
1035        assert_eq!(n, 0);
1036    }
1037    #[inline]
1038    fn shrink_back(&mut self, n: usize) {
1039        assert_eq!(n, 0);
1040    }
1041}
1042impl ParseBuffer for EmptyBuf {
1043    #[inline]
1044    fn parse_with<'a, ParseArgs, P: ParsablePacket<&'a [u8], ParseArgs>>(
1045        &'a mut self,
1046        args: ParseArgs,
1047    ) -> Result<P, P::Error> {
1048        P::parse(EmptyBuf, args)
1049    }
1050}
1051impl ParseBufferMut for EmptyBuf {
1052    #[inline]
1053    fn parse_with_mut<'a, ParseArgs, P: ParsablePacket<&'a mut [u8], ParseArgs>>(
1054        &'a mut self,
1055        args: ParseArgs,
1056    ) -> Result<P, P::Error> {
1057        P::parse_mut(EmptyBuf, args)
1058    }
1059}
1060impl GrowBuffer for EmptyBuf {
1061    #[inline]
1062    fn with_parts<'a, O, F>(&'a self, f: F) -> O
1063    where
1064        F: for<'b> FnOnce(&'a [u8], FragmentedBytes<'b, 'a>, &'a [u8]) -> O,
1065    {
1066        f(&[], FragmentedBytes::new_empty(), &[])
1067    }
1068    #[inline]
1069    fn grow_front(&mut self, n: usize) {
1070        assert_eq!(n, 0);
1071    }
1072    #[inline]
1073    fn grow_back(&mut self, n: usize) {
1074        assert_eq!(n, 0);
1075    }
1076}
1077impl GrowBufferMut for EmptyBuf {
1078    fn with_parts_mut<'a, O, F>(&'a mut self, f: F) -> O
1079    where
1080        F: for<'b> FnOnce(&'a mut [u8], FragmentedBytesMut<'b, 'a>, &'a mut [u8]) -> O,
1081    {
1082        f(&mut [], FragmentedBytesMut::new_empty(), &mut [])
1083    }
1084
1085    fn with_all_contents_mut<'a, O, F>(&'a mut self, f: F) -> O
1086    where
1087        F: for<'b> FnOnce(FragmentedBytesMut<'b, 'a>) -> O,
1088    {
1089        f(FragmentedBytesMut::new_empty())
1090    }
1091}
1092impl<'a> BufferView<&'a [u8]> for EmptyBuf {
1093    #[inline]
1094    fn len(&self) -> usize {
1095        0
1096    }
1097    #[inline]
1098    fn take_front(&mut self, n: usize) -> Option<&'a [u8]> {
1099        if n > 0 {
1100            return None;
1101        }
1102        Some(&[])
1103    }
1104    #[inline]
1105    fn take_back(&mut self, n: usize) -> Option<&'a [u8]> {
1106        if n > 0 {
1107            return None;
1108        }
1109        Some(&[])
1110    }
1111    #[inline]
1112    fn into_rest(self) -> &'a [u8] {
1113        &[]
1114    }
1115}
1116impl<'a> BufferView<&'a mut [u8]> for EmptyBuf {
1117    #[inline]
1118    fn len(&self) -> usize {
1119        0
1120    }
1121    #[inline]
1122    fn take_front(&mut self, n: usize) -> Option<&'a mut [u8]> {
1123        if n > 0 {
1124            return None;
1125        }
1126        Some(&mut [])
1127    }
1128    #[inline]
1129    fn take_back(&mut self, n: usize) -> Option<&'a mut [u8]> {
1130        if n > 0 {
1131            return None;
1132        }
1133        Some(&mut [])
1134    }
1135    #[inline]
1136    fn into_rest(self) -> &'a mut [u8] {
1137        &mut []
1138    }
1139}
1140impl<'a> BufferViewMut<&'a mut [u8]> for EmptyBuf {}
1141impl Buffer for EmptyBuf {
1142    fn parse_with_view<'a, ParseArgs, P: ParsablePacket<&'a [u8], ParseArgs>>(
1143        &'a mut self,
1144        args: ParseArgs,
1145    ) -> Result<(P, &'a [u8]), P::Error> {
1146        self.parse_with(args).map(|r| (r, [].as_slice()))
1147    }
1148}
1149
1150impl FragmentedBuffer for ! {
1151    fn len(&self) -> usize {
1152        match *self {}
1153    }
1154
1155    fn with_bytes<'a, R, F>(&'a self, _f: F) -> R
1156    where
1157        F: for<'b> FnOnce(FragmentedBytes<'b, 'a>) -> R,
1158    {
1159        match *self {}
1160    }
1161}
1162impl FragmentedBufferMut for ! {
1163    fn with_bytes_mut<'a, R, F>(&'a mut self, _f: F) -> R
1164    where
1165        F: for<'b> FnOnce(FragmentedBytesMut<'b, 'a>) -> R,
1166    {
1167        match *self {}
1168    }
1169}
1170impl ShrinkBuffer for ! {
1171    fn shrink_front(&mut self, _n: usize) {}
1172    fn shrink_back(&mut self, _n: usize) {}
1173}
1174impl GrowBuffer for ! {
1175    fn with_parts<'a, O, F>(&'a self, _f: F) -> O
1176    where
1177        F: for<'b> FnOnce(&'a [u8], FragmentedBytes<'b, 'a>, &'a [u8]) -> O,
1178    {
1179        match *self {}
1180    }
1181    fn grow_front(&mut self, _n: usize) {}
1182    fn grow_back(&mut self, _n: usize) {}
1183}
1184impl GrowBufferMut for ! {
1185    fn with_parts_mut<'a, O, F>(&'a mut self, _f: F) -> O
1186    where
1187        F: for<'b> FnOnce(&'a mut [u8], FragmentedBytesMut<'b, 'a>, &'a mut [u8]) -> O,
1188    {
1189        match *self {}
1190    }
1191
1192    fn with_all_contents_mut<'a, O, F>(&'a mut self, _f: F) -> O
1193    where
1194        F: for<'b> FnOnce(FragmentedBytesMut<'b, 'a>) -> O,
1195    {
1196        match *self {}
1197    }
1198}
1199
1200/// A view into a [`ShrinkBuffer`].
1201///
1202/// A `BufferView` borrows a `ShrinkBuffer`, and provides methods to consume
1203/// bytes from the buffer's body. It is primarily intended to be used for
1204/// parsing, although it provides methods which are useful for serialization as
1205/// well.
1206///
1207/// A `BufferView` only provides immutable access to the contents of the buffer.
1208/// For mutable access, see [`BufferViewMut`].
1209///
1210/// # Notable implementations
1211///
1212/// `BufferView` is implemented for mutable references to byte slices (`&mut
1213/// &[u8]` and `&mut &mut [u8]`).
1214pub trait BufferView<B: SplitByteSlice>: Sized + AsRef<[u8]> {
1215    /// The length of the buffer's body.
1216    fn len(&self) -> usize {
1217        self.as_ref().len()
1218    }
1219
1220    /// Is the buffer's body empty?
1221    fn is_empty(&self) -> bool {
1222        self.len() == 0
1223    }
1224
1225    /// Takes `n` bytes from the front of the buffer's body.
1226    ///
1227    /// `take_front` consumes `n` bytes from the front of the buffer's body.
1228    /// After a successful call to `take_front(n)`, the body is `n` bytes
1229    /// shorter and, if `Self: GrowBuffer`, the prefix is `n` bytes longer. If
1230    /// the body is not at least `n` bytes in length, `take_front` returns
1231    /// `None`.
1232    fn take_front(&mut self, n: usize) -> Option<B>;
1233
1234    /// Takes `n` bytes from the back of the buffer's body.
1235    ///
1236    /// `take_back` consumes `n` bytes from the back of the buffer's body. After
1237    /// a successful call to `take_back(n)`, the body is `n` bytes shorter and,
1238    /// if `Self: GrowBuffer`, the suffix is `n` bytes longer. If the body is
1239    /// not at least `n` bytes in length, `take_back` returns `None`.
1240    fn take_back(&mut self, n: usize) -> Option<B>;
1241
1242    /// Takes the rest of the buffer's body from the front.
1243    ///
1244    /// `take_rest_front` consumes the rest of the bytes from the buffer's body.
1245    /// After a call to `take_rest_front`, the body is empty and, if `Self:
1246    /// GrowBuffer`, the bytes which were previously in the body are now in the
1247    /// prefix.
1248    fn take_rest_front(&mut self) -> B {
1249        let len = self.len();
1250        self.take_front(len).unwrap()
1251    }
1252
1253    /// Takes the rest of the buffer's body from the back.
1254    ///
1255    /// `take_rest_back` consumes the rest of the bytes from the buffer's body.
1256    /// After a call to `take_rest_back`, the body is empty and, if `Self:
1257    /// GrowBuffer`, the bytes which were previously in the body are now in the
1258    /// suffix.
1259    fn take_rest_back(&mut self) -> B {
1260        let len = self.len();
1261        self.take_back(len).unwrap()
1262    }
1263
1264    /// Takes a single byte of the buffer's body from the front.
1265    ///
1266    /// `take_byte_front` consumes a single byte from the from of the buffer's
1267    /// body. It's equivalent to calling `take_front(1)` and copying out the
1268    /// single byte on successful return.
1269    fn take_byte_front(&mut self) -> Option<u8> {
1270        self.take_front(1).map(|x| x[0])
1271    }
1272
1273    /// Takes a single byte of the buffer's body from the back.
1274    ///
1275    /// `take_byte_back` consumes a single byte from the fron of the buffer's
1276    /// body. It's equivalent to calling `take_back(1)` and copying out the
1277    /// single byte on successful return.
1278    fn take_byte_back(&mut self) -> Option<u8> {
1279        self.take_back(1).map(|x| x[0])
1280    }
1281
1282    /// Converts this view into a reference to the buffer's body.
1283    ///
1284    /// `into_rest` consumes this `BufferView` by value, and returns a reference
1285    /// to the buffer's body. Unlike `take_rest`, the body is not consumed - it
1286    /// is left unchanged.
1287    fn into_rest(self) -> B;
1288
1289    /// Peeks at an object at the front of the buffer's body.
1290    ///
1291    /// `peek_obj_front` peeks at `size_of::<T>()` bytes at the front of the
1292    /// buffer's body, and interprets them as a `T`. Unlike `take_obj_front`,
1293    /// `peek_obj_front` does not modify the body. If the body is not at least
1294    /// `size_of::<T>()` bytes in length, `peek_obj_front` returns `None`.
1295    fn peek_obj_front<T>(&self) -> Option<&T>
1296    where
1297        T: FromBytes + KnownLayout + Immutable + Unaligned,
1298    {
1299        Some(Ref::into_ref(Ref::<_, T>::from_prefix(self.as_ref()).ok()?.0))
1300    }
1301
1302    /// Takes an object from the front of the buffer's body.
1303    ///
1304    /// `take_obj_front` consumes `size_of::<T>()` bytes from the front of the
1305    /// buffer's body, and interprets them as a `T`. After a successful call to
1306    /// `take_obj_front::<T>()`, the body is `size_of::<T>()` bytes shorter and,
1307    /// if `Self: GrowBuffer`, the prefix is `size_of::<T>()` bytes longer. If
1308    /// the body is not at least `size_of::<T>()` bytes in length,
1309    /// `take_obj_front` returns `None`.
1310    fn take_obj_front<T>(&mut self) -> Option<Ref<B, T>>
1311    where
1312        T: KnownLayout + Immutable + Unaligned,
1313    {
1314        let bytes = self.take_front(mem::size_of::<T>())?;
1315        // unaligned_from_bytes only returns None if there aren't enough bytes
1316        Some(Ref::from_bytes(bytes).unwrap())
1317    }
1318
1319    /// Takes an owned copy of an object from the front of the buffer's body.
1320    ///
1321    /// `take_owned_obj_front` is like `take_obj_front`, but returns an owned
1322    /// `T` rather than a `Ref<B, T>`. This may be more performant in situations
1323    /// where `T` is smaller than `Ref<B, T>`.
1324    fn take_owned_obj_front<T>(&mut self) -> Option<T>
1325    where
1326        T: FromBytes,
1327    {
1328        let bytes = self.take_front(mem::size_of::<T>())?;
1329        // `read_from_bytes` only returns None if there aren't enough bytes.
1330        Some(T::read_from_bytes(bytes.as_ref()).unwrap())
1331    }
1332
1333    /// Takes a slice of objects from the front of the buffer's body.
1334    ///
1335    /// `take_slice_front` consumes `n * size_of::<T>()` bytes from the front of
1336    /// the buffer's body, and interprets them as a `[T]` with `n` elements.
1337    /// After a successful call to `take_slice_front::<T>()`, the body is `n *
1338    /// size_of::<T>()` bytes shorter and, if `Self: GrowBuffer`, the prefix is
1339    /// `n * size_of::<T>()` bytes longer. If the body is not at least `n *
1340    /// size_of::<T>()` bytes in length, `take_slice_front` returns `None`.
1341    ///
1342    /// # Panics
1343    ///
1344    /// Panics if `T` is a zero-sized type.
1345    fn take_slice_front<T>(&mut self, n: usize) -> Option<Ref<B, [T]>>
1346    where
1347        T: Immutable + Unaligned,
1348    {
1349        let bytes = self.take_front(n * mem::size_of::<T>())?;
1350        // `unaligned_from_bytes` will return `None` only if `bytes.len()` is
1351        // not a multiple of `mem::size_of::<T>()`.
1352        Some(Ref::from_bytes(bytes).unwrap())
1353    }
1354
1355    /// Peeks at an object at the back of the buffer's body.
1356    ///
1357    /// `peek_obj_back` peeks at `size_of::<T>()` bytes at the back of the
1358    /// buffer's body, and interprets them as a `T`. Unlike `take_obj_back`,
1359    /// `peek_obj_back` does not modify the body. If the body is not at least
1360    /// `size_of::<T>()` bytes in length, `peek_obj_back` returns `None`.
1361    fn peek_obj_back<T>(&mut self) -> Option<&T>
1362    where
1363        T: FromBytes + KnownLayout + Immutable + Unaligned,
1364    {
1365        Some(Ref::into_ref(Ref::<_, T>::from_suffix((&*self).as_ref()).ok()?.1))
1366    }
1367
1368    /// Takes an object from the back of the buffer's body.
1369    ///
1370    /// `take_obj_back` consumes `size_of::<T>()` bytes from the back of the
1371    /// buffer's body, and interprets them as a `T`. After a successful call to
1372    /// `take_obj_back::<T>()`, the body is `size_of::<T>()` bytes shorter and,
1373    /// if `Self: GrowBuffer`, the suffix is `size_of::<T>()` bytes longer. If
1374    /// the body is not at least `size_of::<T>()` bytes in length,
1375    /// `take_obj_back` returns `None`.
1376    fn take_obj_back<T>(&mut self) -> Option<Ref<B, T>>
1377    where
1378        T: Immutable + KnownLayout + Unaligned,
1379    {
1380        let bytes = self.take_back(mem::size_of::<T>())?;
1381        // unaligned_from_bytes only returns None if there aren't enough bytes
1382        Some(Ref::from_bytes(bytes).unwrap())
1383    }
1384
1385    /// Takes an owned copy of an object from the back of the buffer's body.
1386    ///
1387    /// `take_owned_obj_back` is like `take_obj_back`, but returns an owned
1388    /// `T` rather than a `Ref<B, T>`. This may be more performant in situations
1389    /// where `T` is smaller than `Ref<B, T>`.
1390    fn take_owned_obj_back<T>(&mut self) -> Option<T>
1391    where
1392        T: FromBytes,
1393    {
1394        let bytes = self.take_back(mem::size_of::<T>())?;
1395        // `read_from_bytes` only returns None if there aren't enough bytes.
1396        Some(T::read_from_bytes(bytes.as_ref()).unwrap())
1397    }
1398
1399    /// Takes a slice of objects from the back of the buffer's body.
1400    ///
1401    /// `take_slice_back` consumes `n * size_of::<T>()` bytes from the back of
1402    /// the buffer's body, and interprets them as a `[T]` with `n` elements.
1403    /// After a successful call to `take_slice_back::<T>()`, the body is `n *
1404    /// size_of::<T>()` bytes shorter and, if `Self: GrowBuffer`, the suffix is
1405    /// `n * size_of::<T>()` bytes longer. If the body is not at least `n *
1406    /// size_of::<T>()` bytes in length, `take_slice_back` returns `None`.
1407    ///
1408    /// # Panics
1409    ///
1410    /// Panics if `T` is a zero-sized type.
1411    fn take_slice_back<T>(&mut self, n: usize) -> Option<Ref<B, [T]>>
1412    where
1413        T: Immutable + Unaligned,
1414    {
1415        let bytes = self.take_back(n * mem::size_of::<T>())?;
1416        // `unaligned_from_bytes` will return `None` only if `bytes.len()` is
1417        // not a multiple of `mem::size_of::<T>()`.
1418        Some(Ref::from_bytes(bytes).unwrap())
1419    }
1420}
1421
1422/// A mutable view into a `Buffer`.
1423///
1424/// A `BufferViewMut` is a [`BufferView`] which provides mutable access to the
1425/// contents of the buffer.
1426///
1427/// # Notable implementations
1428///
1429/// `BufferViewMut` is implemented for `&mut &mut [u8]`.
1430pub trait BufferViewMut<B: SplitByteSliceMut>: BufferView<B> + AsMut<[u8]> {
1431    /// Takes `n` bytes from the front of the buffer's body and zeroes them.
1432    ///
1433    /// `take_front_zero` is like [`BufferView::take_front`], except that it
1434    /// zeroes the bytes before returning them. This can be useful when
1435    /// serializing to ensure that the contents of packets previously stored in
1436    /// the buffer are not leaked.
1437    fn take_front_zero(&mut self, n: usize) -> Option<B> {
1438        self.take_front(n).map(|mut buf| {
1439            zero(buf.deref_mut());
1440            buf
1441        })
1442    }
1443
1444    /// Takes `n` bytes from the back of the buffer's body and zeroes them.
1445    ///
1446    /// `take_back_zero` is like [`BufferView::take_back`], except that it
1447    /// zeroes the bytes before returning them. This can be useful when
1448    /// serializing to ensure that the contents of packets previously stored in
1449    /// the buffer are not leaked.
1450    fn take_back_zero(&mut self, n: usize) -> Option<B> {
1451        self.take_back(n).map(|mut buf| {
1452            zero(buf.deref_mut());
1453            buf
1454        })
1455    }
1456
1457    /// Takes the rest of the buffer's body from the front and zeroes it.
1458    ///
1459    /// `take_rest_front_zero` is like [`BufferView::take_rest_front`], except
1460    /// that it zeroes the bytes before returning them. This can be useful when
1461    /// serializing to ensure that the contents of packets previously stored in
1462    /// the buffer are not leaked.
1463    fn take_rest_front_zero(mut self) -> B {
1464        let len = self.len();
1465        self.take_front_zero(len).unwrap()
1466    }
1467
1468    /// Takes the rest of the buffer's body from the back and zeroes it.
1469    ///
1470    /// `take_rest_back_zero` is like [`BufferView::take_rest_back`], except
1471    /// that it zeroes the bytes before returning them. This can be useful when
1472    /// serializing to ensure that the contents of packets previously stored in
1473    /// the buffer are not leaked.
1474    fn take_rest_back_zero(mut self) -> B {
1475        let len = self.len();
1476        self.take_front_zero(len).unwrap()
1477    }
1478
1479    /// Converts this view into a reference to the buffer's body, and zeroes it.
1480    ///
1481    /// `into_rest_zero` is like [`BufferView::into_rest`], except that it
1482    /// zeroes the bytes before returning them. This can be useful when
1483    /// serializing to ensure that the contents of packets previously stored in
1484    /// the buffer are not leaked.
1485    fn into_rest_zero(self) -> B {
1486        let mut bytes = self.into_rest();
1487        zero(&mut bytes);
1488        bytes
1489    }
1490
1491    /// Takes an object from the front of the buffer's body and zeroes it.
1492    ///
1493    /// `take_obj_front_zero` is like [`BufferView::take_obj_front`], except
1494    /// that it zeroes the bytes before converting them to a `T`. This can be
1495    /// useful when serializing to ensure that the contents of packets
1496    /// previously stored in the buffer are not leaked.
1497    fn take_obj_front_zero<T>(&mut self) -> Option<Ref<B, T>>
1498    where
1499        T: KnownLayout + Immutable + Unaligned,
1500    {
1501        let bytes = self.take_front(mem::size_of::<T>())?;
1502        // unaligned_from_bytes only returns None if there aren't enough bytes
1503        let mut obj: Ref<_, _> = Ref::from_bytes(bytes).unwrap();
1504        Ref::bytes_mut(&mut obj).zero();
1505        Some(obj)
1506    }
1507
1508    /// Takes an object from the back of the buffer's body and zeroes it.
1509    ///
1510    /// `take_obj_back_zero` is like [`BufferView::take_obj_back`], except that
1511    /// it zeroes the bytes before converting them to a `T`. This can be useful
1512    /// when serializing to ensure that the contents of packets previously
1513    /// stored in the buffer are not leaked.
1514    fn take_obj_back_zero<T>(&mut self) -> Option<Ref<B, T>>
1515    where
1516        T: KnownLayout + Immutable + Unaligned,
1517    {
1518        let bytes = self.take_back(mem::size_of::<T>())?;
1519        // unaligned_from_bytes only returns None if there aren't enough bytes
1520        let mut obj: Ref<_, _> = Ref::from_bytes(bytes).unwrap();
1521        Ref::bytes_mut(&mut obj).zero();
1522        Some(obj)
1523    }
1524
1525    /// Writes an object to the front of the buffer's body, consuming the bytes.
1526    ///
1527    /// `write_obj_front` consumes `size_of_val(obj)` bytes from the front of
1528    /// the buffer's body, and overwrites them with `obj`. After a successful
1529    /// call to `write_obj_front(obj)`, the body is `size_of_val(obj)` bytes
1530    /// shorter and, if `Self: GrowBuffer`, the prefix is `size_of_val(obj)`
1531    /// bytes longer. If the body is not at least `size_of_val(obj)` bytes in
1532    /// length, `write_obj_front` returns `None`.
1533    fn write_obj_front<T>(&mut self, obj: &T) -> Option<()>
1534    where
1535        T: ?Sized + IntoBytes + Immutable,
1536    {
1537        let mut bytes = self.take_front(mem::size_of_val(obj))?;
1538        bytes.copy_from_slice(obj.as_bytes());
1539        Some(())
1540    }
1541
1542    /// Writes an object to the back of the buffer's body, consuming the bytes.
1543    ///
1544    /// `write_obj_back` consumes `size_of_val(obj)` bytes from the back of the
1545    /// buffer's body, and overwrites them with `obj`. After a successful call
1546    /// to `write_obj_back(obj)`, the body is `size_of_val(obj)` bytes shorter
1547    /// and, if `Self: GrowBuffer`, the suffix is `size_of_val(obj)` bytes
1548    /// longer. If the body is not at least `size_of_val(obj)` bytes in length,
1549    /// `write_obj_back` returns `None`.
1550    fn write_obj_back<T>(&mut self, obj: &T) -> Option<()>
1551    where
1552        T: ?Sized + IntoBytes + Immutable,
1553    {
1554        let mut bytes = self.take_back(mem::size_of_val(obj))?;
1555        bytes.copy_from_slice(obj.as_bytes());
1556        Some(())
1557    }
1558
1559    /// Writes specified `bytes` to the front of the buffer.
1560    ///
1561    /// If `bytes` is larger than `self` then only bytes that fit in `self` are
1562    /// written. Returns the number of bytes actually written to the buffer.
1563    fn write_bytes_front_allow_partial(&mut self, bytes: &[u8]) -> usize {
1564        let len = bytes.len().min(self.len());
1565        self.take_front(len).unwrap().copy_from_slice(&bytes[..len]);
1566        len
1567    }
1568}
1569
1570// NOTE on undo_parse algorithm: It's important that ParseMetadata only describe
1571// the packet itself, and not any padding. This is because the user might call
1572// undo_parse on a packet only once, and then serialize that packet inside of
1573// another packet with a lower minimum body length requirement than the one it
1574// was encapsulated in during parsing. In this case, if we were to include
1575// padding, we would spuriously serialize an unnecessarily large body. Omitting
1576// the padding is required for this reason. It is acceptable because, using the
1577// body_len field of the encapsulating packet's ParseMetadata, it is possible
1578// for undo_parse to reconstruct how many padding bytes there were if it needs
1579// to.
1580//
1581// undo_parse also needs to differentiate between bytes which were consumed from
1582// the beginning and end of the buffer. For normal packets this is easy -
1583// headers are consumed from the beginning, and footers from the end. For inner
1584// packets, which do not have a header/footer distinction (at least from the
1585// perspective of this crate), we arbitrarily decide that all bytes are consumed
1586// from the beginning. So long as ParsablePacket implementations obey this
1587// requirement, undo_parse will work properly. In order to support this,
1588// ParseMetadata::from_inner_packet constructs a ParseMetadata in which the only
1589// non-zero field is header_len.
1590
1591/// Metadata about a previously-parsed packet used to undo its parsing.
1592///
1593/// See [`GrowBuffer::undo_parse`] for more details.
1594#[derive(Copy, Clone, Debug, PartialEq)]
1595pub struct ParseMetadata {
1596    header_len: usize,
1597    body_len: usize,
1598    footer_len: usize,
1599}
1600
1601impl ParseMetadata {
1602    /// Constructs a new `ParseMetadata` from information about a packet.
1603    pub fn from_packet(header_len: usize, body_len: usize, footer_len: usize) -> ParseMetadata {
1604        ParseMetadata { header_len, body_len, footer_len }
1605    }
1606
1607    /// Constructs a new `ParseMetadata` from information about an inner packet.
1608    ///
1609    /// Since inner packets do not have a header/body/footer distinction (at
1610    /// least from the perspective of the utilities in this crate), we
1611    /// arbitrarily produce a `ParseMetadata` with a header length and no body
1612    /// or footer lengths. Thus, `from_inner_packet(len)` is equivalent to
1613    /// `from_packet(len, 0, 0)`.
1614    pub fn from_inner_packet(len: usize) -> ParseMetadata {
1615        ParseMetadata { header_len: len, body_len: 0, footer_len: 0 }
1616    }
1617
1618    /// Gets the header length.
1619    ///
1620    /// `header_len` returns the length of the header of the packet described by
1621    /// this `ParseMetadata`.
1622    pub fn header_len(&self) -> usize {
1623        self.header_len
1624    }
1625
1626    /// Gets the body length.
1627    ///
1628    /// `body_len` returns the length of the body of the packet described by
1629    /// this `ParseMetadata`.
1630    pub fn body_len(&self) -> usize {
1631        self.body_len
1632    }
1633
1634    /// Gets the footer length.
1635    ///
1636    /// `footer_len` returns the length of the footer of the packet described by
1637    /// this `ParseMetadata`.
1638    pub fn footer_len(&self) -> usize {
1639        self.footer_len
1640    }
1641}
1642
1643/// An empty packet parsing context.
1644#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
1645pub struct NoOpParsingContext;
1646
1647/// A packet which can be parsed from a buffer.
1648///
1649/// A `ParsablePacket` is a packet which can be parsed from the body of a
1650/// buffer. For performance reasons, it is recommended that as much of the
1651/// packet object as possible be stored as references into the body in order to
1652/// avoid copying.
1653pub trait ParsablePacket<B: SplitByteSlice, ParseArgs>: Sized {
1654    /// The type of errors returned from [`parse`] and [`parse_mut`].
1655    ///
1656    /// [`parse`]: ParsablePacket::parse
1657    /// [`parse_mut`]: ParsablePacket::parse_mut
1658    type Error;
1659
1660    /// Parses a packet from a buffer.
1661    ///
1662    /// Given a view into a buffer, `parse` parses a packet by consuming bytes
1663    /// from the buffer's body. This works slightly differently for normal
1664    /// packets and inner packets (those which do not contain other packets).
1665    ///
1666    /// ## Packets
1667    ///
1668    /// When parsing a packet which contains another packet, the outer packet's
1669    /// header and footer should be consumed from the beginning and end of the
1670    /// buffer's body respectively. The packet's body should be constructed from
1671    /// a reference to the buffer's body (i.e., [`BufferView::into_rest`]), but
1672    /// the buffer's body should not be consumed. This allows the next
1673    /// encapsulated packet to be parsed from the remaining buffer body. See the
1674    /// crate documentation for more details.
1675    ///
1676    /// ## Inner Packets
1677    ///
1678    /// When parsing packets which do not contain other packets, the entire
1679    /// packet's contents should be consumed from the beginning of the buffer's
1680    /// body. The buffer's body should be empty after `parse` has returned.
1681    ///
1682    /// # Padding
1683    ///
1684    /// There may be post-packet padding (coming after the entire packet,
1685    /// including any footer) which was added in order to satisfy the minimum
1686    /// body length requirement of an encapsulating packet. If the packet
1687    /// currently being parsed describes its own length (and thus, it's possible
1688    /// to determine whether there's any padding), `parse` is required to
1689    /// consume any post-packet padding from the buffer's suffix. If this
1690    /// invariant is not upheld, future calls to [`ParseBuffer::parse`] or
1691    /// [`GrowBuffer::undo_parse`] may behave incorrectly.
1692    ///
1693    /// Pre-packet padding is not supported; if a protocol supports such
1694    /// padding, it must be handled in a way that is transparent to this API. In
1695    /// particular, that means that the [`parse_metadata`] method must treat that
1696    /// padding as part of the packet.
1697    ///
1698    /// [`parse_metadata`]: ParsablePacket::parse_metadata
1699    fn parse<BV: BufferView<B>>(buffer: BV, args: ParseArgs) -> Result<Self, Self::Error>;
1700
1701    /// Parses a packet from a mutable buffer.
1702    ///
1703    /// `parse_mut` is like [`parse`], except that it operates on a mutable
1704    /// buffer view.
1705    ///
1706    /// [`parse`]: ParsablePacket::parse
1707    fn parse_mut<BV: BufferViewMut<B>>(buffer: BV, args: ParseArgs) -> Result<Self, Self::Error>
1708    where
1709        B: SplitByteSliceMut,
1710    {
1711        Self::parse(buffer, args)
1712    }
1713
1714    /// Gets metadata about this packet required by [`GrowBuffer::undo_parse`].
1715    ///
1716    /// The returned [`ParseMetadata`] records the number of header and footer
1717    /// bytes consumed by this packet during parsing, and the number of bytes
1718    /// left in the body (not consumed from the buffer). For packets which
1719    /// encapsulate other packets, the header length must be equal to the number
1720    /// of bytes consumed from the prefix, and the footer length must be equal
1721    /// to the number of bytes consumed from the suffix. For inner packets, use
1722    /// [`ParseMetadata::from_inner_packet`].
1723    ///
1724    /// There is one exception: if any post-packet padding was consumed from the
1725    /// suffix, this should not be included, as it is not considered part of the
1726    /// packet. For example, consider a packet with 8 bytes of footer followed
1727    /// by 8 bytes of post-packet padding. Parsing this packet would consume 16
1728    /// bytes from the suffix, but calling `parse_metadata` on the resulting
1729    /// object would return a `ParseMetadata` with only 8 bytes of footer.
1730    fn parse_metadata(&self) -> ParseMetadata;
1731}
1732
1733fn zero_iter<'a, I: Iterator<Item = &'a mut u8>>(bytes: I) {
1734    for byte in bytes {
1735        *byte = 0;
1736    }
1737}
1738
1739fn zero(bytes: &mut [u8]) {
1740    bytes.fill(0);
1741}
1742impl<'a> FragmentedBuffer for &'a [u8] {
1743    fragmented_buffer_method_impls!();
1744}
1745impl<'a> ContiguousBuffer for &'a [u8] {}
1746impl<'a> ShrinkBuffer for &'a [u8] {
1747    fn shrink_front(&mut self, n: usize) {
1748        let _: &[u8] = self.split_off(..n).unwrap();
1749    }
1750    fn shrink_back(&mut self, n: usize) {
1751        let split = <[u8]>::len(self).checked_sub(n).unwrap();
1752        let _: &[u8] = self.split_off(split..).unwrap();
1753    }
1754}
1755impl<'a> ParseBuffer for &'a [u8] {
1756    fn parse_with<'b, ParseArgs, P: ParsablePacket<&'b [u8], ParseArgs>>(
1757        &'b mut self,
1758        args: ParseArgs,
1759    ) -> Result<P, P::Error> {
1760        // A `&'b mut &'a [u8]` wrapper which implements `BufferView<&'b [u8]>`
1761        // instead of `BufferView<&'a [u8]>`. This is needed thanks to fact that
1762        // `P: ParsablePacket` has the lifetime `'b`, not `'a`.
1763        struct ByteSlice<'a, 'b>(&'b mut &'a [u8]);
1764
1765        impl<'a, 'b> AsRef<[u8]> for ByteSlice<'a, 'b> {
1766            fn as_ref(&self) -> &[u8] {
1767                &self.0
1768            }
1769        }
1770
1771        impl<'b, 'a: 'b> BufferView<&'b [u8]> for ByteSlice<'a, 'b> {
1772            fn len(&self) -> usize {
1773                <[u8]>::len(self.0)
1774            }
1775            fn take_front(&mut self, n: usize) -> Option<&'b [u8]> {
1776                self.0.split_off(..n)
1777            }
1778            fn take_back(&mut self, n: usize) -> Option<&'b [u8]> {
1779                let split = <[u8]>::len(self.0).checked_sub(n)?;
1780                self.0.split_off(split..)
1781            }
1782            fn into_rest(self) -> &'b [u8] {
1783                self.0
1784            }
1785        }
1786
1787        P::parse(ByteSlice(self), args)
1788    }
1789}
1790impl<'a> FragmentedBuffer for &'a mut [u8] {
1791    fragmented_buffer_method_impls!();
1792}
1793impl<'a> FragmentedBufferMut for &'a mut [u8] {
1794    fragmented_buffer_mut_method_impls!();
1795}
1796impl<'a> ContiguousBuffer for &'a mut [u8] {}
1797impl<'a> ShrinkBuffer for &'a mut [u8] {
1798    fn shrink_front(&mut self, n: usize) {
1799        let _: &[u8] = self.split_off_mut(..n).unwrap();
1800    }
1801    fn shrink_back(&mut self, n: usize) {
1802        let split = <[u8]>::len(self).checked_sub(n).unwrap();
1803        let _: &[u8] = self.split_off_mut(split..).unwrap();
1804    }
1805}
1806impl<'a> ParseBuffer for &'a mut [u8] {
1807    fn parse_with<'b, ParseArgs, P: ParsablePacket<&'b [u8], ParseArgs>>(
1808        &'b mut self,
1809        args: ParseArgs,
1810    ) -> Result<P, P::Error> {
1811        P::parse(self, args)
1812    }
1813}
1814
1815impl<'a> ParseBufferMut for &'a mut [u8] {
1816    fn parse_with_mut<'b, ParseArgs, P: ParsablePacket<&'b mut [u8], ParseArgs>>(
1817        &'b mut self,
1818        args: ParseArgs,
1819    ) -> Result<P, P::Error> {
1820        P::parse_mut(self, args)
1821    }
1822}
1823
1824impl<'b, 'a: 'b> BufferView<&'a [u8]> for &'b mut &'a [u8] {
1825    fn len(&self) -> usize {
1826        <[u8]>::len(self)
1827    }
1828    fn take_front(&mut self, n: usize) -> Option<&'a [u8]> {
1829        self.split_off(..n)
1830    }
1831    fn take_back(&mut self, n: usize) -> Option<&'a [u8]> {
1832        let split = <[u8]>::len(self).checked_sub(n)?;
1833        Some(self.split_off(split..).unwrap())
1834    }
1835    fn into_rest(self) -> &'a [u8] {
1836        self
1837    }
1838}
1839
1840impl<'b, 'a: 'b> BufferView<&'b [u8]> for &'b mut &'a mut [u8] {
1841    fn len(&self) -> usize {
1842        <[u8]>::len(self)
1843    }
1844    fn take_front(&mut self, n: usize) -> Option<&'b [u8]> {
1845        self.split_off_mut(..n).map(|b| &*b)
1846    }
1847    fn take_back(&mut self, n: usize) -> Option<&'b [u8]> {
1848        let split = <[u8]>::len(self).checked_sub(n)?;
1849        Some(self.split_off_mut(split..).unwrap())
1850    }
1851    fn into_rest(self) -> &'b [u8] {
1852        self
1853    }
1854}
1855
1856impl<'b, 'a: 'b> BufferView<&'b mut [u8]> for &'b mut &'a mut [u8] {
1857    fn len(&self) -> usize {
1858        <[u8]>::len(self)
1859    }
1860    fn take_front(&mut self, n: usize) -> Option<&'b mut [u8]> {
1861        self.split_off_mut(..n)
1862    }
1863    fn take_back(&mut self, n: usize) -> Option<&'b mut [u8]> {
1864        let split = <[u8]>::len(self).checked_sub(n)?;
1865        Some(self.split_off_mut(split..).unwrap())
1866    }
1867    fn into_rest(self) -> &'b mut [u8] {
1868        self
1869    }
1870}
1871
1872impl<'b, 'a: 'b> BufferViewMut<&'b mut [u8]> for &'b mut &'a mut [u8] {}
1873
1874/// A [`BufferViewMut`] into a `&mut [u8]`.
1875///
1876/// This type is useful for instantiating a mutable view into a slice that can
1877/// be used for parsing, where any parsing that is done only affects this view
1878/// and therefore need not be "undone" later.
1879///
1880/// Note that `BufferViewMut<&mut [u8]>` is also implemented for &mut &mut [u8]
1881/// (a mutable reference to a mutable byte slice), but this can be problematic
1882/// if you need to materialize an *owned* type that implements `BufferViewMut`,
1883/// in order to pass it to a function, for example, so that it does not hold a
1884/// reference to a temporary value.
1885pub struct SliceBufViewMut<'a>(&'a mut [u8]);
1886
1887impl<'a> SliceBufViewMut<'a> {
1888    pub fn new(buf: &'a mut [u8]) -> Self {
1889        Self(buf)
1890    }
1891}
1892
1893impl<'a> BufferView<&'a mut [u8]> for SliceBufViewMut<'a> {
1894    fn take_front(&mut self, n: usize) -> Option<&'a mut [u8]> {
1895        let Self(buf) = self;
1896        buf.split_off_mut(..n)
1897    }
1898
1899    fn take_back(&mut self, n: usize) -> Option<&'a mut [u8]> {
1900        let Self(buf) = self;
1901        let split = <[u8]>::len(buf).checked_sub(n)?;
1902        Some(buf.split_off_mut(split..).unwrap())
1903    }
1904
1905    fn into_rest(self) -> &'a mut [u8] {
1906        self.0
1907    }
1908}
1909
1910impl<'a> BufferViewMut<&'a mut [u8]> for SliceBufViewMut<'a> {}
1911
1912impl<'a> AsRef<[u8]> for SliceBufViewMut<'a> {
1913    fn as_ref(&self) -> &[u8] {
1914        self.0
1915    }
1916}
1917
1918impl<'a> AsMut<[u8]> for SliceBufViewMut<'a> {
1919    fn as_mut(&mut self) -> &mut [u8] {
1920        self.0
1921    }
1922}
1923
1924/// An implementation of `BufferView` for SplitByteSlices.
1925pub struct SplitByteSliceBufView<B>(B);
1926
1927impl<B> SplitByteSliceBufView<B> {
1928    pub fn new(buf: B) -> Self {
1929        Self(buf)
1930    }
1931
1932    pub fn into_inner(self) -> B {
1933        let Self(buf) = self;
1934        buf
1935    }
1936}
1937
1938impl<B: SplitByteSlice> AsRef<[u8]> for SplitByteSliceBufView<B> {
1939    fn as_ref(&self) -> &[u8] {
1940        self.0.as_ref()
1941    }
1942}
1943
1944impl<B: SplitByteSlice> BufferView<B> for SplitByteSliceBufView<B> {
1945    fn take_front(&mut self, n: usize) -> Option<B> {
1946        replace_with::replace_with_and(&mut self.0, |b| match b.split_at(n) {
1947            Ok((prefix, suffix)) => (suffix, Some(prefix)),
1948            Err(e) => (e, None),
1949        })
1950    }
1951
1952    fn take_back(&mut self, n: usize) -> Option<B> {
1953        let len = self.0.deref().len();
1954        let split_point = len.checked_sub(n)?;
1955        replace_with::replace_with_and(&mut self.0, |b| match b.split_at(split_point) {
1956            Ok((prefix, suffix)) => (prefix, Some(suffix)),
1957            Err(_e) => unreachable!("The length of the buffer was already checked"),
1958        })
1959    }
1960
1961    fn into_rest(self) -> B {
1962        let Self(b) = self;
1963        b
1964    }
1965}
1966
1967// Returns the inclusive-exclusive equivalent of the bound, verifying that it is
1968// in range of `len`, and panicking if it is not or if the range is nonsensical.
1969fn canonicalize_range<R: RangeBounds<usize>>(len: usize, range: &R) -> Range<usize> {
1970    let lower = canonicalize_lower_bound(range.start_bound());
1971    let upper = canonicalize_upper_bound(len, range.end_bound()).expect("range out of bounds");
1972    assert!(lower <= upper, "invalid range: upper bound precedes lower bound");
1973    lower..upper
1974}
1975
1976// Returns the inclusive equivalent of the bound.
1977fn canonicalize_lower_bound(bound: Bound<&usize>) -> usize {
1978    match bound {
1979        Bound::Included(x) => *x,
1980        Bound::Excluded(x) => *x + 1,
1981        Bound::Unbounded => 0,
1982    }
1983}
1984
1985// Returns the exclusive equivalent of the bound, verifying that it is in range
1986// of `len`.
1987fn canonicalize_upper_bound(len: usize, bound: Bound<&usize>) -> Option<usize> {
1988    let bound = match bound {
1989        Bound::Included(x) => *x + 1,
1990        Bound::Excluded(x) => *x,
1991        Bound::Unbounded => len,
1992    };
1993    if bound > len {
1994        return None;
1995    }
1996    Some(bound)
1997}
1998
1999mod sealed {
2000    pub trait Sealed {}
2001}
2002
2003#[cfg(test)]
2004mod tests {
2005    use super::*;
2006
2007    // Call test_buffer, test_buffer_view, and test_buffer_view_post for each of
2008    // the Buffer types. Call test_parse_buffer and test_buffer_view for each of
2009    // the ParseBuffer types.
2010
2011    #[test]
2012    fn test_byte_slice_impl_buffer() {
2013        let mut avoid_leaks = Vec::new();
2014        test_parse_buffer::<&[u8], _>(|len| {
2015            let v = ascending(len);
2016            // Requires that |avoid_leaks| outlives this reference. In this case, we know
2017            // |test_parse_buffer| does not retain the reference beyond its run.
2018            let s = unsafe { core::slice::from_raw_parts(v.as_ptr(), v.len()) };
2019            avoid_leaks.push(v);
2020            s
2021        });
2022        let buf = ascending(10);
2023        let mut buf: &[u8] = buf.as_ref();
2024        test_buffer_view::<&[u8], _>(&mut buf);
2025    }
2026
2027    #[test]
2028    fn test_byte_slice_mut_impl_buffer() {
2029        let mut avoid_leaks = Vec::new();
2030        test_parse_buffer::<&mut [u8], _>(|len| {
2031            let mut v = ascending(len);
2032            // Requires that |avoid_leaks| outlives this reference. In this case, we know
2033            // |test_parse_buffer| does not retain the reference beyond its run.
2034            let s = unsafe { core::slice::from_raw_parts_mut(v.as_mut_ptr(), v.len()) };
2035            avoid_leaks.push(v);
2036            s
2037        });
2038        let mut buf = ascending(10);
2039        let mut buf: &mut [u8] = buf.as_mut();
2040        test_buffer_view::<&mut [u8], _>(&mut buf);
2041    }
2042
2043    #[test]
2044    fn test_either_impl_buffer() {
2045        macro_rules! test_either {
2046            ($variant:ident) => {
2047                test_buffer::<Either<Buf<Vec<u8>>, Buf<Vec<u8>>>, _>(|len| {
2048                    Either::$variant(Buf::new(ascending(len), ..))
2049                });
2050                // Test call to `Buf::buffer_view` which returns a
2051                // `BufferView`.
2052                let mut buf: Either<Buf<Vec<u8>>, Buf<Vec<u8>>> =
2053                    Either::$variant(Buf::new(ascending(10), ..));
2054                test_buffer_view(match &mut buf {
2055                    Either::$variant(buf) => buf.buffer_view(),
2056                    _ => unreachable!(),
2057                });
2058                test_buffer_view_post(&buf, true);
2059                // Test call to `Buf::buffer_view_mut` which returns a
2060                // `BufferViewMut`.
2061                let mut buf: Either<Buf<Vec<u8>>, Buf<Vec<u8>>> =
2062                    Either::$variant(Buf::new(ascending(10), ..));
2063                test_buffer_view_mut(match &mut buf {
2064                    Either::$variant(buf) => buf.buffer_view_mut(),
2065                    _ => unreachable!(),
2066                });
2067                test_buffer_view_mut_post(&buf, true);
2068            };
2069        }
2070
2071        test_either!(A);
2072        test_either!(B);
2073    }
2074
2075    #[test]
2076    fn test_slice_buf_view_mut() {
2077        let mut buf = ascending(10);
2078
2079        test_buffer_view(SliceBufViewMut::new(&mut buf));
2080        test_buffer_view_mut(SliceBufViewMut::new(&mut buf));
2081    }
2082
2083    #[test]
2084    fn test_buf_impl_buffer() {
2085        test_buffer(|len| Buf::new(ascending(len), ..));
2086        let mut buf = Buf::new(ascending(10), ..);
2087        test_buffer_view(buf.buffer_view());
2088        test_buffer_view_post(&buf, true);
2089    }
2090
2091    #[test]
2092    fn test_split_byte_slice_buf_view() {
2093        let buf = ascending(10);
2094        test_buffer_view(SplitByteSliceBufView::new(buf.as_slice()));
2095    }
2096
2097    fn ascending(n: u8) -> Vec<u8> {
2098        (0..n).collect::<Vec<u8>>()
2099    }
2100
2101    // This test performs a number of shrinking operations (for ParseBuffer
2102    // implementations) followed by their equivalent growing operations (for
2103    // Buffer implementations only), and at each step, verifies various
2104    // properties of the buffer. The shrinking part of the test is in
2105    // test_parse_buffer_inner, while test_buffer calls test_parse_buffer_inner
2106    // and then performs the growing part of the test.
2107
2108    // When shrinking, we keep two buffers - 'at_once' and 'separately', and for
2109    // each test case, we do the following:
2110    // - shrink the 'at_once' buffer with the 'shrink' field
2111    // - shrink_front the 'separately' buffer with the 'front' field
2112    // - shrink_back the 'separately' buffer with the 'back' field
2113    //
2114    // When growing, we only keep one buffer from the shrinking phase, and for
2115    // each test case, we do the following:
2116    // - grow_front the buffer with the 'front' field
2117    // - grow_back the buffer with the 'back' field
2118    //
2119    // After each action, we verify that the len and contents are as expected.
2120    // For Buffers, we also verify the cap, prefix, and suffix.
2121    struct TestCase {
2122        shrink: Range<usize>,
2123        front: usize, // shrink or grow the front of the body
2124        back: usize,  // shrink or grow the back of the body
2125        cap: usize,
2126        len: usize,
2127        pfx: usize,
2128        sfx: usize,
2129        contents: &'static [u8],
2130    }
2131    #[rustfmt::skip]
2132    const TEST_CASES: &[TestCase] = &[
2133        TestCase { shrink: 0..10, front: 0, back: 0, cap: 10, len: 10, pfx: 0, sfx: 0, contents: &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], },
2134        TestCase { shrink: 2..10, front: 2, back: 0, cap: 10, len: 8,  pfx: 2, sfx: 0, contents: &[2, 3, 4, 5, 6, 7, 8, 9], },
2135        TestCase { shrink: 0..8,  front: 0, back: 0, cap: 10, len: 8,  pfx: 2, sfx: 0, contents: &[2, 3, 4, 5, 6, 7, 8, 9], },
2136        TestCase { shrink: 0..6,  front: 0, back: 2, cap: 10, len: 6,  pfx: 2, sfx: 2, contents: &[2, 3, 4, 5, 6, 7], },
2137        TestCase { shrink: 2..4,  front: 2, back: 2, cap: 10, len: 2,  pfx: 4, sfx: 4, contents: &[4, 5], },
2138    ];
2139
2140    // Test a ParseBuffer implementation. 'new_buf' is a function which
2141    // constructs a buffer of length n, and initializes its contents to [0, 1,
2142    // 2, ..., n -1].
2143    fn test_parse_buffer<B: ParseBuffer, N: FnMut(u8) -> B>(new_buf: N) {
2144        let _: B = test_parse_buffer_inner(new_buf, |buf, _, len, _, _, contents| {
2145            assert_eq!(buf.len(), len);
2146            assert_eq!(buf.as_ref(), contents);
2147        });
2148    }
2149
2150    // Code common to test_parse_buffer and test_buffer. 'assert' is a function
2151    // which takes a buffer, and verifies that its capacity, length, prefix,
2152    // suffix, and contents are equal to the arguments (in that order). For
2153    // ParseBuffers, the capacity, prefix, and suffix arguments are irrelevant,
2154    // and ignored.
2155    //
2156    // When the test is done, test_parse_buffer_inner returns one of the buffers
2157    // it used for testing so that test_buffer can do further testing on it. Its
2158    // prefix, body, and suffix will be [0, 1, 2, 3], [4, 5], and [6, 7, 8, 9]
2159    // respectively.
2160    fn test_parse_buffer_inner<
2161        B: ParseBuffer,
2162        N: FnMut(u8) -> B,
2163        A: Fn(&B, usize, usize, usize, usize, &[u8]),
2164    >(
2165        mut new_buf: N,
2166        assert: A,
2167    ) -> B {
2168        let mut at_once = new_buf(10);
2169        let mut separately = new_buf(10);
2170        for tc in TEST_CASES {
2171            at_once.shrink(tc.shrink.clone());
2172            separately.shrink_front(tc.front);
2173            separately.shrink_back(tc.back);
2174            assert(&at_once, tc.cap, tc.len, tc.pfx, tc.sfx, tc.contents);
2175            assert(&separately, tc.cap, tc.len, tc.pfx, tc.sfx, tc.contents);
2176        }
2177        at_once
2178    }
2179
2180    // Test a Buffer implementation. 'new_buf' is a function which constructs a
2181    // buffer of length and capacity n, and initializes its contents to [0, 1,
2182    // 2, ..., n - 1].
2183    fn test_buffer<B: Buffer, F: Fn(u8) -> B>(new_buf: F) {
2184        fn assert<B: Buffer>(
2185            buf: &B,
2186            cap: usize,
2187            len: usize,
2188            pfx: usize,
2189            sfx: usize,
2190            contents: &[u8],
2191        ) {
2192            assert_eq!(buf.len(), len);
2193            assert_eq!(buf.capacity(), cap);
2194            assert_eq!(buf.prefix_len(), pfx);
2195            assert_eq!(buf.suffix_len(), sfx);
2196            assert_eq!(buf.as_ref(), contents);
2197        }
2198
2199        let mut buf = test_parse_buffer_inner(new_buf, assert);
2200        buf.reset();
2201        assert(&buf, 10, 10, 0, 0, &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9][..]);
2202        buf.shrink_front(4);
2203        buf.shrink_back(4);
2204        assert(&buf, 10, 2, 4, 4, &[4, 5][..]);
2205
2206        for tc in TEST_CASES.iter().rev() {
2207            assert(&buf, tc.cap, tc.len, tc.pfx, tc.sfx, tc.contents);
2208            buf.grow_front(tc.front);
2209            buf.grow_back(tc.back);
2210        }
2211    }
2212
2213    // Test a BufferView implementation. Call with a view into a buffer with no
2214    // extra capacity whose body contains [0, 1, ..., 9]. After the call
2215    // returns, call test_buffer_view_post on the buffer.
2216    fn test_buffer_view<B: SplitByteSlice, BV: BufferView<B>>(mut view: BV) {
2217        assert_eq!(view.len(), 10);
2218        assert_eq!(view.take_front(1).unwrap().as_ref(), &[0][..]);
2219        assert_eq!(view.len(), 9);
2220        assert_eq!(view.take_back(1).unwrap().as_ref(), &[9][..]);
2221        assert_eq!(view.len(), 8);
2222        assert_eq!(view.peek_obj_front::<[u8; 2]>().unwrap(), &[1, 2]);
2223        assert_eq!(view.take_obj_front::<[u8; 2]>().unwrap().as_ref(), [1, 2]);
2224        assert_eq!(view.len(), 6);
2225        assert_eq!(view.peek_obj_front::<u8>().unwrap(), &3);
2226        assert_eq!(view.take_owned_obj_front::<u8>().unwrap(), 3);
2227        assert_eq!(view.len(), 5);
2228        assert_eq!(view.peek_obj_back::<[u8; 2]>().unwrap(), &[7, 8]);
2229        assert_eq!(view.take_obj_back::<[u8; 2]>().unwrap().as_ref(), [7, 8]);
2230        assert_eq!(view.len(), 3);
2231        assert_eq!(view.peek_obj_back::<u8>().unwrap(), &6);
2232        assert_eq!(view.take_owned_obj_back::<u8>().unwrap(), 6);
2233        assert_eq!(view.len(), 2);
2234        assert!(view.take_front(3).is_none());
2235        assert_eq!(view.len(), 2);
2236        assert!(view.take_back(3).is_none());
2237        assert_eq!(view.len(), 2);
2238        assert_eq!(view.into_rest().as_ref(), &[4, 5][..]);
2239    }
2240
2241    // Test a BufferViewMut implementation. Call with a mutable view into a buffer
2242    // with no extra capacity whose body contains [0, 1, ..., 9]. After the call
2243    // returns, call test_buffer_view_post on the buffer.
2244    fn test_buffer_view_mut<B: SplitByteSliceMut, BV: BufferViewMut<B>>(mut view: BV) {
2245        assert_eq!(view.len(), 10);
2246        assert_eq!(view.as_mut()[0], 0);
2247        assert_eq!(view.take_front_zero(1).unwrap().as_ref(), &[0][..]);
2248        assert_eq!(view.len(), 9);
2249        assert_eq!(view.as_mut()[0], 1);
2250        assert_eq!(view.take_front_zero(1).unwrap().as_ref(), &[0][..]);
2251        assert_eq!(view.len(), 8);
2252        assert_eq!(view.as_mut()[7], 9);
2253        assert_eq!(view.take_back_zero(1).unwrap().as_ref(), &[0][..]);
2254        assert_eq!(view.len(), 7);
2255        assert_eq!(&view.as_mut()[0..2], &[2, 3][..]);
2256        assert_eq!(view.peek_obj_front::<[u8; 2]>().unwrap(), &[2, 3]);
2257        assert_eq!(view.take_obj_front_zero::<[u8; 2]>().unwrap().as_ref(), &[0, 0][..]);
2258        assert_eq!(view.len(), 5);
2259        assert_eq!(&view.as_mut()[3..5], &[7, 8][..]);
2260        assert_eq!(view.peek_obj_back::<[u8; 2]>().unwrap(), &[7, 8]);
2261        assert_eq!(view.take_obj_back_zero::<[u8; 2]>().unwrap().as_ref(), &[0, 0][..]);
2262        assert_eq!(view.write_obj_front(&[0u8]), Some(()));
2263        assert_eq!(view.as_mut(), &[5, 6][..]);
2264        assert_eq!(view.write_obj_back(&[0u8]), Some(()));
2265        assert_eq!(view.as_mut(), &[5][..]);
2266        assert!(view.take_front_zero(2).is_none());
2267        assert_eq!(view.len(), 1);
2268        assert!(view.take_back_zero(2).is_none());
2269        assert_eq!(view.len(), 1);
2270        assert_eq!(view.as_mut(), &[5][..]);
2271        assert_eq!(view.into_rest_zero().as_ref(), &[0][..]);
2272    }
2273
2274    // Post-verification to test a BufferView implementation. Call after
2275    // test_buffer_view.
2276    fn test_buffer_view_post<B: Buffer>(buffer: &B, preserves_cap: bool) {
2277        assert_eq!(buffer.as_ref(), &[4, 5][..]);
2278        if preserves_cap {
2279            assert_eq!(buffer.prefix_len(), 4);
2280            assert_eq!(buffer.suffix_len(), 4);
2281        }
2282    }
2283
2284    // Post-verification to test a BufferViewMut implementation. Call after
2285    // test_buffer_view_mut.
2286    fn test_buffer_view_mut_post<B: Buffer>(buffer: &B, preserves_cap: bool) {
2287        assert_eq!(buffer.as_ref(), &[0][..]);
2288        if preserves_cap {
2289            assert_eq!(buffer.prefix_len(), 5);
2290            assert_eq!(buffer.suffix_len(), 4);
2291        }
2292    }
2293
2294    #[test]
2295    fn test_buffer_view_from_buffer() {
2296        // This test is specifically designed to verify that implementations of
2297        // ParseBuffer::parse properly construct a BufferView, and that that
2298        // BufferView properly updates the underlying buffer. It was inspired by
2299        // the bug with Change-Id Ifeab21fba0f7ba94d1a12756d4e83782002e4e1e.
2300
2301        // This ParsablePacket implementation takes the contents it expects as a
2302        // parse argument and validates the BufferView[Mut] against it. It consumes
2303        // one byte from the front and one byte from the back to ensure that that
2304        // functionality works as well. For a mutable buffer, the implementation also
2305        // modifies the bytes that were consumed so tests can make sure that the
2306        // `parse_mut` function was actually called and that the bytes are mutable.
2307        struct TestParsablePacket {}
2308        impl<B: SplitByteSlice> ParsablePacket<B, &[u8]> for TestParsablePacket {
2309            type Error = ();
2310            fn parse<BV: BufferView<B>>(
2311                mut buffer: BV,
2312                args: &[u8],
2313            ) -> Result<TestParsablePacket, ()> {
2314                assert_eq!(buffer.as_ref(), args);
2315                let _: B = buffer.take_front(1).unwrap();
2316                let _: B = buffer.take_back(1).unwrap();
2317                Ok(TestParsablePacket {})
2318            }
2319
2320            fn parse_mut<BV: BufferViewMut<B>>(
2321                mut buffer: BV,
2322                args: &[u8],
2323            ) -> Result<TestParsablePacket, ()>
2324            where
2325                B: SplitByteSliceMut,
2326            {
2327                assert_eq!(buffer.as_ref(), args);
2328                buffer.take_front(1).unwrap().as_mut()[0] += 1;
2329                buffer.take_back(1).unwrap().as_mut()[0] += 2;
2330                Ok(TestParsablePacket {})
2331            }
2332
2333            fn parse_metadata(&self) -> ParseMetadata {
2334                unimplemented!()
2335            }
2336        }
2337
2338        // immutable byte slices
2339
2340        let mut buf = &[0, 1, 2, 3, 4, 5, 6, 7][..];
2341        let TestParsablePacket {} =
2342            buf.parse_with::<_, TestParsablePacket>(&[0, 1, 2, 3, 4, 5, 6, 7]).unwrap();
2343        // test that, after parsing, the bytes consumed are consumed permanently
2344        let TestParsablePacket {} =
2345            buf.parse_with::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2346
2347        // test that different temporary values do not affect one another and
2348        // also that slicing works properly (in that the elements outside of the
2349        // slice are not exposed in the BufferView[Mut]; this is fairly obvious
2350        // for slices, but less obvious for Buf, which we test below)
2351        let buf = &[0, 1, 2, 3, 4, 5, 6, 7][..];
2352        let TestParsablePacket {} =
2353            (&buf[1..7]).parse_with::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2354        let TestParsablePacket {} =
2355            (&buf[1..7]).parse_with::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2356
2357        // mutable byte slices
2358
2359        let mut bytes = [0, 1, 2, 3, 4, 5, 6, 7];
2360        let mut buf = &mut bytes[..];
2361        let TestParsablePacket {} =
2362            buf.parse_with::<_, TestParsablePacket>(&[0, 1, 2, 3, 4, 5, 6, 7]).unwrap();
2363        // test that, after parsing, the bytes consumed are consumed permanently
2364        let TestParsablePacket {} =
2365            buf.parse_with::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2366        // test that this also works with parse_with_mut
2367        let TestParsablePacket {} =
2368            buf.parse_with_mut::<_, TestParsablePacket>(&[2, 3, 4, 5]).unwrap();
2369        let TestParsablePacket {} = buf.parse_with_mut::<_, TestParsablePacket>(&[3, 4]).unwrap();
2370        assert_eq!(bytes, [0, 1, 3, 4, 6, 7, 6, 7]);
2371
2372        // test that different temporary values do not affect one another and
2373        // also that slicing works properly (in that the elements outside of the
2374        // slice are not exposed in the BufferView[Mut]; this is fairly obvious
2375        // for slices, but less obvious for Buf, which we test below)
2376        let buf = &mut [0, 1, 2, 3, 4, 5, 6, 7][..];
2377        let TestParsablePacket {} =
2378            (&buf[1..7]).parse_with::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2379        let TestParsablePacket {} =
2380            (&buf[1..7]).parse_with::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2381        let TestParsablePacket {} =
2382            (&mut buf[1..7]).parse_with_mut::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2383        let TestParsablePacket {} =
2384            (&mut buf[1..7]).parse_with_mut::<_, TestParsablePacket>(&[2, 2, 3, 4, 5, 8]).unwrap();
2385        assert_eq!(buf, &[0, 3, 2, 3, 4, 5, 10, 7][..]);
2386
2387        // Buf with immutable byte slice
2388
2389        let mut buf = Buf::new(&[0, 1, 2, 3, 4, 5, 6, 7][..], ..);
2390        let TestParsablePacket {} =
2391            buf.parse_with::<_, TestParsablePacket>(&[0, 1, 2, 3, 4, 5, 6, 7]).unwrap();
2392        // test that, after parsing, the bytes consumed are consumed permanently
2393        let TestParsablePacket {} =
2394            buf.parse_with::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2395
2396        // the same test again, but this time with Buf's range set
2397        let mut buf = Buf::new(&[0, 1, 2, 3, 4, 5, 6, 7][..], 1..7);
2398        let TestParsablePacket {} =
2399            buf.parse_with::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2400        // test that, after parsing, the bytes consumed are consumed permanently
2401        let TestParsablePacket {} = buf.parse_with::<_, TestParsablePacket>(&[2, 3, 4, 5]).unwrap();
2402
2403        // Buf with mutable byte slice
2404
2405        let mut bytes = [0, 1, 2, 3, 4, 5, 6, 7];
2406        let buf = &mut bytes[..];
2407        let mut buf = Buf::new(&mut buf[..], ..);
2408        let TestParsablePacket {} =
2409            buf.parse_with::<_, TestParsablePacket>(&[0, 1, 2, 3, 4, 5, 6, 7]).unwrap();
2410        // test that, after parsing, the bytes consumed are consumed permanently
2411        let TestParsablePacket {} =
2412            buf.parse_with::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2413        // test that this also works with parse_with_mut
2414        let TestParsablePacket {} =
2415            buf.parse_with_mut::<_, TestParsablePacket>(&[2, 3, 4, 5]).unwrap();
2416        let TestParsablePacket {} = buf.parse_with_mut::<_, TestParsablePacket>(&[3, 4]).unwrap();
2417        assert_eq!(bytes, [0, 1, 3, 4, 6, 7, 6, 7]);
2418        // the same test again, but this time with Buf's range set
2419        let mut bytes = [0, 1, 2, 3, 4, 5, 6, 7];
2420        let buf = &mut bytes[..];
2421        let mut buf = Buf::new(&mut buf[..], 1..7);
2422        let TestParsablePacket {} =
2423            buf.parse_with::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2424        // test that, after parsing, the bytes consumed are consumed permanently
2425        let TestParsablePacket {} = buf.parse_with::<_, TestParsablePacket>(&[2, 3, 4, 5]).unwrap();
2426        assert_eq!(bytes, [0, 1, 2, 3, 4, 5, 6, 7]);
2427        // test that this also works with parse_with_mut
2428        let mut bytes = [0, 1, 2, 3, 4, 5, 6, 7];
2429        let buf = &mut bytes[..];
2430        let mut buf = Buf::new(&mut buf[..], 1..7);
2431        let TestParsablePacket {} =
2432            buf.parse_with_mut::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2433        let TestParsablePacket {} =
2434            buf.parse_with_mut::<_, TestParsablePacket>(&[2, 3, 4, 5]).unwrap();
2435        assert_eq!(bytes, [0, 2, 3, 3, 4, 7, 8, 7]);
2436    }
2437
2438    #[test]
2439    fn test_buf_shrink_to() {
2440        // Tests the shrink_front_to and shrink_back_to methods.
2441        fn test(buf: &[u8], shrink_to: usize, size_after: usize) {
2442            let mut buf0 = &buf[..];
2443            buf0.shrink_front_to(shrink_to);
2444            assert_eq!(buf0.len(), size_after);
2445            let mut buf1 = &buf[..];
2446            buf1.shrink_back_to(shrink_to);
2447            assert_eq!(buf0.len(), size_after);
2448        }
2449
2450        test(&[0, 1, 2, 3], 2, 2);
2451        test(&[0, 1, 2, 3], 4, 4);
2452        test(&[0, 1, 2, 3], 8, 4);
2453    }
2454
2455    #[test]
2456    fn test_empty_buf() {
2457        // Test ParseBuffer impl
2458
2459        assert_eq!(EmptyBuf.as_ref(), []);
2460        assert_eq!(EmptyBuf.as_mut(), []);
2461        EmptyBuf.shrink_front(0);
2462        EmptyBuf.shrink_back(0);
2463
2464        // Test Buffer impl
2465
2466        assert_eq!(EmptyBuf.prefix_len(), 0);
2467        assert_eq!(EmptyBuf.suffix_len(), 0);
2468        EmptyBuf.grow_front(0);
2469        EmptyBuf.grow_back(0);
2470
2471        // Test BufferView impl
2472
2473        assert_eq!(BufferView::<&[u8]>::take_front(&mut EmptyBuf, 0), Some(&[][..]));
2474        assert_eq!(BufferView::<&[u8]>::take_front(&mut EmptyBuf, 1), None);
2475        assert_eq!(BufferView::<&[u8]>::take_back(&mut EmptyBuf, 0), Some(&[][..]));
2476        assert_eq!(BufferView::<&[u8]>::take_back(&mut EmptyBuf, 1), None);
2477        assert_eq!(BufferView::<&[u8]>::into_rest(EmptyBuf), &[][..]);
2478    }
2479
2480    // Each panic test case needs to be in its own function, which results in an
2481    // explosion of test functions. These macros generates the appropriate
2482    // function definitions automatically for a given type, reducing the amount
2483    // of code by a factor of ~4.
2484    macro_rules! make_parse_buffer_panic_tests {
2485        (
2486            $new_empty_buffer:expr,
2487            $shrink_panics:ident,
2488            $nonsense_shrink_panics:ident,
2489        ) => {
2490            #[test]
2491            #[should_panic]
2492            fn $shrink_panics() {
2493                ($new_empty_buffer).shrink(..1);
2494            }
2495            #[test]
2496            #[should_panic]
2497            fn $nonsense_shrink_panics() {
2498                #[allow(clippy::reversed_empty_ranges)] // Intentionally testing with invalid range
2499                ($new_empty_buffer).shrink(1..0);
2500            }
2501        };
2502    }
2503
2504    macro_rules! make_panic_tests {
2505        (
2506            $new_empty_buffer:expr,
2507            $shrink_panics:ident,
2508            $nonsense_shrink_panics:ident,
2509            $grow_front_panics:ident,
2510            $grow_back_panics:ident,
2511        ) => {
2512            make_parse_buffer_panic_tests!(
2513                $new_empty_buffer,
2514                $shrink_panics,
2515                $nonsense_shrink_panics,
2516            );
2517            #[test]
2518            #[should_panic]
2519            fn $grow_front_panics() {
2520                ($new_empty_buffer).grow_front(1);
2521            }
2522            #[test]
2523            #[should_panic]
2524            fn $grow_back_panics() {
2525                ($new_empty_buffer).grow_back(1);
2526            }
2527        };
2528    }
2529
2530    make_parse_buffer_panic_tests!(
2531        &[][..],
2532        test_byte_slice_shrink_panics,
2533        test_byte_slice_nonsense_shrink_panics,
2534    );
2535    make_parse_buffer_panic_tests!(
2536        &mut [][..],
2537        test_byte_slice_mut_shrink_panics,
2538        test_byte_slice_mut_nonsense_shrink_panics,
2539    );
2540    make_panic_tests!(
2541        Either::A::<Buf<&[u8]>, Buf<&[u8]>>(Buf::new(&[][..], ..)),
2542        test_either_slice_panics,
2543        test_either_nonsense_slice_panics,
2544        test_either_grow_front_panics,
2545        test_either_grow_back_panics,
2546    );
2547    make_panic_tests!(
2548        Buf::new(&[][..], ..),
2549        test_buf_shrink_panics,
2550        test_buf_nonsense_shrink_panics,
2551        test_buf_grow_front_panics,
2552        test_buf_grow_back_panics,
2553    );
2554    make_panic_tests!(
2555        EmptyBuf,
2556        test_empty_buf_shrink_panics,
2557        test_empty_buf_nonsense_shrink_panics,
2558        test_empty_buf_grow_front_panics,
2559        test_empty_buf_grow_back_panics,
2560    );
2561
2562    #[test]
2563    fn take_rest_front_back() {
2564        let buf = [1_u8, 2, 3];
2565        let mut b = &mut &buf[..];
2566        assert_eq!(b.take_rest_front(), &buf[..]);
2567        assert_eq!(b.len(), 0);
2568
2569        let mut b = &mut &buf[..];
2570        assert_eq!(b.take_rest_back(), &buf[..]);
2571        assert_eq!(b.len(), 0);
2572    }
2573
2574    #[test]
2575    fn take_byte_front_back() {
2576        let buf = [1_u8, 2, 3, 4];
2577        let mut b = &mut &buf[..];
2578        assert_eq!(b.take_byte_front().unwrap(), 1);
2579        assert_eq!(b.take_byte_front().unwrap(), 2);
2580        assert_eq!(b.take_byte_back().unwrap(), 4);
2581        assert_eq!(b.take_byte_back().unwrap(), 3);
2582        assert!(b.take_byte_front().is_none());
2583        assert!(b.take_byte_back().is_none());
2584    }
2585}