proc_macro/bridge/
closure.rs

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