-
Notifications
You must be signed in to change notification settings - Fork 208
/
test_async.rs
99 lines (81 loc) · 2.52 KB
/
test_async.rs
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
use std::cell::RefCell;
use gdnative::prelude::*;
use gdnative::tasks::{Async, AsyncMethod, Spawner};
pub(crate) fn run_tests() -> bool {
// Relevant tests in GDScript
true
}
thread_local! {
static EXECUTOR: &'static SharedLocalPool = {
Box::leak(Box::new(SharedLocalPool::default()))
};
}
pub(crate) fn register(handle: InitHandle) {
gdnative::tasks::register_runtime(&handle);
gdnative::tasks::set_executor(EXECUTOR.with(|e| *e));
handle.add_class::<AsyncMethods>();
handle.add_class::<AsyncExecutorDriver>();
}
#[derive(Default)]
struct SharedLocalPool {
pool: RefCell<futures::executor::LocalPool>,
}
impl futures::task::LocalSpawn for SharedLocalPool {
fn spawn_local_obj(
&self,
future: futures::task::LocalFutureObj<'static, ()>,
) -> Result<(), futures::task::SpawnError> {
self.pool.borrow_mut().spawner().spawn_local_obj(future)
}
}
#[derive(NativeClass)]
#[inherit(Node)]
struct AsyncExecutorDriver;
impl AsyncExecutorDriver {
fn new(_owner: &Node) -> Self {
AsyncExecutorDriver
}
}
#[methods]
impl AsyncExecutorDriver {
#[export]
fn _process(&self, _owner: &Node, _delta: f64) {
EXECUTOR.with(|e| e.pool.borrow_mut().run_until_stalled());
}
}
#[derive(NativeClass)]
#[inherit(Reference)]
#[register_with(register_methods)]
struct AsyncMethods;
#[methods]
impl AsyncMethods {
fn new(_owner: TRef<Reference>) -> Self {
AsyncMethods
}
}
struct ResumeAddFn;
impl AsyncMethod<AsyncMethods> for ResumeAddFn {
fn spawn_with(&self, spawner: Spawner<'_, AsyncMethods>) {
spawner.spawn(|ctx, _this, mut args| {
let a = args.read::<i32>().get().unwrap();
let obj = args.read::<Ref<Object>>().get().unwrap();
let name = args.read::<GodotString>().get().unwrap();
async move {
let b = ctx.until_resume().await;
let b = i32::from_variant(&b).unwrap();
let c = unsafe { obj.assume_safe().call(name, &[]) };
let c = Ref::<Reference>::from_variant(&c).unwrap();
let c = unsafe { c.assume_safe() };
let c = ctx.signal(c, "completed").unwrap().await;
assert_eq!(1, c.len());
let c = i32::from_variant(&c[0]).unwrap();
(a + b + c).to_variant()
}
});
}
}
fn register_methods(builder: &ClassBuilder<AsyncMethods>) {
builder
.build_method("resume_add", Async::new(ResumeAddFn))
.done();
}