use std::ffi::c_void;
use std::marker::PhantomData;
use crate::object::type_key_of_index;
use crate::tvm_ffi_sys::{TVMFFIAny, TVMFFITypeIndex};
use crate::type_traits::DowncastRefFromObject;
use crate::{Any, AnyView, Error, Function, Result, TYPE_ERROR};
pub struct NativeFunction<Args, R = ()> {
data: Any,
signature: PhantomData<fn() -> (Args, R)>,
}
impl<Args: NativeArgs, R: TryFrom<Any>> NativeFunction<Args, R> {
pub fn call(&self, args: Args) -> Result<R> {
let raw = self.data.as_raw_ffi_any();
let result = if raw.type_index == TVMFFITypeIndex::kTVMFFIOpaquePtr as i32 {
unsafe { args.call_native(raw.data_union.v_ptr) }
} else {
let function = self.data.downcast_ref::<Function>();
args.call_packed(function.expect("a hook is a native or packed function"))?
};
if result.type_index() == TVMFFITypeIndex::kTVMFFIError as i32 {
return Err(result.try_into()?);
}
R::try_from(result).map_err(|_| Error::new(TYPE_ERROR, "Packed hook result type mismatch"))
}
}
impl<Args, R> Clone for NativeFunction<Args, R> {
fn clone(&self) -> Self {
Self {
data: self.data.clone(),
signature: PhantomData,
}
}
}
impl<Args, R> NativeFunction<Args, R> {
pub unsafe fn from_any(value: Any) -> Result<Self> {
let raw = value.as_raw_ffi_any();
let native = raw.type_index == TVMFFITypeIndex::kTVMFFIOpaquePtr as i32
&& !unsafe { raw.data_union.v_ptr }.is_null();
if !native && raw.type_index != TVMFFITypeIndex::kTVMFFIFunction as i32 {
let message = format!(
"Cannot convert from type `{}` to `NativeFunction`",
type_key_of_index(raw.type_index)
);
return Err(Error::new(TYPE_ERROR, &message));
}
Ok(Self {
data: value,
signature: PhantomData,
})
}
pub unsafe fn into_any(self) -> Any {
self.data
}
}
pub trait NativeArgs: sealed::NativeArgs {}
impl<T: sealed::NativeArgs> NativeArgs for T {}
mod sealed {
use super::*;
pub trait NativeArgs {
unsafe fn call_native(self, function: *mut c_void) -> Any;
fn call_packed(self, function: &Function) -> Result<Any>;
}
pub trait NativeArg: Copy {
type Target: 'static;
fn to_any_view(&self) -> AnyView<'_>;
}
impl<T: DowncastRefFromObject + 'static> NativeArg for &T {
type Target = T;
#[inline(always)]
fn to_any_view(&self) -> AnyView<'_> {
AnyView::from_object(self.as_object())
}
}
impl NativeArg for &Any {
type Target = Any;
#[inline(always)]
fn to_any_view(&self) -> AnyView<'_> {
AnyView::from(*self)
}
}
#[inline(always)]
unsafe fn conjure<F: Copy>() -> F {
const {
assert!(
size_of::<F>() == 0,
"a native hook is built from a function or a closure that captures nothing"
)
};
unsafe { std::mem::zeroed() }
}
#[inline(always)]
fn into_raw<R: Into<Any>>(result: Result<R>) -> TVMFFIAny {
Any::into_raw_ffi_any(match result {
Ok(value) => value.into(),
Err(error) => Any::from(error),
})
}
macro_rules! impl_native_args {
($($arg:ident $index:tt),*) => {
impl<$($arg: NativeArg),*> NativeArgs for ($($arg,)*) {
#[inline(always)]
unsafe fn call_native(self, function: *mut c_void) -> Any {
$(let _ = self.$index.to_any_view();)*
unsafe {
let function = std::mem::transmute::<
*mut c_void,
unsafe extern "C" fn($($arg),*) -> TVMFFIAny,
>(function);
Any::from_raw_ffi_any(function($(self.$index),*))
}
}
#[inline(always)]
fn call_packed(self, function: &Function) -> Result<Any> {
function.call_packed(&[$(self.$index.to_any_view()),*])
}
}
};
}
macro_rules! impl_native_fn {
($($arg:ident $raw:ident),*) => {
impl<F, $($arg: NativeArg,)* R: Into<Any>> From<F> for NativeFunction<($($arg,)*), R>
where
F: for<'a> Fn($(&'a $arg::Target),*) -> Result<R> + Copy + 'static,
{
fn from(_function: F) -> Self {
extern "C" fn adapter<F, $($arg: NativeArg,)* R: Into<Any>>(
$($raw: *const $arg::Target),*
) -> TVMFFIAny
where
F: for<'a> Fn($(&'a $arg::Target),*) -> Result<R> + Copy + 'static,
{
let function = unsafe { conjure::<F>() };
$(let Some($raw) = (unsafe { $raw.as_ref() }) else {
let message = "A native hook argument is null";
return into_raw::<R>(Err(Error::new(TYPE_ERROR, message)));
};)*
into_raw(function($($raw),*))
}
let adapter = adapter::<F, $($arg,)* R> as *mut c_void;
Self { data: Any::from(adapter), signature: PhantomData }
}
}
};
}
impl_native_fn!();
impl_native_fn!(A0 a0);
impl_native_fn!(A0 a0, A1 a1);
impl_native_fn!(A0 a0, A1 a1, A2 a2);
impl_native_fn!(A0 a0, A1 a1, A2 a2, A3 a3);
impl_native_fn!(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4);
impl_native_fn!(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5);
impl_native_fn!(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6);
impl_native_fn!(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7);
impl_native_args!();
impl_native_args!(A0 0);
impl_native_args!(A0 0, A1 1);
impl_native_args!(A0 0, A1 1, A2 2);
impl_native_args!(A0 0, A1 1, A2 2, A3 3);
impl_native_args!(A0 0, A1 1, A2 2, A3 3, A4 4);
impl_native_args!(A0 0, A1 1, A2 2, A3 3, A4 4, A5 5);
impl_native_args!(A0 0, A1 1, A2 2, A3 3, A4 4, A5 5, A6 6);
impl_native_args!(A0 0, A1 1, A2 2, A3 3, A4 4, A5 5, A6 6, A7 7);
}