enough-tokio
Tokio integration for the enough cooperative cancellation trait.
This crate bridges tokio's CancellationToken with the Stop trait, allowing you to use tokio's cancellation system with any library that accepts impl Stop.
Use Cases
- spawn_blocking with cancellation: Pass cancellation into CPU-intensive sync code
- Unified cancellation: Use the same
Stoptrait across async and sync code - Library integration: Use tokio cancellation with codecs, parsers, and other
impl Stoplibraries
Quick Start
use TokioStop;
use Stop;
use CancellationToken;
async
Features
Wrapping CancellationToken
use TokioStop;
use CancellationToken;
let token = new;
let stop = new;
// Check cancellation
assert!;
// Cancel
token.cancel;
assert!;
Extension Trait
use CancellationTokenExt;
use CancellationToken;
let token = new;
let stop = token.as_stop; // Creates TokioStop
Async Waiting
use TokioStop;
use CancellationToken;
async
Child Tokens
use TokioStop;
use CancellationToken;
let parent = new;
let child = parent.child;
// Child is cancelled when parent is cancelled
parent.cancel;
assert!;
Use with tokio::select!
For one-shot select (runs once):
use TokioStop;
use CancellationToken;
async
async
Important: For select in a loop, pin the future to avoid recreating it each iteration:
use TokioStop;
use mpsc;
async
Wrong (creates new future each iteration, inefficient):
// DON'T do this in a loop!
loop
Integration with Libraries
Any library that accepts impl Stop works seamlessly:
use TokioStop;
use Stop;
use CancellationToken;
// Example library function
async
API Reference
TokioStop
| Method | Description |
|---|---|
new(token) |
Create from CancellationToken |
token() |
Get reference to underlying token |
into_token() |
Consume and return underlying token |
cancelled() |
Async wait for cancellation |
child() |
Create a child TokioStop |
cancel() |
Trigger cancellation |
should_stop() |
Check if cancelled (from Stop trait) |
check() |
Check with Result return (from Stop trait) |
CancellationTokenExt
Extension trait for CancellationToken:
| Method | Description |
|---|---|
as_stop() |
Convert to TokioStop |
Conversions
use TokioStop;
use CancellationToken;
let token = new;
// From CancellationToken
let stop: TokioStop = token.clone.into;
// Back to CancellationToken
let token2: CancellationToken = stop.into;
Thread Safety
TokioStop is Send + Sync and can be safely shared across threads and tasks.
License
Licensed under either of Apache License, Version 2.0 or MIT license at your option.