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
use std::{
pin::Pin,
task::{Context, Poll},
};
use tokio::{
stream::Stream,
sync::watch::{self, Receiver, Sender},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Control {
Shutdown,
Kill,
}
pub struct Controller {
sender: Sender<Control>,
receiver: Receiver<Control>,
}
pub struct ControlReader {
receiver: Receiver<Control>,
}
impl Controller {
#[allow(clippy::new_without_default)]
pub async fn new() -> Self {
let (sender, mut receiver) = watch::channel(Control::Kill);
let _ = receiver.recv().await;
Controller { sender, receiver }
}
pub fn reader(&self) -> ControlReader {
ControlReader {
receiver: self.receiver.clone(),
}
}
pub fn send(&mut self, control: Control) {
if self.sender.broadcast(control).is_err() {
unsafe { std::hint::unreachable_unchecked() }
}
}
pub async fn reset(&mut self) -> ControlReader {
let mut reader = self.reader();
self.send(Control::Kill);
if reader.updated().await.is_none() {
unsafe { std::hint::unreachable_unchecked() }
}
reader
}
}
impl ControlReader {
pub async fn updated(&mut self) -> Option<Control> {
self.receiver.recv().await
}
}
impl Stream for ControlReader {
type Item = Control;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.get_mut().receiver).poll_next(cx)
}
}