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/// A packet which can be parsed from a buffer.
1640///
1641/// A `ParsablePacket` is a packet which can be parsed from the body of a
1642/// buffer. For performance reasons, it is recommended that as much of the
1643/// packet object as possible be stored as references into the body in order to
1644/// avoid copying.
1645pub trait ParsablePacket<B: SplitByteSlice, ParseArgs>: Sized {
1646 /// The type of errors returned from [`parse`] and [`parse_mut`].
1647 ///
1648 /// [`parse`]: ParsablePacket::parse
1649 /// [`parse_mut`]: ParsablePacket::parse_mut
1650 type Error;
1651
1652 /// Parses a packet from a buffer.
1653 ///
1654 /// Given a view into a buffer, `parse` parses a packet by consuming bytes
1655 /// from the buffer's body. This works slightly differently for normal
1656 /// packets and inner packets (those which do not contain other packets).
1657 ///
1658 /// ## Packets
1659 ///
1660 /// When parsing a packet which contains another packet, the outer packet's
1661 /// header and footer should be consumed from the beginning and end of the
1662 /// buffer's body respectively. The packet's body should be constructed from
1663 /// a reference to the buffer's body (i.e., [`BufferView::into_rest`]), but
1664 /// the buffer's body should not be consumed. This allows the next
1665 /// encapsulated packet to be parsed from the remaining buffer body. See the
1666 /// crate documentation for more details.
1667 ///
1668 /// ## Inner Packets
1669 ///
1670 /// When parsing packets which do not contain other packets, the entire
1671 /// packet's contents should be consumed from the beginning of the buffer's
1672 /// body. The buffer's body should be empty after `parse` has returned.
1673 ///
1674 /// # Padding
1675 ///
1676 /// There may be post-packet padding (coming after the entire packet,
1677 /// including any footer) which was added in order to satisfy the minimum
1678 /// body length requirement of an encapsulating packet. If the packet
1679 /// currently being parsed describes its own length (and thus, it's possible
1680 /// to determine whether there's any padding), `parse` is required to
1681 /// consume any post-packet padding from the buffer's suffix. If this
1682 /// invariant is not upheld, future calls to [`ParseBuffer::parse`] or
1683 /// [`GrowBuffer::undo_parse`] may behave incorrectly.
1684 ///
1685 /// Pre-packet padding is not supported; if a protocol supports such
1686 /// padding, it must be handled in a way that is transparent to this API. In
1687 /// particular, that means that the [`parse_metadata`] method must treat that
1688 /// padding as part of the packet.
1689 ///
1690 /// [`parse_metadata`]: ParsablePacket::parse_metadata
1691 fn parse<BV: BufferView<B>>(buffer: BV, args: ParseArgs) -> Result<Self, Self::Error>;
1692
1693 /// Parses a packet from a mutable buffer.
1694 ///
1695 /// `parse_mut` is like [`parse`], except that it operates on a mutable
1696 /// buffer view.
1697 ///
1698 /// [`parse`]: ParsablePacket::parse
1699 fn parse_mut<BV: BufferViewMut<B>>(buffer: BV, args: ParseArgs) -> Result<Self, Self::Error>
1700 where
1701 B: SplitByteSliceMut,
1702 {
1703 Self::parse(buffer, args)
1704 }
1705
1706 /// Gets metadata about this packet required by [`GrowBuffer::undo_parse`].
1707 ///
1708 /// The returned [`ParseMetadata`] records the number of header and footer
1709 /// bytes consumed by this packet during parsing, and the number of bytes
1710 /// left in the body (not consumed from the buffer). For packets which
1711 /// encapsulate other packets, the header length must be equal to the number
1712 /// of bytes consumed from the prefix, and the footer length must be equal
1713 /// to the number of bytes consumed from the suffix. For inner packets, use
1714 /// [`ParseMetadata::from_inner_packet`].
1715 ///
1716 /// There is one exception: if any post-packet padding was consumed from the
1717 /// suffix, this should not be included, as it is not considered part of the
1718 /// packet. For example, consider a packet with 8 bytes of footer followed
1719 /// by 8 bytes of post-packet padding. Parsing this packet would consume 16
1720 /// bytes from the suffix, but calling `parse_metadata` on the resulting
1721 /// object would return a `ParseMetadata` with only 8 bytes of footer.
1722 fn parse_metadata(&self) -> ParseMetadata;
1723}
1724
1725fn zero_iter<'a, I: Iterator<Item = &'a mut u8>>(bytes: I) {
1726 for byte in bytes {
1727 *byte = 0;
1728 }
1729}
1730
1731fn zero(bytes: &mut [u8]) {
1732 bytes.fill(0);
1733}
1734impl<'a> FragmentedBuffer for &'a [u8] {
1735 fragmented_buffer_method_impls!();
1736}
1737impl<'a> ContiguousBuffer for &'a [u8] {}
1738impl<'a> ShrinkBuffer for &'a [u8] {
1739 fn shrink_front(&mut self, n: usize) {
1740 let _: &[u8] = self.split_off(..n).unwrap();
1741 }
1742 fn shrink_back(&mut self, n: usize) {
1743 let split = <[u8]>::len(self).checked_sub(n).unwrap();
1744 let _: &[u8] = self.split_off(split..).unwrap();
1745 }
1746}
1747impl<'a> ParseBuffer for &'a [u8] {
1748 fn parse_with<'b, ParseArgs, P: ParsablePacket<&'b [u8], ParseArgs>>(
1749 &'b mut self,
1750 args: ParseArgs,
1751 ) -> Result<P, P::Error> {
1752 // A `&'b mut &'a [u8]` wrapper which implements `BufferView<&'b [u8]>`
1753 // instead of `BufferView<&'a [u8]>`. This is needed thanks to fact that
1754 // `P: ParsablePacket` has the lifetime `'b`, not `'a`.
1755 struct ByteSlice<'a, 'b>(&'b mut &'a [u8]);
1756
1757 impl<'a, 'b> AsRef<[u8]> for ByteSlice<'a, 'b> {
1758 fn as_ref(&self) -> &[u8] {
1759 &self.0
1760 }
1761 }
1762
1763 impl<'b, 'a: 'b> BufferView<&'b [u8]> for ByteSlice<'a, 'b> {
1764 fn len(&self) -> usize {
1765 <[u8]>::len(self.0)
1766 }
1767 fn take_front(&mut self, n: usize) -> Option<&'b [u8]> {
1768 self.0.split_off(..n)
1769 }
1770 fn take_back(&mut self, n: usize) -> Option<&'b [u8]> {
1771 let split = <[u8]>::len(self.0).checked_sub(n)?;
1772 self.0.split_off(split..)
1773 }
1774 fn into_rest(self) -> &'b [u8] {
1775 self.0
1776 }
1777 }
1778
1779 P::parse(ByteSlice(self), args)
1780 }
1781}
1782impl<'a> FragmentedBuffer for &'a mut [u8] {
1783 fragmented_buffer_method_impls!();
1784}
1785impl<'a> FragmentedBufferMut for &'a mut [u8] {
1786 fragmented_buffer_mut_method_impls!();
1787}
1788impl<'a> ContiguousBuffer for &'a mut [u8] {}
1789impl<'a> ShrinkBuffer for &'a mut [u8] {
1790 fn shrink_front(&mut self, n: usize) {
1791 let _: &[u8] = self.split_off_mut(..n).unwrap();
1792 }
1793 fn shrink_back(&mut self, n: usize) {
1794 let split = <[u8]>::len(self).checked_sub(n).unwrap();
1795 let _: &[u8] = self.split_off_mut(split..).unwrap();
1796 }
1797}
1798impl<'a> ParseBuffer for &'a mut [u8] {
1799 fn parse_with<'b, ParseArgs, P: ParsablePacket<&'b [u8], ParseArgs>>(
1800 &'b mut self,
1801 args: ParseArgs,
1802 ) -> Result<P, P::Error> {
1803 P::parse(self, args)
1804 }
1805}
1806
1807impl<'a> ParseBufferMut for &'a mut [u8] {
1808 fn parse_with_mut<'b, ParseArgs, P: ParsablePacket<&'b mut [u8], ParseArgs>>(
1809 &'b mut self,
1810 args: ParseArgs,
1811 ) -> Result<P, P::Error> {
1812 P::parse_mut(self, args)
1813 }
1814}
1815
1816impl<'b, 'a: 'b> BufferView<&'a [u8]> for &'b mut &'a [u8] {
1817 fn len(&self) -> usize {
1818 <[u8]>::len(self)
1819 }
1820 fn take_front(&mut self, n: usize) -> Option<&'a [u8]> {
1821 self.split_off(..n)
1822 }
1823 fn take_back(&mut self, n: usize) -> Option<&'a [u8]> {
1824 let split = <[u8]>::len(self).checked_sub(n)?;
1825 Some(self.split_off(split..).unwrap())
1826 }
1827 fn into_rest(self) -> &'a [u8] {
1828 self
1829 }
1830}
1831
1832impl<'b, 'a: 'b> BufferView<&'b [u8]> for &'b mut &'a mut [u8] {
1833 fn len(&self) -> usize {
1834 <[u8]>::len(self)
1835 }
1836 fn take_front(&mut self, n: usize) -> Option<&'b [u8]> {
1837 self.split_off_mut(..n).map(|b| &*b)
1838 }
1839 fn take_back(&mut self, n: usize) -> Option<&'b [u8]> {
1840 let split = <[u8]>::len(self).checked_sub(n)?;
1841 Some(self.split_off_mut(split..).unwrap())
1842 }
1843 fn into_rest(self) -> &'b [u8] {
1844 self
1845 }
1846}
1847
1848impl<'b, 'a: 'b> BufferView<&'b mut [u8]> for &'b mut &'a mut [u8] {
1849 fn len(&self) -> usize {
1850 <[u8]>::len(self)
1851 }
1852 fn take_front(&mut self, n: usize) -> Option<&'b mut [u8]> {
1853 self.split_off_mut(..n)
1854 }
1855 fn take_back(&mut self, n: usize) -> Option<&'b mut [u8]> {
1856 let split = <[u8]>::len(self).checked_sub(n)?;
1857 Some(self.split_off_mut(split..).unwrap())
1858 }
1859 fn into_rest(self) -> &'b mut [u8] {
1860 self
1861 }
1862}
1863
1864impl<'b, 'a: 'b> BufferViewMut<&'b mut [u8]> for &'b mut &'a mut [u8] {}
1865
1866/// A [`BufferViewMut`] into a `&mut [u8]`.
1867///
1868/// This type is useful for instantiating a mutable view into a slice that can
1869/// be used for parsing, where any parsing that is done only affects this view
1870/// and therefore need not be "undone" later.
1871///
1872/// Note that `BufferViewMut<&mut [u8]>` is also implemented for &mut &mut [u8]
1873/// (a mutable reference to a mutable byte slice), but this can be problematic
1874/// if you need to materialize an *owned* type that implements `BufferViewMut`,
1875/// in order to pass it to a function, for example, so that it does not hold a
1876/// reference to a temporary value.
1877pub struct SliceBufViewMut<'a>(&'a mut [u8]);
1878
1879impl<'a> SliceBufViewMut<'a> {
1880 pub fn new(buf: &'a mut [u8]) -> Self {
1881 Self(buf)
1882 }
1883}
1884
1885impl<'a> BufferView<&'a mut [u8]> for SliceBufViewMut<'a> {
1886 fn take_front(&mut self, n: usize) -> Option<&'a mut [u8]> {
1887 let Self(buf) = self;
1888 buf.split_off_mut(..n)
1889 }
1890
1891 fn take_back(&mut self, n: usize) -> Option<&'a mut [u8]> {
1892 let Self(buf) = self;
1893 let split = <[u8]>::len(buf).checked_sub(n)?;
1894 Some(buf.split_off_mut(split..).unwrap())
1895 }
1896
1897 fn into_rest(self) -> &'a mut [u8] {
1898 self.0
1899 }
1900}
1901
1902impl<'a> BufferViewMut<&'a mut [u8]> for SliceBufViewMut<'a> {}
1903
1904impl<'a> AsRef<[u8]> for SliceBufViewMut<'a> {
1905 fn as_ref(&self) -> &[u8] {
1906 self.0
1907 }
1908}
1909
1910impl<'a> AsMut<[u8]> for SliceBufViewMut<'a> {
1911 fn as_mut(&mut self) -> &mut [u8] {
1912 self.0
1913 }
1914}
1915
1916/// An implementation of `BufferView` for SplitByteSlices.
1917pub struct SplitByteSliceBufView<B>(B);
1918
1919impl<B> SplitByteSliceBufView<B> {
1920 pub fn new(buf: B) -> Self {
1921 Self(buf)
1922 }
1923
1924 pub fn into_inner(self) -> B {
1925 let Self(buf) = self;
1926 buf
1927 }
1928}
1929
1930impl<B: SplitByteSlice> AsRef<[u8]> for SplitByteSliceBufView<B> {
1931 fn as_ref(&self) -> &[u8] {
1932 self.0.as_ref()
1933 }
1934}
1935
1936impl<B: SplitByteSlice> BufferView<B> for SplitByteSliceBufView<B> {
1937 fn take_front(&mut self, n: usize) -> Option<B> {
1938 replace_with::replace_with_and(&mut self.0, |b| match b.split_at(n) {
1939 Ok((prefix, suffix)) => (suffix, Some(prefix)),
1940 Err(e) => (e, None),
1941 })
1942 }
1943
1944 fn take_back(&mut self, n: usize) -> Option<B> {
1945 let len = self.0.deref().len();
1946 let split_point = len.checked_sub(n)?;
1947 replace_with::replace_with_and(&mut self.0, |b| match b.split_at(split_point) {
1948 Ok((prefix, suffix)) => (prefix, Some(suffix)),
1949 Err(_e) => unreachable!("The length of the buffer was already checked"),
1950 })
1951 }
1952
1953 fn into_rest(self) -> B {
1954 let Self(b) = self;
1955 b
1956 }
1957}
1958
1959// Returns the inclusive-exclusive equivalent of the bound, verifying that it is
1960// in range of `len`, and panicking if it is not or if the range is nonsensical.
1961fn canonicalize_range<R: RangeBounds<usize>>(len: usize, range: &R) -> Range<usize> {
1962 let lower = canonicalize_lower_bound(range.start_bound());
1963 let upper = canonicalize_upper_bound(len, range.end_bound()).expect("range out of bounds");
1964 assert!(lower <= upper, "invalid range: upper bound precedes lower bound");
1965 lower..upper
1966}
1967
1968// Returns the inclusive equivalent of the bound.
1969fn canonicalize_lower_bound(bound: Bound<&usize>) -> usize {
1970 match bound {
1971 Bound::Included(x) => *x,
1972 Bound::Excluded(x) => *x + 1,
1973 Bound::Unbounded => 0,
1974 }
1975}
1976
1977// Returns the exclusive equivalent of the bound, verifying that it is in range
1978// of `len`.
1979fn canonicalize_upper_bound(len: usize, bound: Bound<&usize>) -> Option<usize> {
1980 let bound = match bound {
1981 Bound::Included(x) => *x + 1,
1982 Bound::Excluded(x) => *x,
1983 Bound::Unbounded => len,
1984 };
1985 if bound > len {
1986 return None;
1987 }
1988 Some(bound)
1989}
1990
1991mod sealed {
1992 pub trait Sealed {}
1993}
1994
1995#[cfg(test)]
1996mod tests {
1997 use super::*;
1998
1999 // Call test_buffer, test_buffer_view, and test_buffer_view_post for each of
2000 // the Buffer types. Call test_parse_buffer and test_buffer_view for each of
2001 // the ParseBuffer types.
2002
2003 #[test]
2004 fn test_byte_slice_impl_buffer() {
2005 let mut avoid_leaks = Vec::new();
2006 test_parse_buffer::<&[u8], _>(|len| {
2007 let v = ascending(len);
2008 // Requires that |avoid_leaks| outlives this reference. In this case, we know
2009 // |test_parse_buffer| does not retain the reference beyond its run.
2010 let s = unsafe { std::slice::from_raw_parts(v.as_ptr(), v.len()) };
2011 avoid_leaks.push(v);
2012 s
2013 });
2014 let buf = ascending(10);
2015 let mut buf: &[u8] = buf.as_ref();
2016 test_buffer_view::<&[u8], _>(&mut buf);
2017 }
2018
2019 #[test]
2020 fn test_byte_slice_mut_impl_buffer() {
2021 let mut avoid_leaks = Vec::new();
2022 test_parse_buffer::<&mut [u8], _>(|len| {
2023 let mut v = ascending(len);
2024 // Requires that |avoid_leaks| outlives this reference. In this case, we know
2025 // |test_parse_buffer| does not retain the reference beyond its run.
2026 let s = unsafe { std::slice::from_raw_parts_mut(v.as_mut_ptr(), v.len()) };
2027 avoid_leaks.push(v);
2028 s
2029 });
2030 let mut buf = ascending(10);
2031 let mut buf: &mut [u8] = buf.as_mut();
2032 test_buffer_view::<&mut [u8], _>(&mut buf);
2033 }
2034
2035 #[test]
2036 fn test_either_impl_buffer() {
2037 macro_rules! test_either {
2038 ($variant:ident) => {
2039 test_buffer::<Either<Buf<Vec<u8>>, Buf<Vec<u8>>>, _>(|len| {
2040 Either::$variant(Buf::new(ascending(len), ..))
2041 });
2042 // Test call to `Buf::buffer_view` which returns a
2043 // `BufferView`.
2044 let mut buf: Either<Buf<Vec<u8>>, Buf<Vec<u8>>> =
2045 Either::$variant(Buf::new(ascending(10), ..));
2046 test_buffer_view(match &mut buf {
2047 Either::$variant(buf) => buf.buffer_view(),
2048 _ => unreachable!(),
2049 });
2050 test_buffer_view_post(&buf, true);
2051 // Test call to `Buf::buffer_view_mut` which returns a
2052 // `BufferViewMut`.
2053 let mut buf: Either<Buf<Vec<u8>>, Buf<Vec<u8>>> =
2054 Either::$variant(Buf::new(ascending(10), ..));
2055 test_buffer_view_mut(match &mut buf {
2056 Either::$variant(buf) => buf.buffer_view_mut(),
2057 _ => unreachable!(),
2058 });
2059 test_buffer_view_mut_post(&buf, true);
2060 };
2061 }
2062
2063 test_either!(A);
2064 test_either!(B);
2065 }
2066
2067 #[test]
2068 fn test_slice_buf_view_mut() {
2069 let mut buf = ascending(10);
2070
2071 test_buffer_view(SliceBufViewMut::new(&mut buf));
2072 test_buffer_view_mut(SliceBufViewMut::new(&mut buf));
2073 }
2074
2075 #[test]
2076 fn test_buf_impl_buffer() {
2077 test_buffer(|len| Buf::new(ascending(len), ..));
2078 let mut buf = Buf::new(ascending(10), ..);
2079 test_buffer_view(buf.buffer_view());
2080 test_buffer_view_post(&buf, true);
2081 }
2082
2083 #[test]
2084 fn test_split_byte_slice_buf_view() {
2085 let buf = ascending(10);
2086 test_buffer_view(SplitByteSliceBufView::new(buf.as_slice()));
2087 }
2088
2089 fn ascending(n: u8) -> Vec<u8> {
2090 (0..n).collect::<Vec<u8>>()
2091 }
2092
2093 // This test performs a number of shrinking operations (for ParseBuffer
2094 // implementations) followed by their equivalent growing operations (for
2095 // Buffer implementations only), and at each step, verifies various
2096 // properties of the buffer. The shrinking part of the test is in
2097 // test_parse_buffer_inner, while test_buffer calls test_parse_buffer_inner
2098 // and then performs the growing part of the test.
2099
2100 // When shrinking, we keep two buffers - 'at_once' and 'separately', and for
2101 // each test case, we do the following:
2102 // - shrink the 'at_once' buffer with the 'shrink' field
2103 // - shrink_front the 'separately' buffer with the 'front' field
2104 // - shrink_back the 'separately' buffer with the 'back' field
2105 //
2106 // When growing, we only keep one buffer from the shrinking phase, and for
2107 // each test case, we do the following:
2108 // - grow_front the buffer with the 'front' field
2109 // - grow_back the buffer with the 'back' field
2110 //
2111 // After each action, we verify that the len and contents are as expected.
2112 // For Buffers, we also verify the cap, prefix, and suffix.
2113 struct TestCase {
2114 shrink: Range<usize>,
2115 front: usize, // shrink or grow the front of the body
2116 back: usize, // shrink or grow the back of the body
2117 cap: usize,
2118 len: usize,
2119 pfx: usize,
2120 sfx: usize,
2121 contents: &'static [u8],
2122 }
2123 #[rustfmt::skip]
2124 const TEST_CASES: &[TestCase] = &[
2125 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], },
2126 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], },
2127 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], },
2128 TestCase { shrink: 0..6, front: 0, back: 2, cap: 10, len: 6, pfx: 2, sfx: 2, contents: &[2, 3, 4, 5, 6, 7], },
2129 TestCase { shrink: 2..4, front: 2, back: 2, cap: 10, len: 2, pfx: 4, sfx: 4, contents: &[4, 5], },
2130 ];
2131
2132 // Test a ParseBuffer implementation. 'new_buf' is a function which
2133 // constructs a buffer of length n, and initializes its contents to [0, 1,
2134 // 2, ..., n -1].
2135 fn test_parse_buffer<B: ParseBuffer, N: FnMut(u8) -> B>(new_buf: N) {
2136 let _: B = test_parse_buffer_inner(new_buf, |buf, _, len, _, _, contents| {
2137 assert_eq!(buf.len(), len);
2138 assert_eq!(buf.as_ref(), contents);
2139 });
2140 }
2141
2142 // Code common to test_parse_buffer and test_buffer. 'assert' is a function
2143 // which takes a buffer, and verifies that its capacity, length, prefix,
2144 // suffix, and contents are equal to the arguments (in that order). For
2145 // ParseBuffers, the capacity, prefix, and suffix arguments are irrelevant,
2146 // and ignored.
2147 //
2148 // When the test is done, test_parse_buffer_inner returns one of the buffers
2149 // it used for testing so that test_buffer can do further testing on it. Its
2150 // prefix, body, and suffix will be [0, 1, 2, 3], [4, 5], and [6, 7, 8, 9]
2151 // respectively.
2152 fn test_parse_buffer_inner<
2153 B: ParseBuffer,
2154 N: FnMut(u8) -> B,
2155 A: Fn(&B, usize, usize, usize, usize, &[u8]),
2156 >(
2157 mut new_buf: N,
2158 assert: A,
2159 ) -> B {
2160 let mut at_once = new_buf(10);
2161 let mut separately = new_buf(10);
2162 for tc in TEST_CASES {
2163 at_once.shrink(tc.shrink.clone());
2164 separately.shrink_front(tc.front);
2165 separately.shrink_back(tc.back);
2166 assert(&at_once, tc.cap, tc.len, tc.pfx, tc.sfx, tc.contents);
2167 assert(&separately, tc.cap, tc.len, tc.pfx, tc.sfx, tc.contents);
2168 }
2169 at_once
2170 }
2171
2172 // Test a Buffer implementation. 'new_buf' is a function which constructs a
2173 // buffer of length and capacity n, and initializes its contents to [0, 1,
2174 // 2, ..., n - 1].
2175 fn test_buffer<B: Buffer, F: Fn(u8) -> B>(new_buf: F) {
2176 fn assert<B: Buffer>(
2177 buf: &B,
2178 cap: usize,
2179 len: usize,
2180 pfx: usize,
2181 sfx: usize,
2182 contents: &[u8],
2183 ) {
2184 assert_eq!(buf.len(), len);
2185 assert_eq!(buf.capacity(), cap);
2186 assert_eq!(buf.prefix_len(), pfx);
2187 assert_eq!(buf.suffix_len(), sfx);
2188 assert_eq!(buf.as_ref(), contents);
2189 }
2190
2191 let mut buf = test_parse_buffer_inner(new_buf, assert);
2192 buf.reset();
2193 assert(&buf, 10, 10, 0, 0, &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9][..]);
2194 buf.shrink_front(4);
2195 buf.shrink_back(4);
2196 assert(&buf, 10, 2, 4, 4, &[4, 5][..]);
2197
2198 for tc in TEST_CASES.iter().rev() {
2199 assert(&buf, tc.cap, tc.len, tc.pfx, tc.sfx, tc.contents);
2200 buf.grow_front(tc.front);
2201 buf.grow_back(tc.back);
2202 }
2203 }
2204
2205 // Test a BufferView implementation. Call with a view into a buffer with no
2206 // extra capacity whose body contains [0, 1, ..., 9]. After the call
2207 // returns, call test_buffer_view_post on the buffer.
2208 fn test_buffer_view<B: SplitByteSlice, BV: BufferView<B>>(mut view: BV) {
2209 assert_eq!(view.len(), 10);
2210 assert_eq!(view.take_front(1).unwrap().as_ref(), &[0][..]);
2211 assert_eq!(view.len(), 9);
2212 assert_eq!(view.take_back(1).unwrap().as_ref(), &[9][..]);
2213 assert_eq!(view.len(), 8);
2214 assert_eq!(view.peek_obj_front::<[u8; 2]>().unwrap(), &[1, 2]);
2215 assert_eq!(view.take_obj_front::<[u8; 2]>().unwrap().as_ref(), [1, 2]);
2216 assert_eq!(view.len(), 6);
2217 assert_eq!(view.peek_obj_front::<u8>().unwrap(), &3);
2218 assert_eq!(view.take_owned_obj_front::<u8>().unwrap(), 3);
2219 assert_eq!(view.len(), 5);
2220 assert_eq!(view.peek_obj_back::<[u8; 2]>().unwrap(), &[7, 8]);
2221 assert_eq!(view.take_obj_back::<[u8; 2]>().unwrap().as_ref(), [7, 8]);
2222 assert_eq!(view.len(), 3);
2223 assert_eq!(view.peek_obj_back::<u8>().unwrap(), &6);
2224 assert_eq!(view.take_owned_obj_back::<u8>().unwrap(), 6);
2225 assert_eq!(view.len(), 2);
2226 assert!(view.take_front(3).is_none());
2227 assert_eq!(view.len(), 2);
2228 assert!(view.take_back(3).is_none());
2229 assert_eq!(view.len(), 2);
2230 assert_eq!(view.into_rest().as_ref(), &[4, 5][..]);
2231 }
2232
2233 // Test a BufferViewMut implementation. Call with a mutable view into a buffer
2234 // with no extra capacity whose body contains [0, 1, ..., 9]. After the call
2235 // returns, call test_buffer_view_post on the buffer.
2236 fn test_buffer_view_mut<B: SplitByteSliceMut, BV: BufferViewMut<B>>(mut view: BV) {
2237 assert_eq!(view.len(), 10);
2238 assert_eq!(view.as_mut()[0], 0);
2239 assert_eq!(view.take_front_zero(1).unwrap().as_ref(), &[0][..]);
2240 assert_eq!(view.len(), 9);
2241 assert_eq!(view.as_mut()[0], 1);
2242 assert_eq!(view.take_front_zero(1).unwrap().as_ref(), &[0][..]);
2243 assert_eq!(view.len(), 8);
2244 assert_eq!(view.as_mut()[7], 9);
2245 assert_eq!(view.take_back_zero(1).unwrap().as_ref(), &[0][..]);
2246 assert_eq!(view.len(), 7);
2247 assert_eq!(&view.as_mut()[0..2], &[2, 3][..]);
2248 assert_eq!(view.peek_obj_front::<[u8; 2]>().unwrap(), &[2, 3]);
2249 assert_eq!(view.take_obj_front_zero::<[u8; 2]>().unwrap().as_ref(), &[0, 0][..]);
2250 assert_eq!(view.len(), 5);
2251 assert_eq!(&view.as_mut()[3..5], &[7, 8][..]);
2252 assert_eq!(view.peek_obj_back::<[u8; 2]>().unwrap(), &[7, 8]);
2253 assert_eq!(view.take_obj_back_zero::<[u8; 2]>().unwrap().as_ref(), &[0, 0][..]);
2254 assert_eq!(view.write_obj_front(&[0u8]), Some(()));
2255 assert_eq!(view.as_mut(), &[5, 6][..]);
2256 assert_eq!(view.write_obj_back(&[0u8]), Some(()));
2257 assert_eq!(view.as_mut(), &[5][..]);
2258 assert!(view.take_front_zero(2).is_none());
2259 assert_eq!(view.len(), 1);
2260 assert!(view.take_back_zero(2).is_none());
2261 assert_eq!(view.len(), 1);
2262 assert_eq!(view.as_mut(), &[5][..]);
2263 assert_eq!(view.into_rest_zero().as_ref(), &[0][..]);
2264 }
2265
2266 // Post-verification to test a BufferView implementation. Call after
2267 // test_buffer_view.
2268 fn test_buffer_view_post<B: Buffer>(buffer: &B, preserves_cap: bool) {
2269 assert_eq!(buffer.as_ref(), &[4, 5][..]);
2270 if preserves_cap {
2271 assert_eq!(buffer.prefix_len(), 4);
2272 assert_eq!(buffer.suffix_len(), 4);
2273 }
2274 }
2275
2276 // Post-verification to test a BufferViewMut implementation. Call after
2277 // test_buffer_view_mut.
2278 fn test_buffer_view_mut_post<B: Buffer>(buffer: &B, preserves_cap: bool) {
2279 assert_eq!(buffer.as_ref(), &[0][..]);
2280 if preserves_cap {
2281 assert_eq!(buffer.prefix_len(), 5);
2282 assert_eq!(buffer.suffix_len(), 4);
2283 }
2284 }
2285
2286 #[test]
2287 fn test_buffer_view_from_buffer() {
2288 // This test is specifically designed to verify that implementations of
2289 // ParseBuffer::parse properly construct a BufferView, and that that
2290 // BufferView properly updates the underlying buffer. It was inspired by
2291 // the bug with Change-Id Ifeab21fba0f7ba94d1a12756d4e83782002e4e1e.
2292
2293 // This ParsablePacket implementation takes the contents it expects as a
2294 // parse argument and validates the BufferView[Mut] against it. It consumes
2295 // one byte from the front and one byte from the back to ensure that that
2296 // functionality works as well. For a mutable buffer, the implementation also
2297 // modifies the bytes that were consumed so tests can make sure that the
2298 // `parse_mut` function was actually called and that the bytes are mutable.
2299 struct TestParsablePacket {}
2300 impl<B: SplitByteSlice> ParsablePacket<B, &[u8]> for TestParsablePacket {
2301 type Error = ();
2302 fn parse<BV: BufferView<B>>(
2303 mut buffer: BV,
2304 args: &[u8],
2305 ) -> Result<TestParsablePacket, ()> {
2306 assert_eq!(buffer.as_ref(), args);
2307 let _: B = buffer.take_front(1).unwrap();
2308 let _: B = buffer.take_back(1).unwrap();
2309 Ok(TestParsablePacket {})
2310 }
2311
2312 fn parse_mut<BV: BufferViewMut<B>>(
2313 mut buffer: BV,
2314 args: &[u8],
2315 ) -> Result<TestParsablePacket, ()>
2316 where
2317 B: SplitByteSliceMut,
2318 {
2319 assert_eq!(buffer.as_ref(), args);
2320 buffer.take_front(1).unwrap().as_mut()[0] += 1;
2321 buffer.take_back(1).unwrap().as_mut()[0] += 2;
2322 Ok(TestParsablePacket {})
2323 }
2324
2325 fn parse_metadata(&self) -> ParseMetadata {
2326 unimplemented!()
2327 }
2328 }
2329
2330 // immutable byte slices
2331
2332 let mut buf = &[0, 1, 2, 3, 4, 5, 6, 7][..];
2333 let TestParsablePacket {} =
2334 buf.parse_with::<_, TestParsablePacket>(&[0, 1, 2, 3, 4, 5, 6, 7]).unwrap();
2335 // test that, after parsing, the bytes consumed are consumed permanently
2336 let TestParsablePacket {} =
2337 buf.parse_with::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2338
2339 // test that different temporary values do not affect one another and
2340 // also that slicing works properly (in that the elements outside of the
2341 // slice are not exposed in the BufferView[Mut]; this is fairly obvious
2342 // for slices, but less obvious for Buf, which we test below)
2343 let buf = &[0, 1, 2, 3, 4, 5, 6, 7][..];
2344 let TestParsablePacket {} =
2345 (&buf[1..7]).parse_with::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2346 let TestParsablePacket {} =
2347 (&buf[1..7]).parse_with::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2348
2349 // mutable byte slices
2350
2351 let mut bytes = [0, 1, 2, 3, 4, 5, 6, 7];
2352 let mut buf = &mut bytes[..];
2353 let TestParsablePacket {} =
2354 buf.parse_with::<_, TestParsablePacket>(&[0, 1, 2, 3, 4, 5, 6, 7]).unwrap();
2355 // test that, after parsing, the bytes consumed are consumed permanently
2356 let TestParsablePacket {} =
2357 buf.parse_with::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2358 // test that this also works with parse_with_mut
2359 let TestParsablePacket {} =
2360 buf.parse_with_mut::<_, TestParsablePacket>(&[2, 3, 4, 5]).unwrap();
2361 let TestParsablePacket {} = buf.parse_with_mut::<_, TestParsablePacket>(&[3, 4]).unwrap();
2362 assert_eq!(bytes, [0, 1, 3, 4, 6, 7, 6, 7]);
2363
2364 // test that different temporary values do not affect one another and
2365 // also that slicing works properly (in that the elements outside of the
2366 // slice are not exposed in the BufferView[Mut]; this is fairly obvious
2367 // for slices, but less obvious for Buf, which we test below)
2368 let buf = &mut [0, 1, 2, 3, 4, 5, 6, 7][..];
2369 let TestParsablePacket {} =
2370 (&buf[1..7]).parse_with::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2371 let TestParsablePacket {} =
2372 (&buf[1..7]).parse_with::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2373 let TestParsablePacket {} =
2374 (&mut buf[1..7]).parse_with_mut::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2375 let TestParsablePacket {} =
2376 (&mut buf[1..7]).parse_with_mut::<_, TestParsablePacket>(&[2, 2, 3, 4, 5, 8]).unwrap();
2377 assert_eq!(buf, &[0, 3, 2, 3, 4, 5, 10, 7][..]);
2378
2379 // Buf with immutable byte slice
2380
2381 let mut buf = Buf::new(&[0, 1, 2, 3, 4, 5, 6, 7][..], ..);
2382 let TestParsablePacket {} =
2383 buf.parse_with::<_, TestParsablePacket>(&[0, 1, 2, 3, 4, 5, 6, 7]).unwrap();
2384 // test that, after parsing, the bytes consumed are consumed permanently
2385 let TestParsablePacket {} =
2386 buf.parse_with::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2387
2388 // the same test again, but this time with Buf's range set
2389 let mut buf = Buf::new(&[0, 1, 2, 3, 4, 5, 6, 7][..], 1..7);
2390 let TestParsablePacket {} =
2391 buf.parse_with::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2392 // test that, after parsing, the bytes consumed are consumed permanently
2393 let TestParsablePacket {} = buf.parse_with::<_, TestParsablePacket>(&[2, 3, 4, 5]).unwrap();
2394
2395 // Buf with mutable byte slice
2396
2397 let mut bytes = [0, 1, 2, 3, 4, 5, 6, 7];
2398 let buf = &mut bytes[..];
2399 let mut buf = Buf::new(&mut buf[..], ..);
2400 let TestParsablePacket {} =
2401 buf.parse_with::<_, TestParsablePacket>(&[0, 1, 2, 3, 4, 5, 6, 7]).unwrap();
2402 // test that, after parsing, the bytes consumed are consumed permanently
2403 let TestParsablePacket {} =
2404 buf.parse_with::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2405 // test that this also works with parse_with_mut
2406 let TestParsablePacket {} =
2407 buf.parse_with_mut::<_, TestParsablePacket>(&[2, 3, 4, 5]).unwrap();
2408 let TestParsablePacket {} = buf.parse_with_mut::<_, TestParsablePacket>(&[3, 4]).unwrap();
2409 assert_eq!(bytes, [0, 1, 3, 4, 6, 7, 6, 7]);
2410 // the same test again, but this time with Buf's range set
2411 let mut bytes = [0, 1, 2, 3, 4, 5, 6, 7];
2412 let buf = &mut bytes[..];
2413 let mut buf = Buf::new(&mut buf[..], 1..7);
2414 let TestParsablePacket {} =
2415 buf.parse_with::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2416 // test that, after parsing, the bytes consumed are consumed permanently
2417 let TestParsablePacket {} = buf.parse_with::<_, TestParsablePacket>(&[2, 3, 4, 5]).unwrap();
2418 assert_eq!(bytes, [0, 1, 2, 3, 4, 5, 6, 7]);
2419 // test that this also works with parse_with_mut
2420 let mut bytes = [0, 1, 2, 3, 4, 5, 6, 7];
2421 let buf = &mut bytes[..];
2422 let mut buf = Buf::new(&mut buf[..], 1..7);
2423 let TestParsablePacket {} =
2424 buf.parse_with_mut::<_, TestParsablePacket>(&[1, 2, 3, 4, 5, 6]).unwrap();
2425 let TestParsablePacket {} =
2426 buf.parse_with_mut::<_, TestParsablePacket>(&[2, 3, 4, 5]).unwrap();
2427 assert_eq!(bytes, [0, 2, 3, 3, 4, 7, 8, 7]);
2428 }
2429
2430 #[test]
2431 fn test_buf_shrink_to() {
2432 // Tests the shrink_front_to and shrink_back_to methods.
2433 fn test(buf: &[u8], shrink_to: usize, size_after: usize) {
2434 let mut buf0 = &buf[..];
2435 buf0.shrink_front_to(shrink_to);
2436 assert_eq!(buf0.len(), size_after);
2437 let mut buf1 = &buf[..];
2438 buf1.shrink_back_to(shrink_to);
2439 assert_eq!(buf0.len(), size_after);
2440 }
2441
2442 test(&[0, 1, 2, 3], 2, 2);
2443 test(&[0, 1, 2, 3], 4, 4);
2444 test(&[0, 1, 2, 3], 8, 4);
2445 }
2446
2447 #[test]
2448 fn test_empty_buf() {
2449 // Test ParseBuffer impl
2450
2451 assert_eq!(EmptyBuf.as_ref(), []);
2452 assert_eq!(EmptyBuf.as_mut(), []);
2453 EmptyBuf.shrink_front(0);
2454 EmptyBuf.shrink_back(0);
2455
2456 // Test Buffer impl
2457
2458 assert_eq!(EmptyBuf.prefix_len(), 0);
2459 assert_eq!(EmptyBuf.suffix_len(), 0);
2460 EmptyBuf.grow_front(0);
2461 EmptyBuf.grow_back(0);
2462
2463 // Test BufferView impl
2464
2465 assert_eq!(BufferView::<&[u8]>::take_front(&mut EmptyBuf, 0), Some(&[][..]));
2466 assert_eq!(BufferView::<&[u8]>::take_front(&mut EmptyBuf, 1), None);
2467 assert_eq!(BufferView::<&[u8]>::take_back(&mut EmptyBuf, 0), Some(&[][..]));
2468 assert_eq!(BufferView::<&[u8]>::take_back(&mut EmptyBuf, 1), None);
2469 assert_eq!(BufferView::<&[u8]>::into_rest(EmptyBuf), &[][..]);
2470 }
2471
2472 // Each panic test case needs to be in its own function, which results in an
2473 // explosion of test functions. These macros generates the appropriate
2474 // function definitions automatically for a given type, reducing the amount
2475 // of code by a factor of ~4.
2476 macro_rules! make_parse_buffer_panic_tests {
2477 (
2478 $new_empty_buffer:expr,
2479 $shrink_panics:ident,
2480 $nonsense_shrink_panics:ident,
2481 ) => {
2482 #[test]
2483 #[should_panic]
2484 fn $shrink_panics() {
2485 ($new_empty_buffer).shrink(..1);
2486 }
2487 #[test]
2488 #[should_panic]
2489 fn $nonsense_shrink_panics() {
2490 #[allow(clippy::reversed_empty_ranges)] // Intentionally testing with invalid range
2491 ($new_empty_buffer).shrink(1..0);
2492 }
2493 };
2494 }
2495
2496 macro_rules! make_panic_tests {
2497 (
2498 $new_empty_buffer:expr,
2499 $shrink_panics:ident,
2500 $nonsense_shrink_panics:ident,
2501 $grow_front_panics:ident,
2502 $grow_back_panics:ident,
2503 ) => {
2504 make_parse_buffer_panic_tests!(
2505 $new_empty_buffer,
2506 $shrink_panics,
2507 $nonsense_shrink_panics,
2508 );
2509 #[test]
2510 #[should_panic]
2511 fn $grow_front_panics() {
2512 ($new_empty_buffer).grow_front(1);
2513 }
2514 #[test]
2515 #[should_panic]
2516 fn $grow_back_panics() {
2517 ($new_empty_buffer).grow_back(1);
2518 }
2519 };
2520 }
2521
2522 make_parse_buffer_panic_tests!(
2523 &[][..],
2524 test_byte_slice_shrink_panics,
2525 test_byte_slice_nonsense_shrink_panics,
2526 );
2527 make_parse_buffer_panic_tests!(
2528 &mut [][..],
2529 test_byte_slice_mut_shrink_panics,
2530 test_byte_slice_mut_nonsense_shrink_panics,
2531 );
2532 make_panic_tests!(
2533 Either::A::<Buf<&[u8]>, Buf<&[u8]>>(Buf::new(&[][..], ..)),
2534 test_either_slice_panics,
2535 test_either_nonsense_slice_panics,
2536 test_either_grow_front_panics,
2537 test_either_grow_back_panics,
2538 );
2539 make_panic_tests!(
2540 Buf::new(&[][..], ..),
2541 test_buf_shrink_panics,
2542 test_buf_nonsense_shrink_panics,
2543 test_buf_grow_front_panics,
2544 test_buf_grow_back_panics,
2545 );
2546 make_panic_tests!(
2547 EmptyBuf,
2548 test_empty_buf_shrink_panics,
2549 test_empty_buf_nonsense_shrink_panics,
2550 test_empty_buf_grow_front_panics,
2551 test_empty_buf_grow_back_panics,
2552 );
2553
2554 #[test]
2555 fn take_rest_front_back() {
2556 let buf = [1_u8, 2, 3];
2557 let mut b = &mut &buf[..];
2558 assert_eq!(b.take_rest_front(), &buf[..]);
2559 assert_eq!(b.len(), 0);
2560
2561 let mut b = &mut &buf[..];
2562 assert_eq!(b.take_rest_back(), &buf[..]);
2563 assert_eq!(b.len(), 0);
2564 }
2565
2566 #[test]
2567 fn take_byte_front_back() {
2568 let buf = [1_u8, 2, 3, 4];
2569 let mut b = &mut &buf[..];
2570 assert_eq!(b.take_byte_front().unwrap(), 1);
2571 assert_eq!(b.take_byte_front().unwrap(), 2);
2572 assert_eq!(b.take_byte_back().unwrap(), 4);
2573 assert_eq!(b.take_byte_back().unwrap(), 3);
2574 assert!(b.take_byte_front().is_none());
2575 assert!(b.take_byte_back().is_none());
2576 }
2577}