Skip to main content

packet/
lib.rs

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