-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaux.txt
560 lines (461 loc) · 13.8 KB
/
aux.txt
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
//! Async runtime for functionality crossing multiple ticks
use std::cell::RefCell;
use std::collections::VecDeque;
use std::hint::unreachable_unchecked;
use std::ops::{Deref, DerefMut};
use std::rc::{Rc, Weak};
use std::sync::atomic::{AtomicBool, Ordering};
use std::task::Poll;
use cooked_waker::{IntoWaker, ViaRawPointer, Wake, WakeRef};
use futures::channel::oneshot::Sender;
use futures::future::LocalBoxFuture;
use futures::prelude::*;
use futures::task::Context;
/// Task must be manually readied up by runtime
#[derive(Default)]
pub struct ParkUntilWakeupFuture(ParkState);
#[derive(Copy, Clone, Debug, Default)]
enum ParkState {
#[default]
Unpolled,
Parked,
Complete,
}
impl Future for ParkUntilWakeupFuture {
type Output = ();
fn poll(mut self: std::pin::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"),
}
}
}
#[derive(Debug)]
struct RuntimeInner {
ready: Vec<WeakTaskRef>,
/// Swapped out with `ready` during tick
ready_double_buf: Vec<WeakTaskRef>,
next_task: TaskHandle,
/// Stores all triggered events for use by e2e tests
#[cfg(feature = "testing")]
event_log: Vec<crate::event::EntityEvent>,
}
#[derive(Clone, Debug)]
pub struct Runtime(std::rc::Rc<std::cell::RefCell<RuntimeInner>>);
#[derive(Eq, PartialEq, Copy, Clone, Default, Debug)]
pub struct TaskHandle(u64);
type BoxedResult<T> = Result<T, Box<dyn std::error::Error>>;
pub struct Peepee<T>(LocalBoxFuture<'static, T>);
impl <T> std::fmt::Debug for Peepee<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LocalBoxFuture")
.field("type", &std::any::type_name::<T>())
.finish()
}
}
impl <T> Deref for Peepee<T> {
type Target = LocalBoxFuture<'static, T>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl <T> DerefMut for Peepee<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[derive(Debug)]
pub enum TaskFuture {
Running(Peepee<BoxedResult<()>>),
Polling,
Done(TaskResult),
DoneButConsumed,
}
#[derive(Debug)]
pub enum TaskResult {
Cancelled,
Finished(BoxedResult<()>),
}
#[derive(Debug)]
pub struct Task {
runtime: Runtime,
handle: TaskHandle,
future: RefCell<TaskFuture>,
// TODO reuse/share/pool this allocation between tasks, maybe own it in the runtime
//event_sink: RefCell<VecDeque<EntityEvent>>,
ready: AtomicBool,
}
impl Drop for Task {
fn drop(&mut self) {
println!("dropping task {:?}", self.handle);
}
}
#[derive(Clone, Debug)]
pub struct TaskRef(std::rc::Rc<Task>);
#[derive(Debug)]
pub struct WeakTaskRef(Weak<Task>);
// everything will run on the main thread
unsafe impl Send for TaskRef {}
unsafe impl Sync for TaskRef {}
unsafe impl Send for WeakTaskRef {}
unsafe impl Sync for WeakTaskRef {}
impl Runtime {
pub fn spawn(&self, gimme_task_ref: Sender<TaskRef>, future: impl Future<Output = BoxedResult<()>> + 'static,) -> TaskRef {
let mut runtime = self.0.borrow_mut();
let task = Task {
runtime: self.clone(),
handle: runtime.next_task_handle(),
future: RefCell::new(TaskFuture::Running(Peepee(future.boxed_local()))),
//event_sink: RefCell::new(VecDeque::new()),
ready: AtomicBool::new(false),
};
let task = TaskRef(Rc::new(task));
// send task ref to future
let _ = gimme_task_ref.send(task.clone());
// task is ready immediately
runtime.ready.push(task.weak());
task.0.ready.store(true, Ordering::Relaxed);
task
}
/// Polls all ready tasks
pub fn tick(&self) {
let mut runtime = self.0.borrow_mut();
if !runtime.ready.is_empty() {
println!("{} ready tasks", runtime.ready.len());
}
// temporarily move ready tasks out of runtime so we can release the mutable ref
let mut ready_tasks = {
let to_consume = std::mem::take(&mut runtime.ready);
// use cached double buf allocation for any tasks readied up during tick
let runtime = &mut *runtime; // pls borrowck
std::mem::swap(&mut runtime.ready, &mut runtime.ready_double_buf);
debug_assert!(runtime.ready.is_empty());
to_consume
};
drop(runtime);
for task in ready_tasks.drain(..).filter_map(|t| t.upgrade()) {
let was_ready = task.0.ready.swap(false, Ordering::Relaxed);
debug_assert!(was_ready, "task should've been ready but wasn't");
task.poll_task();
}
// swap ready list back
let mut runtime = self.0.borrow_mut();
let mut double_buf = std::mem::replace(&mut runtime.ready, ready_tasks);
// move any newly ready tasks into proper ready queue out of double buf
runtime.ready.append(&mut double_buf);
// store double buf allocation again
let dummy = std::mem::replace(&mut runtime.ready_double_buf, double_buf);
debug_assert!(dummy.is_empty());
std::mem::forget(dummy);
}
/// Can be called multiple times
pub fn mark_ready(&self, task: &TaskRef) {
//println!("marking task as ready"; "task" => ?task.handle());
if !task.0.ready.swap(true, Ordering::Relaxed) {
debug_assert!(
!self.is_ready(task.handle()),
"task handle ready flag is wrong, should be not ready"
);
self.0.borrow_mut().ready.push(task.weak());
} else {
debug_assert!(
self.is_ready(task.handle()),
"task handle ready flag is wrong, should be ready"
);
}
}
fn is_ready(&self, task: TaskHandle) -> bool {
self.find_ready(task).is_some()
}
fn find_ready(&self, task: TaskHandle) -> Option<usize> {
self.0
.borrow()
.ready
.iter()
.filter_map(|t| t.upgrade())
.position(|t| t.handle() == task)
}
}
#[cfg(feature = "testing")]
impl Runtime {
pub fn post_events(&self, events: impl Iterator<Item = EntityEvent>) {
let mut inner = self.0.borrow_mut();
inner.event_log.extend(events);
}
/// Only used in tests, so allocation waste doesn't matter
pub fn event_log(&self) -> Vec<EntityEvent> {
let inner = self.0.borrow();
inner.event_log.clone()
}
pub fn clear_event_log(&self) {
let mut inner = self.0.borrow_mut();
inner.event_log.clear();
}
}
impl RuntimeInner {
fn next_task_handle(&mut self) -> TaskHandle {
let this = self.next_task;
self.next_task.0 += 1;
this
}
}
impl Default for Runtime {
fn default() -> Self {
let inner = RefCell::new(RuntimeInner {
ready: Vec::with_capacity(128),
ready_double_buf: Vec::with_capacity(128),
next_task: TaskHandle::default(),
#[cfg(feature = "testing")]
event_log: Vec::new(),
});
Runtime(Rc::new(inner))
}
}
impl TaskRef {
pub fn is_finished(&self) -> bool {
let fut = self.0.future.borrow();
match &*fut {
TaskFuture::DoneButConsumed | TaskFuture::Done(_) => true,
TaskFuture::Running(_) => false,
TaskFuture::Polling => unreachable!(),
}
}
/// Call once only, panics the second time
pub fn result(&self) -> Option<TaskResult> {
let mut fut = self.0.future.borrow_mut();
match &*fut {
TaskFuture::Running(_) => None,
TaskFuture::Polling => unreachable!(),
TaskFuture::DoneButConsumed => panic!("result has already been consumed"),
TaskFuture::Done(_) => {
let done = std::mem::replace(&mut *fut, TaskFuture::DoneButConsumed);
let result = match done {
TaskFuture::Done(res) => res,
_ => unsafe { unreachable_unchecked() }, // already checked
};
Some(result)
}
}
}
pub fn is_ready(&self) -> bool {
self.0.ready.load(Ordering::Relaxed)
}
/// Only wakes up when the runtime manually wakes it up via event
pub async fn park_until_triggered(&self) {
ParkUntilWakeupFuture::default().await
}
pub fn cancel(self) {
let mut fut = self.0.future.borrow_mut();
match &mut *fut {
TaskFuture::Running(_) => {
//trace!("cancelling task {:?}", self.0.handle);
// drop future
*fut = TaskFuture::Done(TaskResult::Cancelled);
}
TaskFuture::Done(res) => {
// consume
//debug!("cancelling finished task {:?}, consuming result", self.0.handle; "result" => ?res);
*fut = TaskFuture::Done(TaskResult::Cancelled);
}
TaskFuture::Polling => unreachable!("task is in invalid state"),
TaskFuture::DoneButConsumed => {
drop(fut);
//warn!("cancelling task that's already consumed"; "task" => ?self.0);
}
}
}
fn poll_task(self) {
let mut fut_slot = self.0.future.borrow_mut();
// take ownership for poll
let fut = std::mem::replace(&mut *fut_slot, TaskFuture::Polling);
if let TaskFuture::Running(mut fut) = fut {
// TODO reimplement raw waiter manually to avoid this unconditional clone
let waker = self.clone().into_waker();
let mut ctx = Context::from_waker(&waker);
//trace!("polling task"; "task" => ?self.0.handle);
match fut.as_mut().poll(&mut ctx) {
Poll::Ready(result) => {
//trace!("task is complete"; "task" => ?self.0.handle, "result" => ?result);
*fut_slot = TaskFuture::Done(TaskResult::Finished(result));
}
Poll::Pending => {
//trace!("task is still ongoing"; "task" => ?self.0.handle);
*fut_slot = TaskFuture::Running(fut);
}
}
}
}
// pub fn push_event(&self, event: EntityEvent) {
// self.0.event_sink.borrow_mut().push_back(event);
// }
// pub fn pop_event(&self) -> Option<EntityEvent> {
// self.0.event_sink.borrow_mut().pop_front()
// }
pub fn handle(&self) -> TaskHandle {
self.0.handle
}
pub fn weak(&self) -> WeakTaskRef {
WeakTaskRef(Rc::downgrade(&self.0))
}
}
impl WeakTaskRef {
pub fn upgrade(&self) -> Option<TaskRef> {
self.0.upgrade().map(TaskRef)
}
#[cfg(test)]
pub fn dangling() -> Self {
Self(Weak::default())
}
}
impl WakeRef for TaskRef {
fn wake_by_ref(&self) {
self.0.runtime.mark_ready(self);
}
}
impl Wake for TaskRef {}
unsafe impl ViaRawPointer for TaskRef {
type Target = Task;
fn into_raw(self) -> *mut Task {
Rc::into_raw(self.0) as *mut Task
}
unsafe fn from_raw(ptr: *mut Task) -> Self {
Self(Rc::from_raw(ptr as *const Task))
}
}
#[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
}
}
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicBool, Ordering};
use futures::channel::oneshot::channel;
//use common::bumpalo::core_alloc::sync::Arc;
use super::*;
#[test]
fn basic_operation() {
let runtime = Runtime::default();
let fut = manual::ManualFuture::default();
let it_worked = std::sync::Arc::new(AtomicBool::new(false));
let (tx, rx) = channel();
let fut2 = fut.clone();
let it_worked2 = it_worked.clone();
let task = runtime.spawn(tx, async move {
let _taskref = rx.await.unwrap();
let msg = fut2.await;
it_worked2.store(true, Ordering::Relaxed);
Ok(())
});
assert!(!task.is_finished());
for _ in 0..4 {
runtime.tick();
assert!(!task.is_finished());
}
fut.trigger("nice");
assert!(!task.is_finished());
for _ in 0..2 {
runtime.tick();
}
assert!(task.is_finished());
assert!(it_worked.load(Ordering::Relaxed), "future did not complete");
}
}
pub struct SystemHandle(u32);
pub trait System {
fn as_any(&mut self) -> &mut dyn std::any::Any;
}
pub struct Orchestrator {
}
impl Orchestrator {
pub fn new() -> Orchestrator {
Orchestrator {}
}
pub fn initialize(&self) {}
pub fn deinitialize(&self) {}
pub fn update(&self) {}
pub fn add_system<T>(&mut self, system: T) -> SystemHandle {
SystemHandle(0)
}
pub fn get_system(&self, system_handle: SystemHandle) -> Option<&dyn System> {
todo!()
}
}