Skip to main content

Crate nio

Crate nio 

Source
Expand description

Documentation Crates.io CI License: Apache-2.0

§Nio

Nio is a Thread-Per-Core async runtime for Rust.

§Task spawning APIs

Nio uses multiple worker threads to execute tasks.

FunctionSend requirementThread affinity
nio::spawn_local!Send allowedPinned to current thread
nio::spawn_pinnedOnly captured variablesPinned to one worker thread (selected by the runtime based on load)
nio::spawn_pinned_atOnly captured variablesPinned to a specific worker thread (by index)
nio::spawnSend requiredNot pinned, may move between threads at .await points

Note: nio::spawn_pinned, nio::spawn_pinned_at accept async closure, Only captured variables required to be Send, task itself is !Send.

§Example

[dependencies]
nio = { version = "0.1.3", features = ["tokio-io"] }

By default, Nio implements async traits from futures-io. But the optional “tokio-io” feature implements async traits from tokio::io.

Here is a basic echo server example:

use futures::AsyncWriteExt;
use nio::net::TcpListener;
use std::io::Result;

#[nio::main]
async fn main() -> Result<()> {
    let mut listener = TcpListener::bind("127.0.0.1:8080").await?;
    println!("{listener:#?}");

    loop {
        let conn = listener.accept().await?;
        println!("[INCOMING] {:?}", conn.peer_addr());

        let accept = || async {
            // Accept the connection on different worker thread
            let mut stream = conn.connect().await?;
            let mut buf = vec![0; 1024];
            while let Ok(n) = stream.read(&mut buf).await {
                if n == 0 {
                    break;
                }
                stream.write_all(&buf[..n]).await.unwrap();
            }
            Result::Ok(())
        };
        nio::spawn_pinned(accept);
    }
}

Modules§

fs
metrics
net

Structs§

AbortHandle
Interval
JoinError
JoinHandle
LocalContext
LocalRuntime
Runtime
RuntimeBuilder
RuntimeContext
Sleep
TaskId
Timeout
WorkerId

Functions§

interval
sleep
spawn
spawn_blocking
spawn_local
spawn_pinned
spawn_pinned_at
task_id
timeout

Attribute Macros§

main
test