Welcome to mirror list, hosted at ThFree Co, Russian Federation.

timer.rs « executor « runtime « src « threadshare « generic - gitlab.freedesktop.org/gstreamer/gst-plugins-rs.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 079c7a9ef63f0737fec6577190a12ea36e262e89 (plain)
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
// This is based on https://github.com/smol-rs/async-io
// with adaptations by:
//
// Copyright (C) 2021 François Laignel <fengalin@free.fr>
//
// Take a look at the license at the top of the repository in the LICENSE file.

use futures::stream::Stream;

use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll, Waker};
use std::time::{Duration, Instant};

use super::Reactor;

/// A future or stream that emits timed events.
///
/// Timers are futures that output a single [`Instant`] when they fire.
///
/// Timers are also streams that can output [`Instant`]s periodically.
#[derive(Debug)]
pub struct Timer {
    /// This timer's ID and last waker that polled it.
    ///
    /// When this field is set to `None`, this timer is not registered in the reactor.
    id_and_waker: Option<(usize, Waker)>,

    /// The next instant at which this timer fires.
    when: Instant,

    /// The period.
    period: Duration,
}

impl Timer {
    /// Creates a timer that emits an event once after the given duration of time.
    ///
    /// When throttling is activated (i.e. when using a non-`0` `wait`
    /// duration in `Context::acquire`), timer entries are assigned to
    /// the nearest time frame, meaning that the delay might elapse
    /// `wait` / 2 ms earlier or later than the expected instant.
    ///
    /// Use [`Timer::after_at_least`] when it's preferable not to return
    /// before the expected instant.
    pub fn after(duration: Duration) -> Timer {
        Timer::at(Instant::now() + duration)
    }

    /// Creates a timer that emits an event once after the given duration of time.
    ///
    /// See [`Timer::after`] for details. The event won't be emitted before
    /// the expected delay has elapsed.
    #[track_caller]
    pub fn after_at_least(duration: Duration) -> Timer {
        Timer::at_least_at(Instant::now() + duration)
    }

    /// Creates a timer that emits an event once at the given time instant.
    ///
    /// When throttling is activated (i.e. when using a non-`0` `wait`
    /// duration in `Context::acquire`), timer entries are assigned to
    /// the nearest time frame, meaning that the delay might elapse
    /// `wait` / 2 ms earlier or later than the expected instant.
    ///
    /// Use [`Timer::at_least_at`] when it's preferable not to return
    /// before the expected instant.
    pub fn at(instant: Instant) -> Timer {
        Timer::interval_at(instant, Duration::MAX)
    }

    /// Creates a timer that emits an event once at the given time instant.
    ///
    /// See [`Timer::at`] for details. The event won't be emitted before
    /// the expected delay has elapsed.
    #[track_caller]
    pub fn at_least_at(instant: Instant) -> Timer {
        Timer::interval_at_least_at(instant, Duration::MAX)
    }

    /// Creates a timer that emits events periodically.
    pub fn interval(period: Duration) -> Timer {
        Timer::interval_at(Instant::now() + period, period)
    }

    /// Creates a timer that emits events periodically, starting after `delay`.
    ///
    /// When throttling is activated (i.e. when using a non-`0` `wait`
    /// duration in `Context::acquire`), timer entries are assigned to
    /// the nearest time frame, meaning that the delay might elapse
    /// `wait` / 2 ms earlier or later than the expected instant.
    pub fn interval_delayed_by(delay: Duration, period: Duration) -> Timer {
        Timer::interval_at(Instant::now() + delay, period)
    }

    /// Creates a timer that emits events periodically, starting at `start`.
    ///
    /// When throttling is activated (i.e. when using a non-`0` `wait`
    /// duration in `Context::acquire`), timer entries are assigned to
    /// the nearest time frame, meaning that the delay might elapse
    /// `wait` / 2 ms earlier or later than the expected instant.
    ///
    /// Use [`Timer::interval_at_least_at`] when it's preferable not to return
    /// before the expected instant.
    pub fn interval_at(start: Instant, period: Duration) -> Timer {
        Timer {
            id_and_waker: None,
            when: start,
            period,
        }
    }

    /// Creates a timer that emits events periodically, starting at `start`.
    ///
    /// See [`Timer::interval_at`] for details. The event won't be emitted before
    /// the expected delay has elapsed.
    #[track_caller]
    pub fn interval_at_least_at(start: Instant, period: Duration) -> Timer {
        Timer {
            id_and_waker: None,
            when: start + Reactor::with(|reactor| reactor.half_max_throttling()),
            period,
        }
    }

    /// Sets the timer to emit an en event once after the given duration of time.
    ///
    /// Note that resetting a timer is different from creating a new timer because
    /// [`set_after()`][`Timer::set_after()`] does not remove the waker associated with the task
    /// that is polling the timer.
    pub fn set_after(&mut self, duration: Duration) {
        self.set_at(Instant::now() + duration);
    }

