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
use crate::vm::Vm;
use std::cell::RefCell;
use std::future::Future;
use std::pin::Pin;
use std::ptr::NonNull;
use std::task::{Context, Poll};
thread_local!(static VM: RefCell<Option<NonNull<Vm>>> = RefCell::new(None));
struct Guard<'a>(&'a RefCell<Option<NonNull<Vm>>>, Option<NonNull<Vm>>);
impl Drop for Guard<'_> {
fn drop(&mut self) {
if let Some(vm) = self.1.take() {
*self.0.borrow_mut() = Some(vm);
}
}
}
pub fn inject_vm<F, O>(vm: &mut Vm, f: F) -> O
where
F: FnOnce() -> O,
{
let vm = unsafe { NonNull::new_unchecked(vm) };
VM.with(|storage| {
let old_vm = storage.borrow_mut().replace(vm);
let _guard = Guard(&storage, old_vm);
f()
})
}
pub fn with_vm<F, O>(f: F) -> O
where
F: FnOnce(&mut Vm) -> O,
{
VM.with(|storage| {
let mut b = storage.borrow_mut().expect("vm must be available");
f(unsafe { b.as_mut() })
})
}
pub struct InjectVm<'vm, T> {
vm: &'vm mut Vm,
future: T,
}
impl<'vm, T> InjectVm<'vm, T> {
pub unsafe fn new(vm: &'vm mut Vm, future: T) -> Self {
Self { vm, future }
}
}
impl<'vm, T> Future for InjectVm<'vm, T>
where
T: Future,
{
type Output = T::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
unsafe {
let this = Pin::into_inner_unchecked(self);
let future = Pin::new_unchecked(&mut this.future);
inject_vm(this.vm, || future.poll(cx))
}
}
}