Skip to main content
tokio-util provides additional utilities for working with Tokio. This crate contains helpers and extensions that complement the core Tokio runtime.

Installation

Add tokio-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 traits

compat

Compatibility layer between tokio::io and futures-io traits

io-util

Additional I/O utilities like ReaderStream and StreamReader

time

Time-based utilities including DelayQueue

net

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.
Codecs provide a way to convert between byte streams and typed frames. This is essential for implementing network protocols.

Using LinesCodec

The LinesCodec splits data by newlines:

Reading Framed Data

Custom Decoder Implementation

Here’s an example of a custom length-prefixed string decoder:

Available Codecs

Splits frames by newline characters (\n or \r\n).
Simple codec that works with raw bytes.
Frames data with a length prefix for variable-length messages.
Splits frames by any specified delimiter byte sequence.

Synchronization Primitives

CancellationToken

The CancellationToken allows signaling cancellation requests across multiple tasks:

PollSemaphore

Wrapper around tokio::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 an AsyncRead into a Stream of bytes:

StreamReader

Converts a Stream of bytes into an AsyncRead:

SyncBridge

Bridges tokio::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