-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathfutures.rs
More file actions
193 lines (166 loc) 路 5.16 KB
/
Copy pathfutures.rs
File metadata and controls
193 lines (166 loc) 路 5.16 KB
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
use crate::event::{RuntimeTimers, TimerToken};
use crate::{ComponentWorld, EcsWorld, Tick};
use common::*;
use futures::future::FusedFuture;
use futures::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
pub struct TimerFuture<'w> {
end_tick: Tick,
/// For cancelling on drop
token: TimerToken,
world: Pin<&'w EcsWorld>,
}
// only used on main thread
unsafe impl Send for TimerFuture<'_> {}
/// Task must be manually readied up by runtime
pub struct ParkUntilWakeupFuture(ParkState);
#[derive(Copy, Clone, Debug)]
enum ParkState {
Unpolled,
Parked,
Complete,
}
impl Future for ParkUntilWakeupFuture {
type Output = ();
fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
match self.0 {
ParkState::Unpolled => {
// first call
self.0 = ParkState::Parked;
// intentionally does use waker - this will be done by the runtime
Poll::Pending
}
ParkState::Parked => {
// woken up
self.0 = ParkState::Complete;
Poll::Ready(())
}
ParkState::Complete => unreachable!("task has already been unparked"),
}
}
}
impl<'w> TimerFuture<'w> {
pub fn new(end_tick: Tick, token: TimerToken, world: Pin<&'w EcsWorld>) -> Self {
Self {
token,
end_tick,
world,
}
}
fn elapsed(&self) -> bool {
let now = Tick::fetch();
now.value() >= self.end_tick.value()
}
}
impl Drop for TimerFuture<'_> {
fn drop(&mut self) {
if !self.elapsed() {
trace!(
"cancelling timer {:?} due to task dropping before trigger",
self.token
);
let timers = self.world.resource_mut::<RuntimeTimers>();
if !timers.cancel(self.token) {
warn!("failed to cancel timer {:?} (already elapsed?)", self.token);
}
}
}
}
impl Future for TimerFuture<'_> {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if self.elapsed() {
cx.waker().wake_by_ref();
Poll::Ready(())
} else {
Poll::Pending
}
}
}
impl FusedFuture for ParkUntilWakeupFuture {
fn is_terminated(&self) -> bool {
// futures::future::Fuse will poll this once too many and mark as always Complete when it
// isn't really. implementing this manually avoids this special case and removes extra
// polls
!matches!(self.0, ParkState::Unpolled)
}
}
impl Default for ParkUntilWakeupFuture {
fn default() -> Self {
Self(ParkState::Unpolled)
}
}
#[cfg(test)]
pub mod manual {
use std::cell::RefCell;
use std::future::Future;
use std::mem::MaybeUninit;
use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll, Waker};
/// Beware, contains allocation
#[derive(Clone)]
pub struct ManualFuture<V>(Rc<RefCell<ManualFutureInner<V>>>);
#[derive(Copy, Clone)]
enum TriggerStatus {
NotTriggered,
Triggered,
Cancelled,
}
struct ManualFutureInner<V> {
state: TriggerStatus,
waker: Option<Waker>,
value: MaybeUninit<V>,
}
// only used on main thread
unsafe impl<V> Send for ManualFuture<V> {}
impl<V> Default for ManualFuture<V> {
fn default() -> Self {
Self(Rc::new(RefCell::new(ManualFutureInner {
state: TriggerStatus::NotTriggered,
waker: None,
value: MaybeUninit::uninit(),
})))
}
}
impl<V> Drop for ManualFutureInner<V> {
fn drop(&mut self) {
if matches!(self.state, TriggerStatus::Triggered) {
// safety: value was initialised on trigger and not consumed
unsafe { std::ptr::drop_in_place(self.value.as_mut_ptr()) }
}
}
}
impl<V> ManualFuture<V> {
pub fn trigger(&self, val: V) {
let mut inner = self.0.borrow_mut();
inner.value = MaybeUninit::new(val);
inner.state = TriggerStatus::Triggered;
inner
.waker
.take()
.expect("waker not set for triggered event")
.wake();
}
fn state(&self) -> TriggerStatus {
self.0.borrow().state
}
}
impl<V> Future for ManualFuture<V> {
type Output = V;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut inner = self.0.borrow_mut();
if let TriggerStatus::Triggered = inner.state {
inner.state = TriggerStatus::Cancelled; // dont drop value again in destructor
let val = std::mem::replace(&mut inner.value, MaybeUninit::uninit());
// safety: value is initialised on trigger
let val = unsafe { val.assume_init() };
Poll::Ready(val)
} else {
inner.waker = Some(cx.waker().clone());
Poll::Pending
}
}
}
}