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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
//! Single-future, `#![no_std]` executor based on event bitmasks.
//!
//! See `README.md` for a brief overview. [`Executor`] describes the most important elements
//! to get started.
use ;
pub use ;
pub use nb;
pub use Mpmc;
/// Definition of event bits.
///
/// Implementors should be simple wrappers around `u32` that allow application code to clearly
/// differentiate the relevant event sources. Events and signals correspond to the bits of the
/// value returned by `as_bits()`.
///
/// # Examples
///
/// ```
/// # use nb_executor::EventMask;
/// use bitflags::bitflags;
///
/// bitflags! {
/// struct Ev: u32 {
/// const USB_RX = 1 << 0;
/// const PRIO = 1 << 1;
/// const TICK = 1 << 2;
/// }
/// }
///
/// impl EventMask for Ev {
/// fn as_bits(self) -> u32 {
/// self.bits()
/// }
/// }
/// ```
/// Shared event mask.
///
/// The event mask is an atomic bitmask shared between the executor and the event sources. The type
/// parameter `S` is an [`EventMask`].
///
/// # Events or signals?
/// They are the same. The name "event" refers to their presence in the shared event mask,
/// while the name "signal" refers to poll-local signal masks. Events become signals when they
/// are handled or waited for.
/// Signal state manager and event listener.
///
/// `Signals` maintains the signal state of an [`Executor`]. This consists of the raised signal set
/// and the wakeup signal set. Upon polling the future, the raised signal set is frozen to the
/// then-current value of the event mask, all bits in the wakeup signal set are removed from the
/// event mask (atomically), and the wakeup signal set is cleared. See also [`Step::poll()`]
/// for behavior when the wakeup signal set is zero. Current poll functions which are driven
/// by any of the raised signals will be attempted. If a poll function is not attempted or does
/// not yet resolve to an output then its signal mask will be OR-ed into the wakeup signal set.
/// The future won't be polled again until a raised signal matches the wakeup signal set.
///
/// The type parameter `S` is an [`EventMask`].
///
/// # Delayed signals
/// The executor will examine the event mask after polling the future to check for any
/// immediate updates. Since the raised signal set remains frozen during polling, any signal
/// raised by the future itself through [`Events`] won't become visible until this happens.
/// This also means that external events are not tested for until the future yields. As an
/// optimization for the first case, [`Signals::raise()`] updates the raised signal set
/// immediately. Correct programs are not able to observe this behavior.
/// A single-threaded, single-future async executor.
///
/// # Typical setup
/// - First, an event mask is created with [`Events::default()`] (or [`Events::new()`] if
/// that needs to be `const`). Event masks are `Send + Sync` and shared references to them
/// are enough for all operations, so they work well as `static` items or other types of
/// shared state. Distribute event mask references to the external event sources and keep
/// one for the executor.
///
/// - The event mask is then watched with [`Events::watch()`]. The resulting [`Signals`] is
/// `Send + !Sync`. This means that operations become limited to one thread of execution
/// from this point on, so this is usually done in some type of initialization or main
/// function instead of in a shared or global context.
///
/// - A new executor is bound with [`Signals::bind()`]. Executors are `!Send + !Sync`:
/// neither it nor the associated `Signals` may escape the current thread. This makes them
/// appropriate for construction at the use site.
///
/// - A future is created. It needs a reference to the `Signals` object in order to drive
/// poll functions, making it `!Sync` too.
///
/// - Finally, [`Executor::block_on()`] blocks and resolves the future while external event
/// sources direct it through the event mask, possibly with help from the park function.
///
/// # Examples
///
/// This is a complete usage example. It uses `std::sync` primitives and a park function based on
/// `std::thread::park()` to multiply the integers from 1 to 10 read from a blocking queue.
///
/// ```
/// # use nb_executor::*;
/// # use bitflags::bitflags;
/// use std::{thread, sync::{mpsc::*, Arc}};
///
/// bitflags! {
/// struct Ev: u32 {
/// const QUEUE = 1 << 0;
/// }
/// }
///
/// impl EventMask for Ev {
/// fn as_bits(self) -> u32 {
/// self.bits()
/// }
/// }
///
/// async fn recv(signals: &Signals<'_, Ev>, rx: &Receiver<u32>) -> Option<u32> {
/// signals.drive_infallible(Ev::QUEUE, || match rx.try_recv() {
/// Ok(n) => Ok(Some(n)),
/// Err(TryRecvError::Disconnected) => Ok(None),
/// Err(TryRecvError::Empty) => Err(nb::Error::WouldBlock),
/// }).await
/// }
///
/// let events = Arc::new(Events::default());
/// let signals = events.watch();
///
/// let (tx, rx) = sync_channel(1);
/// let future = async {
/// let mut product = 1;
/// while let Some(n) = recv(&signals, &rx).await {
/// product *= n;
/// }
///
/// product
/// };
///
/// let events_prod = Arc::clone(&events);
/// let runner = thread::current();
///
/// thread::spawn(move || {
/// for n in 1..=10 {
/// tx.send(n).unwrap();
/// events_prod.raise(Ev::QUEUE);
/// runner.unpark();
/// }
///
/// // Notify shutdown
/// drop(tx);
/// events_prod.raise(Ev::QUEUE);
/// runner.unpark();
/// });
///
/// let result = signals.bind().block_on(future, |park| {
/// // thread::park() is event-safe, no lock is required
/// let parked = park.race_free();
/// if parked.is_idle() {
/// thread::park();
/// }
///
/// parked
/// });
///
/// assert_eq!(result, (1..=10).product()); // 3628800
/// ```
/// A non-blocking executor-future-park state machine.
///
/// All executor operations are ultimately implemented with `Step`. It allows fine-grained
/// control over execution and control flow. `Step` can only perform one poll step at a time
/// and requires a pinned future. A `Step` object is created by calling [`Executor::step()`].
///
/// See [`Executor::block_on()`] for a blocking runner.
/// A request to park the executor.
///
/// Parking is the mechanism by which the executor *tries* to wait for external event sources when
/// no signal in the wakeup set is currently raised (see [`Signals`]). The executor might
/// nonetheless resume immediately if a signal is raised before the atomic part of the *park
/// protocol* takes place. Park functions implement the park protocol and must follow it strictly,
/// **you risk deadlocks otherwise**.
///
/// # The park protocol
///
/// - First, the executor determines that further progress is unlikely at this moment. The
/// specifics of this process are implementation details that should not be relied upon.
///
/// - The park function is called with a `Park` parameter.
///
/// - The park function enters a context wherein no external events may influence a correct
/// decision to sleep or not. For example, a park function that does not sleep at all does
/// not need to do anything here, since no external event can incorrectly change that
/// behavior. On the other hand, a park function that halts until a hardware interrupt occurs
/// would need to enter an interrupt-free context to avoid deadlocks.
///
/// - The park function calls [`Park::race_free()`] while still in the event-safe context.
/// This produces a [`Parked`] value that serves as proof of the call to `race_free()`.
///
/// - If the park function intends to block or sleep, then it must first call
/// [`Parked::is_idle()`]. It may be allowed to sleep only if that function returns `true`.
///
/// - If the park function is willing to sleep and is allowed to do so, it must
/// atomically exit the event-safe context whilst entering the sleep state. A deadlock is
/// again possible if both operations are not done atomically with respect to each other
/// (**only for blocking runners, see below**).
///
/// - If the park function sleeps, this state should be automatically exited when an external
/// event occurs.
///
/// - The park function returns its [`Parked`] token.
///
/// - The executor resumes.
///
/// # Delegating out of the park function
///
/// Blocking runners, such as [`Executor::block_on()`], require that the park function's
/// event-safe context be exited in an atomic manner with respect to the start of whatever
/// blocking operation. However, this requirement does not hold for [`Step`] **as long as
/// the park function never exits the event-safe context and it itself never blocks**. Since
/// [`Step::poll()`] will return after parking, the caller can perform potentially-blocking
/// operations from the event-safe context. It must still release it atomically if it will
/// sleep, though. With this technique it is even possible for the `poll()` caller to be an
/// external event source.
/// Proof of parking.
///
/// Park functions return `Parked` objects as a proof of having called [`Park::race_free()`]. This
/// is necessary because [`Park::race_free()`] updates executor state and must always be run.
/// `Parked` can be used by park functions to determine whether blocking or sleeping is
/// permissible. See [`Park`] documentation for the correct parking protocol.