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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
//! Async runtime abstraction layer
//!
//! Provides unified primitives for task spawning, joining, and inter-task
//! communication with feature-gated implementations for tokio vs std threads.
//!
//! # Features
//!
//! - `tokio`: Uses tokio runtime primitives (recommended for async workloads)
//! - `std` (without tokio): Falls back to std threads, bounded sync channels,
//! and a parking `block_on` executor
/// Runtime primitives module
///
/// Contains type aliases and functions that abstract over the underlying
/// async runtime (tokio) or std threading.
#[cfg(feature = "tokio")]
pub mod rt {
use core::future::Future;
// =========================================================================
// Types
// =========================================================================
/// Handle to a spawned task
pub type JoinHandle = tokio::task::JoinHandle<()>;
/// Error returned when joining a task fails
pub type JoinError = tokio::task::JoinError;
/// Multi-producer, single-consumer channel sender
pub type Sender<T> = tokio::sync::mpsc::Sender<T>;
/// Multi-producer, single-consumer channel receiver
pub type Receiver<T> = tokio::sync::mpsc::Receiver<T>;
/// One-shot channel sender (single value, single consumer)
pub type OneshotSender<T> = tokio::sync::oneshot::Sender<T>;
/// One-shot channel receiver (single value, single consumer)
pub type OneshotReceiver<T> = tokio::sync::oneshot::Receiver<T>;
// =========================================================================
// Task Management
// =========================================================================
/// Spawn a future as an async task
pub fn spawn<F>(fut: F) -> JoinHandle
where
F: Future<Output = ()> + Send + 'static,
{
tokio::spawn(fut)
}
/// Abort a spawned task
pub fn abort(handle: &JoinHandle) {
handle.abort();
}
/// Wait for a task to complete
pub async fn join(handle: JoinHandle) -> Result<(), JoinError> {
handle.await
}
/// Sleep for a duration
pub async fn sleep(duration: core::time::Duration) {
tokio::time::sleep(duration).await;
}
// =========================================================================
// Channels
// =========================================================================
/// Create a bounded multi-producer, single-consumer channel
pub fn channel<T>(capacity: usize) -> (Sender<T>, Receiver<T>) {
tokio::sync::mpsc::channel(capacity)
}
/// Create a one-shot channel for single value transfer
pub fn oneshot<T>() -> (OneshotSender<T>, OneshotReceiver<T>) {
tokio::sync::oneshot::channel()
}
/// Send a value through a channel
pub async fn send<T>(sender: &Sender<T>, value: T) -> Result<(), ()> {
sender.send(value).await.map_err(|_| ())
}
/// Receive a value from a channel
pub async fn recv<T>(receiver: &mut Receiver<T>) -> Option<T> {
receiver.recv().await
}
/// Wait for a response on a oneshot channel
pub async fn wait_response<T>(receiver: OneshotReceiver<T>) -> Result<T, ()> {
receiver.await.map_err(|_| ())
}
// =========================================================================
// Blocking
// =========================================================================
/// Block on a future from a synchronous context
///
/// # Panics
/// Panics if called outside of a tokio runtime context.
pub fn block_on<F>(future: F) -> F::Output
where
F: Future,
{
tokio::task::block_in_place(|| tokio::runtime::Handle::current().block_on(future))
}
}
#[cfg(all(not(feature = "tokio"), feature = "std"))]
pub mod rt {
use core::{
future::Future,
pin::pin,
task::{Context, Poll, Waker},
};
use std::{
io::{Error, ErrorKind},
sync::mpsc,
sync::Arc,
task::Wake,
thread,
thread::Thread,
};
// =========================================================================
// Types
// =========================================================================
/// Handle to a spawned thread
pub type JoinHandle = thread::JoinHandle<()>;
/// Error returned when joining a thread fails
pub type JoinError = Error;
/// Multi-producer, single-consumer bounded channel sender (std)
pub type Sender<T> = mpsc::SyncSender<T>;
/// Multi-producer, single-consumer bounded channel receiver (std)
pub type Receiver<T> = mpsc::Receiver<T>;
/// One-shot channel sender (simulated with a capacity-1 bounded mpsc)
pub type OneshotSender<T> = mpsc::SyncSender<T>;
/// One-shot channel receiver (simulated with a capacity-1 bounded mpsc)
pub type OneshotReceiver<T> = mpsc::Receiver<T>;
// =========================================================================
// Task Management
// =========================================================================
/// Spawn a closure as a thread
pub fn spawn<F>(task: F) -> JoinHandle
where
F: FnOnce() + Send + 'static,
{
thread::spawn(task)
}
/// Abort a thread (no-op for std threads - dropping detaches)
pub fn abort(_handle: &JoinHandle) {
// No cooperative cancellation for std threads
}
/// Wait for a thread to complete
pub fn join(handle: JoinHandle) -> Result<(), JoinError> {
handle.join().map_err(|_| Error::new(ErrorKind::Other, "thread panicked"))
}
// =========================================================================
// Channels
// =========================================================================
/// Create a bounded multi-producer, single-consumer channel
///
/// [`send`] blocks once `capacity` messages are queued, matching the
/// backpressure semantics of the tokio implementation.
pub fn channel<T>(capacity: usize) -> (Sender<T>, Receiver<T>) {
mpsc::sync_channel(capacity)
}
/// Create a one-shot channel (simulated with a capacity-1 bounded mpsc)
pub fn oneshot<T>() -> (OneshotSender<T>, OneshotReceiver<T>) {
mpsc::sync_channel(1)
}
/// Send a value through a channel (blocking)
pub fn send<T>(sender: &Sender<T>, value: T) -> Result<(), ()> {
sender.send(value).map_err(|_| ())
}
/// Receive a value from a channel (blocking)
pub fn recv<T>(receiver: &Receiver<T>) -> Option<T> {
receiver.recv().ok()
}
/// Wait for a response on a oneshot channel (blocking)
pub fn wait_response<T>(receiver: OneshotReceiver<T>) -> Result<T, ()> {
receiver.recv().map_err(|_| ())
}
/// Sleep for a duration (blocking)
pub fn sleep(duration: core::time::Duration) {
thread::sleep(duration);
}
// =========================================================================
// Blocking
// =========================================================================
/// Waker that unparks the executor thread when the future is ready to
/// make progress
struct ThreadWaker(Thread);
impl Wake for ThreadWaker {
fn wake(self: Arc<Self>) {
self.0.unpark();
}
fn wake_by_ref(self: &Arc<Self>) {
self.0.unpark();
}
}
/// Block on a future using a parking executor
///
/// The current thread parks between polls and is unparked by the waker,
/// so a `Pending` future consumes no CPU while it waits. Spurious
/// unparks only cost an extra poll.
pub fn block_on<F: Future>(future: F) -> F::Output {
let waker = Waker::from(Arc::new(ThreadWaker(thread::current())));
let mut cx = Context::from_waker(&waker);
let mut future = pin!(future);
loop {
match future.as_mut().poll(&mut cx) {
Poll::Ready(result) => return result,
Poll::Pending => thread::park(),
}
}
}
}