Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

util: add examples for FramedRead and FramedWrite #6310

Merged
merged 10 commits into from
Feb 10, 2024
21 changes: 21 additions & 0 deletions tokio-util/src/codec/framed_read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,27 @@ use std::task::{Context, Poll};
pin_project! {
/// A [`Stream`] of messages decoded from an [`AsyncRead`].
///
/// # Examples
/// ```
/// use tokio_stream::StreamExt;
/// use tokio_util::codec::LinesCodec;
/// use tokio_util::codec::FramedRead;
///
/// #[tokio::main]
/// async fn main() {
/// let message = "Hello\nWorld".as_bytes();
/// let decoder = LinesCodec::new();
/// let mut reader = FramedRead::new(message, decoder);
///
/// let frame1 = reader.next().await.unwrap().unwrap();
/// let frame2 = reader.next().await.unwrap().unwrap();
///
/// assert!(reader.next().await.is_none());
/// assert_eq!(frame1, "Hello");
/// assert_eq!(frame2, "World");
/// }
/// ```
///
/// [`Stream`]: futures_core::Stream
/// [`AsyncRead`]: tokio::io::AsyncRead
pub struct FramedRead<T, D> {
Expand Down
24 changes: 24 additions & 0 deletions tokio-util/src/codec/framed_write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,30 @@ use std::task::{Context, Poll};
pin_project! {
/// A [`Sink`] of frames encoded to an `AsyncWrite`.
///
/// # Examples
/// ```
/// use futures::sink::SinkExt;
/// use tokio_util::codec::LinesCodec;
/// use tokio_util::codec::FramedWrite;
///
/// #[tokio::main]
/// async fn main() {
/// let messages = vec!["Hello", "World"];
///
/// let buffer = Vec::new();
/// let encoder = LinesCodec::new();
/// let mut writer = FramedWrite::new(buffer, encoder);
///
/// for message in &messages {
/// writer.send(message).await.unwrap();
/// }
///
/// let buffer = writer.get_ref();
///
/// assert_eq!(buffer.as_slice(), "Hello\nWorld\n".as_bytes());
/// }
/// ```
///
/// [`Sink`]: futures_sink::Sink
pub struct FramedWrite<T, E> {
#[pin]
Expand Down