tokio_global/
lib.rs

1//!Provides you with global tokio runtimes
2//!
3//!It can be used from any point in code without need to manually pass around runtime itself
4//!Or being forced to use tokio macros
5//!
6//!## Example
7//!
8//!```rust
9//!use tokio_global::{Runtime, AutoRuntime};
10//!use tokio::io::{AsyncWriteExt, AsyncReadExt};
11//!
12//!async fn server() {
13//!    let mut listener = tokio::net::TcpListener::bind("127.0.0.1:8080").await.expect("To bind");
14//!
15//!    let (mut socket, _) = listener.accept().await.expect("To accept connection");
16//!
17//!    async move {
18//!        let mut buf = [0; 1024];
19//!        loop {
20//!            match socket.read(&mut buf).await {
21//!                // socket closed
22//!                Ok(0) => return,
23//!                Ok(_) => continue,
24//!                Err(_) => panic!("Error :("),
25//!            };
26//!        }
27//!    }.spawn().await.expect("Finish listening");
28//!}
29//!
30//!async fn client() {
31//!    let mut stream = tokio::net::TcpStream::connect("127.0.0.1:8080").await.expect("Connect");
32//!
33//!    // Write some data.
34//!    stream.write_all(b"hello world!").await.expect("Write");
35//!
36//!    //Stop runtime
37//!    Runtime::stop();
38//!}
39//!
40//!let _guard = Runtime::default();
41//!
42//!let runner = std::thread::spawn(|| {
43//!    Runtime::run();
44//!});
45//!
46//!server().spawn();
47//!client().spawn();
48
49pub extern crate tokio;
50
51///Trait to bootstrap your futures.
52pub trait AutoRuntime: core::future::Future {
53    ///Blocks and waits for future to finish.
54    fn wait(self) -> Self::Output where Self: Send + core::future::Future + 'static, Self::Output: Send + 'static;
55
56    ///Spawns futures onto global runtime.
57    ///
58    ///## Note
59    ///
60    ///Can be used in any context, but it requires future that returns nothing
61    fn spawn(self) -> tokio::task::JoinHandle<Self::Output> where Self: Send + core::future::Future + 'static, Self::Output: Send + 'static;
62}
63
64mod blocking;
65mod guard;
66mod global;
67pub use global::Runtime;