1//! Closure type (equivalent to `&mut dyn FnMut(A) -> R`) that's `repr(C)`.
2
3use std::marker::PhantomData;
4
5#[repr(C)]
6pub struct Closure<'a, A, R> {
7 call: unsafe extern "C" fn(*mut Env, A) -> R,
8 env: *mut Env,
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`.
14 _marker: PhantomData<*mut &'a mut ()>,
15}
16
17struct Env;
18
19impl<'a, A, R, F: FnMut(A) -> R> From<&'a mut F> for Closure<'a, A, R> {
20 fn from(f: &'a mut F) -> Self {
21 unsafe extern "C" fn call<A, R, F: FnMut(A) -> R>(env: *mut Env, arg: A) -> R {
22 (*(env as *mut _ as *mut F))(arg)
23 }
24 Closure { call: call::<A, R, F>, env: f as *mut _ as *mut Env, _marker: PhantomData }
25 }
26}
27
28impl<'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}
33