moduvex_runtime/runtime.rs
1//! Runtime builder and handle.
2//!
3//! Provides [`RuntimeBuilder`] for configuring and constructing a [`Runtime`],
4//! and [`Runtime`] for driving async entry points.
5//!
6//! # Example
7//! ```
8//! use moduvex_runtime::Runtime;
9//!
10//! let rt = Runtime::builder()
11//! .thread_per_core()
12//! .enable_io()
13//! .enable_time()
14//! .build()
15//! .unwrap();
16//!
17//! rt.block_on(async { 1 + 1 });
18//! ```
19
20use std::future::Future;
21
22use crate::executor;
23
24// ── RuntimeBuilder ───────────────────────────────────────────────────────────
25
26/// Configures a [`Runtime`].
27///
28/// Currently single-threaded (thread-per-core). Multi-thread work-stealing
29/// will be added in a future phase.
30pub struct RuntimeBuilder {
31 _io: bool,
32 _time: bool,
33}
34
35impl RuntimeBuilder {
36 fn new() -> Self {
37 Self {
38 _io: false,
39 _time: false,
40 }
41 }
42
43 /// Use thread-per-core threading model (default).
44 pub fn thread_per_core(self) -> Self {
45 self // already the default
46 }
47
48 /// Enable the I/O reactor.
49 pub fn enable_io(mut self) -> Self {
50 self._io = true;
51 self
52 }
53
54 /// Enable the timer wheel.
55 pub fn enable_time(mut self) -> Self {
56 self._time = true;
57 self
58 }
59
60 /// Build the runtime.
61 pub fn build(self) -> std::io::Result<Runtime> {
62 Ok(Runtime { _private: () })
63 }
64}
65
66// ── Runtime ──────────────────────────────────────────────────────────────────
67
68/// A configured async runtime.
69///
70/// Created via [`Runtime::builder`]. Drives futures to completion with
71/// [`Runtime::block_on`].
72pub struct Runtime {
73 _private: (),
74}
75
76impl Runtime {
77 /// Create a new [`RuntimeBuilder`].
78 pub fn builder() -> RuntimeBuilder {
79 RuntimeBuilder::new()
80 }
81
82 /// Drive `future` to completion, with `spawn()` available inside.
83 pub fn block_on<F: Future>(&self, future: F) -> F::Output {
84 executor::block_on_with_spawn(future)
85 }
86}
87
88// ── Tests ────────────────────────────────────────────────────────────────────
89
90#[cfg(test)]
91mod tests {
92 use super::*;
93
94 #[test]
95 fn builder_creates_runtime() {
96 let rt = Runtime::builder()
97 .thread_per_core()
98 .enable_io()
99 .enable_time()
100 .build()
101 .unwrap();
102 let v = rt.block_on(async { 42u32 });
103 assert_eq!(v, 42);
104 }
105
106 #[test]
107 fn runtime_spawn_works() {
108 let rt = Runtime::builder().build().unwrap();
109 let result = rt.block_on(async {
110 let jh = crate::spawn(async { 100u32 });
111 jh.await.unwrap()
112 });
113 assert_eq!(result, 100);
114 }
115}