use alloc::collections::BTreeMap;
use alloc::string::String;
use hyperlight_common::func::{ParameterTuple, SupportedReturnType};
use super::definition::{GuestFunc, GuestFunctionDefinition};
use crate::REGISTERED_GUEST_FUNCTIONS;
use crate::guest_function::definition::AsGuestFunctionDefinition;
#[derive(Debug, Clone)]
pub struct GuestFunctionRegister<F: Copy> {
guest_functions: BTreeMap<String, GuestFunctionDefinition<F>>,
}
impl<F: Copy> Default for GuestFunctionRegister<F> {
fn default() -> Self {
Self {
guest_functions: BTreeMap::new(),
}
}
}
impl<F: Copy> GuestFunctionRegister<F> {
pub const fn new() -> Self {
Self {
guest_functions: BTreeMap::new(),
}
}
pub fn register(
&mut self,
guest_function: GuestFunctionDefinition<F>,
) -> Option<GuestFunctionDefinition<F>> {
self.guest_functions
.insert(guest_function.function_name.clone(), guest_function)
}
pub fn get(&self, function_name: &str) -> Option<&GuestFunctionDefinition<F>> {
self.guest_functions.get(function_name)
}
}
impl GuestFunctionRegister<GuestFunc> {
pub fn register_fn<Output, Args>(
&mut self,
name: impl Into<String>,
f: impl AsGuestFunctionDefinition<Output, Args>,
) where
Args: ParameterTuple,
Output: SupportedReturnType,
{
let gfd = f.as_guest_function_definition(name);
self.register(gfd);
}
}
pub fn register_function(function_definition: GuestFunctionDefinition<GuestFunc>) {
unsafe {
#[allow(static_mut_refs)]
let gfd = &mut REGISTERED_GUEST_FUNCTIONS;
gfd.register(function_definition);
}
}
pub fn register_fn<Output, Args>(
name: impl Into<String>,
f: impl AsGuestFunctionDefinition<Output, Args>,
) where
Args: ParameterTuple,
Output: SupportedReturnType,
{
unsafe {
#[allow(static_mut_refs)]
let gfd = &mut REGISTERED_GUEST_FUNCTIONS;
gfd.register_fn(name, f);
}
}