diff options
author | Benjamin Halsted <benjamin_halsted@yahoo.com> | 2020-04-02 14:09:56 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-04-02 17:09:56 -0400 |
commit | 215d7d4c5f3aa5b436183b8d8abfb9701f34a17d (patch) | |
tree | 915410caec1c0f7ea56400b64adcd96f0c92965b /tokio-util | |
parent | 2a8d917d2c8c310262e81731ca994a17e5f11c3c (diff) |
util: documentation example for LengthDelimitedCodec (#2339)
There is a gap in examples for Builder::num_skip() that shows how to
move past unused bytes between the length and payload.
Diffstat (limited to 'tokio-util')
-rw-r--r-- | tokio-util/src/codec/length_delimited.rs | 31 | ||||
-rw-r--r-- | tokio-util/tests/length_delimited.rs | 19 |
2 files changed, 50 insertions, 0 deletions
diff --git a/tokio-util/src/codec/length_delimited.rs b/tokio-util/src/codec/length_delimited.rs index 5e98d4a7..f11fb3ea 100644 --- a/tokio-util/src/codec/length_delimited.rs +++ b/tokio-util/src/codec/length_delimited.rs @@ -302,6 +302,37 @@ //! anywhere because it already is factored into the total frame length that //! is read from the byte stream. //! +//! ## Example 7 +//! +//! The following will parse a 3 byte length field at offset 0 in a 4 byte +//! frame head, excluding the 4th byte from the yielded `BytesMut`. +//! +//! ``` +//! # use tokio::io::AsyncRead; +//! # use tokio_util::codec::LengthDelimitedCodec; +//! # fn bind_read<T: AsyncRead>(io: T) { +//! LengthDelimitedCodec::builder() +//! .length_field_offset(0) // default value +//! .length_field_length(3) +//! .length_adjustment(0) // default value +//! .num_skip(4) // skip the first 4 bytes +//! .new_read(io); +//! # } +//! # pub fn main() {} +//! ``` +//! +//! The following frame will be decoded as such: +//! +//! ```text +//! INPUT DECODED +//! +------- len ------+--- Payload ---+ +--- Payload ---+ +//! | \x00\x00\x0B\xFF | Hello world | => | Hello world | +//! +------------------+---------------+ +---------------+ +//! ``` +//! +//! A simple example where there are unused bytes between the length field +//! and the payload. +//! //! # Encoding //! //! [`FramedWrite`] adapts an [`AsyncWrite`] into a `Sink` of [`BytesMut`], diff --git a/tokio-util/tests/length_delimited.rs b/tokio-util/tests/length_delimited.rs index 6c519916..734cd834 100644 --- a/tokio-util/tests/length_delimited.rs +++ b/tokio-util/tests/length_delimited.rs @@ -373,6 +373,25 @@ fn read_single_multi_frame_one_packet_skip_none_adjusted() { } #[test] +fn read_single_frame_length_adjusted() { + let mut d: Vec<u8> = vec![]; + d.extend_from_slice(b"\x00\x00\x0b\x0cHello world"); + + let io = length_delimited::Builder::new() + .length_field_offset(0) + .length_field_length(3) + .length_adjustment(0) + .num_skip(4) + .new_read(mock! { + data(&d), + }); + pin_mut!(io); + + assert_next_eq!(io, b"Hello world"); + assert_done!(io); +} + +#[test] fn read_single_multi_frame_one_packet_length_includes_head() { let mut d: Vec<u8> = vec![]; d.extend_from_slice(b"\x00\x0babcdefghi"); |