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
use core::{
fmt,
future::Future,
num::NonZeroUsize,
pin::Pin,
task::{Context, Poll},
};
use futures::stream::Stream;
#[derive(Debug)]
pub struct TimerOverflow;
pub trait Timer: Send {
type Stop: TimerStop;
fn sleep(&mut self, duration: u32) -> TimerSleep<'_, Self::Stop>;
fn interval(
&mut self,
duration: u32,
) -> TimerInterval<'_, Self::Stop, Result<NonZeroUsize, TimerOverflow>>;
fn interval_skip(&mut self, duration: u32) -> TimerInterval<'_, Self::Stop, NonZeroUsize>;
}
pub trait TimerStop: Send {
fn stop(&mut self);
}
pub struct TimerSleep<'a, T: TimerStop> {
stop: &'a mut T,
future: Pin<Box<dyn Future<Output = ()> + Send + 'a>>,
}
pub struct TimerInterval<'a, T: TimerStop, I> {
stop: &'a mut T,
stream: Pin<Box<dyn Stream<Item = I> + Send + 'a>>,
}
impl<'a, T: TimerStop> TimerSleep<'a, T> {
pub fn new(stop: &'a mut T, future: Pin<Box<dyn Future<Output = ()> + Send + 'a>>) -> Self {
Self { stop, future }
}
}
impl<'a, T: TimerStop> Future for TimerSleep<'a, T> {
type Output = ();
#[inline]
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
self.future.as_mut().poll(cx)
}
}
impl<'a, T: TimerStop> Drop for TimerSleep<'a, T> {
#[inline]
fn drop(&mut self) {
self.stop.stop();
}
}
impl<'a, T: TimerStop, I> TimerInterval<'a, T, I> {
pub fn new(stop: &'a mut T, stream: Pin<Box<dyn Stream<Item = I> + Send + 'a>>) -> Self {
Self { stop, stream }
}
#[inline]
pub fn stop(mut self: Pin<&mut Self>) {
self.stop.stop();
}
}
impl<'a, T: TimerStop, I> Stream for TimerInterval<'a, T, I> {
type Item = I;
#[inline]
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<I>> {
self.stream.as_mut().poll_next(cx)
}
}
impl<'a, T: TimerStop, I> Drop for TimerInterval<'a, T, I> {
#[inline]
fn drop(&mut self) {
self.stop.stop();
}
}
impl fmt::Display for TimerOverflow {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Timer stream overflow.")
}
}