    /// Sets the timer to emit an event once at the given time instant.
    ///
    /// Note that resetting a timer is different from creating a new timer because
    /// [`set_at()`][`Timer::set_at()`] does not remove the waker associated with the task
    /// that is polling the timer.
    pub fn set_at(&mut self, instant: Instant) {
        Reactor::with_mut(|reactor| {
            if let Some((id, _)) = self.id_and_waker.as_ref() {
                // Deregister the timer from the reactor.
                reactor.remove_timer(self.when, *id);
            }

            // Update the timeout.
            self.when = instant;

            if let Some((id, waker)) = self.id_and_waker.as_mut() {
                // Re-register the timer with the new timeout.
                *id = reactor.insert_timer(self.when, waker);
            }
        })
    }

    /// Sets the timer to emit events periodically.
    ///
    /// Note that resetting a timer is different from creating a new timer because
    /// [`set_interval()`][`Timer::set_interval()`] does not remove the waker associated with the
    /// task that is polling the timer.
    pub fn set_interval(&mut self, period: Duration) {
        self.set_interval_at(Instant::now() + period, period);
    }

    /// Sets the timer to emit events periodically, starting at `start`.
    ///
    /// Note that resetting a timer is different from creating a new timer because
    /// [`set_interval_at()`][`Timer::set_interval_at()`] does not remove the waker associated with
    /// the task that is polling the timer.
    pub fn set_interval_at(&mut self, start: Instant, period: Duration) {
        // Note: the timer might have been registered on an Executor and then transfered to another.
        Reactor::with_mut(|reactor| {
            if let Some((id, _)) = self.id_and_waker.as_ref() {
                // Deregister the timer from the reactor.
                reactor.remove_timer(self.when, *id);
            }

            self.when = start;
            self.period = period;

            if let Some((id, waker)) = self.id_and_waker.as_mut() {
                // Re-register the timer with the new timeout.
                *id = reactor.insert_timer(self.when, waker);
            }
        })
    }
}

impl Drop for Timer {
    fn drop(&mut self) {
        if let Some((id, _)) = self.id_and_waker.take() {
            Reactor::with_mut(|reactor| {
                reactor.remove_timer(self.when, id);
            });
        }
    }
}

impl Future for Timer {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        match self.poll_next(cx) {
            Poll::Ready(Some(_)) => Poll::Ready(()),
            Poll::Pending => Poll::Pending,
            Poll::Ready(None) => unreachable!(),
        }
    }
}

impl Stream for Timer {
    type Item = ();

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Reactor::with_mut(|reactor| {
            if Instant::now() + reactor.half_max_throttling() >= self.when {
                if let Some((id, _)) = self.id_and_waker.take() {
                    // Deregister the timer from the reactor.
                    reactor.remove_timer(self.when, id);
                }
                let when = self.when;
                if let Some(next) = when.checked_add(self.period) {
                    self.when = next;
                    // Register the timer in the reactor.
                    let id = reactor.insert_timer(self.when, cx.waker());
                    self.id_and_waker = Some((id, cx.waker().clone()));
                }

                Poll::Ready(Some(()))
            } else {
                match &self.id_and_waker {
                    None => {
                        // Register the timer in the reactor.
                        let id = reactor.insert_timer(self.when, cx.waker());
                        self.id_and_waker = Some((id, cx.waker().clone()));
                    }
                    Some((id, w)) if !w.will_wake(cx.waker()) => {
                        // Deregister the timer from the reactor to remove the old waker.
                        reactor.remove_timer(self.when, *id);

                        // Register the timer in the reactor with the new waker.
                        let id = reactor.insert_timer(self.when, cx.waker());
                        self.id_and_waker = Some((id, cx.waker().clone()));
                    }
                    Some(_) => {}
                }

                Poll::Pending
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use std::time::{Duration, Instant};

    use super::Timer;
    use crate::runtime::executor::Scheduler;

    const MAX_THROTTLING: Duration = Duration::from_millis(10);
    const DELAY: Duration = Duration::from_millis(12);

    #[test]
    fn delay_for() {
        gst::init().unwrap();

        let handle = Scheduler::start("delay_for", MAX_THROTTLING);

        let elapsed = futures::executor::block_on(handle.spawn(async {
            let now = Instant::now();
            Timer::after(DELAY).await;
            now.elapsed()
        }))
        .unwrap();

        // Due to throttling, timer may be fired earlier
        assert!(elapsed + MAX_THROTTLING / 2 >= DELAY);
    }

    #[test]
    fn delay_for_at_least() {
        gst::init().unwrap();

        let handle = Scheduler::start("delay_for_at_least", MAX_THROTTLING);

        let elapsed = futures::executor::block_on(handle.spawn(async {
            let now = Instant::now();
            Timer::after_at_least(DELAY).await;
            now.elapsed()
        }))
        .unwrap();

        // Never returns earlier than DELAY
        assert!(elapsed >= DELAY);
    }

    #[test]
    fn interval() {
        use futures::prelude::*;

        gst::init().unwrap();

        let handle = Scheduler::start("interval", MAX_THROTTLING);

        let join_handle = handle.spawn(async move {
            let start = Instant::now();
            let mut interval = Timer::interval(DELAY);

            interval.next().await;
            // Due to throttling, timer may be fired earlier
            assert!(start.elapsed() + MAX_THROTTLING / 2 >= DELAY);

            interval.next().await;
            // Due to throttling, timer may be fired earlier
            assert!(start.elapsed() + MAX_THROTTLING >= 2 * DELAY);
        });

        futures::executor::block_on(join_handle).unwrap();
    }
}