1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
//! The abstraction of Tokio runtimes.

#![doc(html_root_url = "https://docs.rs/izanami-rt/0.1.0-preview.1")]
#![deny(
    missing_docs,
    missing_debug_implementations,
    nonstandard_style,
    rust_2018_idioms,
    rust_2018_compatibility,
    unused
)]
#![forbid(clippy::unimplemented)]

#[doc(no_inline)]
pub use tokio_threadpool::{
    blocking as poll_blocking, //
    BlockingError,
};

use futures::Future;

/// Creates a `Future` to enter the specified blocking section of code.
///
/// The future genereted by this function internally calls the Tokio's blocking API,
/// and then enters a blocking section after other tasks are moved to another thread.
/// See [the documentation of `tokio_threadpool::blocking`][blocking] for details.
///
/// [blocking]: https://docs.rs/tokio-threadpool/0.1/tokio_threadpool/fn.blocking.html
pub fn blocking_section<F, T>(op: F) -> BlockingSection<F>
where
    F: FnOnce() -> T,
{
    BlockingSection { op: Some(op) }
}

/// The future that enters a blocking section of code.
#[derive(Debug)]
pub struct BlockingSection<F> {
    op: Option<F>,
}

impl<F, T> Future for BlockingSection<F>
where
    F: FnOnce() -> T,
{
    type Item = T;
    type Error = BlockingError;

    #[inline]
    fn poll(&mut self) -> futures::Poll<Self::Item, Self::Error> {
        poll_blocking(|| {
            let op = self.op.take().expect("The future has already been polled");
            op()
        })
    }
}

/// A marker trait indicating that the implementor is a Tokio runtime.
pub trait Runtime: sealed::Runtime {}

impl Runtime for tokio::runtime::Runtime {}
impl Runtime for tokio::runtime::current_thread::Runtime {}

/// Trait representing the value that drives on the specific runtime
/// and returns a result.
pub trait Runnable<Rt>
where
    Rt: Runtime + ?Sized,
{
    /// The result type obtained by driving this value.
    type Output;

    /// Run this value onto the specified runtime until it completes.
    fn run(self, rt: &mut Rt) -> Self::Output;
}

impl<F> Runnable<tokio::runtime::Runtime> for F
where
    F: Future + Send + 'static,
    F::Item: Send + 'static,
    F::Error: Send + 'static,
{
    type Output = Result<F::Item, F::Error>;

    fn run(self, rt: &mut tokio::runtime::Runtime) -> Self::Output {
        rt.block_on(self)
    }
}

impl<F> Runnable<tokio::runtime::current_thread::Runtime> for F
where
    F: Future,
{
    type Output = Result<F::Item, F::Error>;

    fn run(self, rt: &mut tokio::runtime::current_thread::Runtime) -> Self::Output {
        rt.block_on(self)
    }
}

/// A marker trait indicating that the implementor is able to spawn asynchronous tasks.
pub trait Spawner: sealed::Spawner {}

impl Spawner for tokio::executor::DefaultExecutor {}
impl Spawner for tokio::runtime::Runtime {}
impl Spawner for tokio::runtime::TaskExecutor {}
impl Spawner for tokio::runtime::current_thread::Runtime {}
impl Spawner for tokio::runtime::current_thread::TaskExecutor {}

/// Trait representing the value to be spawned.
pub trait Spawn<Sp>
where
    Sp: Spawner + ?Sized,
{
    /// Spawns itself onto the specified spawner.
    fn spawn(self, spawner: &mut Sp);
}

impl<F> Spawn<tokio::runtime::Runtime> for F
where
    F: Future<Item = (), Error = ()> + Send + 'static,
{
    fn spawn(self, spawner: &mut tokio::runtime::Runtime) {
        spawner.spawn(self);
    }
}

impl<F> Spawn<tokio::runtime::current_thread::Runtime> for F
where
    F: Future<Item = (), Error = ()> + 'static,
{
    fn spawn(self, spawner: &mut tokio::runtime::current_thread::Runtime) {
        spawner.spawn(self);
    }
}

impl<F> Spawn<tokio::executor::DefaultExecutor> for F
where
    F: Future<Item = (), Error = ()> + Send + 'static,
{
    fn spawn(self, spawner: &mut tokio::executor::DefaultExecutor) {
        use tokio::executor::Executor;
        spawner
            .spawn(Box::new(self))
            .expect("failed to spawn the task");
    }
}

impl<F> Spawn<tokio::runtime::TaskExecutor> for F
where
    F: Future<Item = (), Error = ()> + Send + 'static,
{
    fn spawn(self, spawner: &mut tokio::runtime::TaskExecutor) {
        spawner.spawn(self);
    }
}

impl<F> Spawn<tokio::runtime::current_thread::TaskExecutor> for F
where
    F: Future<Item = (), Error = ()> + 'static,
{
    fn spawn(self, spawner: &mut tokio::runtime::current_thread::TaskExecutor) {
        spawner
            .spawn_local(Box::new(self))
            .expect("failed to spawn the task");
    }
}

mod sealed {
    pub trait Runtime {}
    impl Runtime for tokio::runtime::Runtime {}
    impl Runtime for tokio::runtime::current_thread::Runtime {}

    pub trait Spawner {}
    impl Spawner for tokio::executor::DefaultExecutor {}
    impl Spawner for tokio::runtime::Runtime {}
    impl Spawner for tokio::runtime::TaskExecutor {}
    impl Spawner for tokio::runtime::current_thread::Runtime {}
    impl Spawner for tokio::runtime::current_thread::TaskExecutor {}
}

/// Start the Tokio runtime using the specified task to bootstrap execution.
///
/// Unlike [`run`], it takes a value of `Spawn<Runtime>` in order
/// to allow spawning values that cannot directly implement `Future`.
///
/// [`run`]: https://docs.rs/tokio/0.1/tokio/runtime/fn.run.html
pub fn run<S>(task: S)
where
    S: Spawn<tokio::runtime::Runtime>,
{
    let mut entered = tokio_executor::enter().expect("nested run_incoming");
    let mut runtime = tokio::runtime::Runtime::new().expect("failed to start Runtime");

    task.spawn(&mut runtime);

    entered
        .block_on(runtime.shutdown_on_idle())
        .expect("shutdown cannot error");
}

/// Single-threaded runtime.
pub mod current_thread {
    use super::*;

    /// Start a single-threaded Tokio runtime using the specified task to bootstrap execution.
    ///
    /// Unlike [`run`], it takes a value of `Spawn<Runtime>` in order
    /// to allow spawning values that cannot directly implement `Future`.
    ///
    /// [`run`]: https://docs.rs/tokio/0.1/tokio/runtime/current_thread/fn.run.html
    pub fn run<S>(task: S)
    where
        S: Spawn<tokio::runtime::current_thread::Runtime>,
    {
        let mut runtime =
            tokio::runtime::current_thread::Runtime::new().expect("failed to start Runtime");
        task.spawn(&mut runtime);
        runtime.run().expect("failed to resolve remaining futures");
    }
}