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