]>
Commit | Line | Data |
---|---|---|
a1dfa0c6 XL |
1 | //! Closure type (equivalent to `&mut dyn FnMut(A) -> R`) that's `repr(C)`. |
2 | ||
04454e1e FG |
3 | use std::marker::PhantomData; |
4 | ||
a1dfa0c6 XL |
5 | #[repr(C)] |
6 | pub struct Closure<'a, A, R> { | |
04454e1e FG |
7 | call: unsafe extern "C" fn(*mut Env, A) -> R, |
8 | env: *mut Env, | |
923072b8 FG |
9 | // Prevent Send and Sync impls. `!Send`/`!Sync` is the usual way of doing |
10 | // this, but that requires unstable features. rust-analyzer uses this code | |
11 | // and avoids unstable features. | |
12 | // | |
13 | // The `'a` lifetime parameter represents the lifetime of `Env`. | |
04454e1e | 14 | _marker: PhantomData<*mut &'a mut ()>, |
a1dfa0c6 XL |
15 | } |
16 | ||
04454e1e | 17 | struct Env; |
a1dfa0c6 XL |
18 | |
19 | impl<'a, A, R, F: FnMut(A) -> R> From<&'a mut F> for Closure<'a, A, R> { | |
20 | fn from(f: &'a mut F) -> Self { | |
04454e1e | 21 | unsafe extern "C" fn call<A, R, F: FnMut(A) -> R>(env: *mut Env, arg: A) -> R { |
a1dfa0c6 XL |
22 | (*(env as *mut _ as *mut F))(arg) |
23 | } | |
04454e1e | 24 | Closure { call: call::<A, R, F>, env: f as *mut _ as *mut Env, _marker: PhantomData } |
a1dfa0c6 XL |
25 | } |
26 | } | |
27 | ||
28 | impl<'a, A, R> Closure<'a, A, R> { | |
29 | pub fn call(&mut self, arg: A) -> R { | |
30 | unsafe { (self.call)(self.env, arg) } | |
31 | } | |
32 | } |