tokio-util provides additional utilities for working with Tokio. This crate contains helpers and extensions that complement the core Tokio runtime.
Installation
Addtokio-util to your Cargo.toml:
Cargo.toml
tokio-util is not versioned in lockstep with the core tokio crate, but respects Rust’s semantic versioning policy.Features
The crate is organized around optional feature flags:codec
Encoding and decoding frames with
Decoder and Encoder traitscompat
Compatibility layer between
tokio::io and futures-io traitsio-util
Additional I/O utilities like
ReaderStream and StreamReadertime
Time-based utilities including
DelayQueuenet
Network utilities and UDP frame handling
rt
Runtime utilities and task tracking
Enable All Features
Cargo.toml
Codec - Framing I/O Streams
Requires the
codec feature flag.Using LinesCodec
TheLinesCodec splits data by newlines:
Reading Framed Data
Custom Decoder Implementation
Here’s an example of a custom length-prefixed string decoder:Available Codecs
LinesCodec
LinesCodec
Splits frames by newline characters (
\n or \r\n).BytesCodec
BytesCodec
Simple codec that works with raw bytes.
LengthDelimitedCodec
LengthDelimitedCodec
Frames data with a length prefix for variable-length messages.
AnyDelimiterCodec
AnyDelimiterCodec
Splits frames by any specified delimiter byte sequence.
Synchronization Primitives
CancellationToken
TheCancellationToken allows signaling cancellation requests across multiple tasks:
PollSemaphore
Wrapper aroundtokio::sync::Semaphore that provides a poll_acquire method.
Time Utilities
Requires the
time feature flag.DelayQueue
A queue where elements are yielded once their delay has expired. Perfect for managing cache timeouts:I/O Utilities
Requires the
io-util feature flag.ReaderStream
Converts anAsyncRead into a Stream of bytes:
StreamReader
Converts aStream of bytes into an AsyncRead:
SyncBridge
Bridgestokio::io async traits with std::io sync traits, enabling compatibility with blocking I/O.
Task Utilities
Requires the
rt feature flag.TaskTracker
Tracks spawned tasks and waits for them to complete:JoinMap
A collection of tasks that can be awaited individually:Either Type
A sum type for handling two possible types:Resources
API Documentation
Complete API reference on docs.rs
GitHub Repository
View source code and examples