actori_rt/runtime.rs
1use std::future::Future;
2use std::io;
3use tokio::{runtime, task::LocalSet};
4
5/// Single-threaded runtime provides a way to start reactor
6/// and runtime on the current thread.
7///
8/// See [module level][mod] documentation for more details.
9///
10/// [mod]: index.html
11#[derive(Debug)]
12pub struct Runtime {
13 local: LocalSet,
14 rt: runtime::Runtime,
15}
16
17impl Runtime {
18 #[allow(clippy::new_ret_no_self)]
19 /// Returns a new runtime initialized with default configuration values.
20 pub fn new() -> io::Result<Runtime> {
21 let rt = runtime::Builder::new()
22 .enable_io()
23 .enable_time()
24 .basic_scheduler()
25 .build()?;
26
27 Ok(Runtime {
28 rt,
29 local: LocalSet::new(),
30 })
31 }
32
33 /// Spawn a future onto the single-threaded runtime.
34 ///
35 /// See [module level][mod] documentation for more details.
36 ///
37 /// [mod]: index.html
38 ///
39 /// # Examples
40 ///
41 /// ```rust,ignore
42 /// # use futures::{future, Future, Stream};
43 /// use actori_rt::Runtime;
44 ///
45 /// # fn dox() {
46 /// // Create the runtime
47 /// let mut rt = Runtime::new().unwrap();
48 ///
49 /// // Spawn a future onto the runtime
50 /// rt.spawn(future::lazy(|_| {
51 /// println!("running on the runtime");
52 /// }));
53 /// # }
54 /// # pub fn main() {}
55 /// ```
56 ///
57 /// # Panics
58 ///
59 /// This function panics if the spawn fails. Failure occurs if the executor
60 /// is currently at capacity and is unable to spawn a new future.
61 pub fn spawn<F>(&self, future: F) -> &Self
62 where
63 F: Future<Output = ()> + 'static,
64 {
65 self.local.spawn_local(future);
66 self
67 }
68
69 /// Runs the provided future, blocking the current thread until the future
70 /// completes.
71 ///
72 /// This function can be used to synchronously block the current thread
73 /// until the provided `future` has resolved either successfully or with an
74 /// error. The result of the future is then returned from this function
75 /// call.
76 ///
77 /// Note that this function will **also** execute any spawned futures on the
78 /// current thread, but will **not** block until these other spawned futures
79 /// have completed. Once the function returns, any uncompleted futures
80 /// remain pending in the `Runtime` instance. These futures will not run
81 /// until `block_on` or `run` is called again.
82 ///
83 /// The caller is responsible for ensuring that other spawned futures
84 /// complete execution by calling `block_on` or `run`.
85 pub fn block_on<F>(&mut self, f: F) -> F::Output
86 where
87 F: Future + 'static,
88 {
89 let res = self.local.block_on(&mut self.rt, f);
90 res
91 }
92}