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