hyperlight_guest_bin/guest_function/
register.rs1use alloc::collections::BTreeMap;
5use alloc::string::String;
6
7use hyperlight_common::func::{ParameterTuple, SupportedReturnType};
8
9use super::definition::{GuestFunc, GuestFunctionDefinition};
10use crate::REGISTERED_GUEST_FUNCTIONS;
11use crate::guest_function::definition::AsGuestFunctionDefinition;
12
13#[derive(Debug, Clone)]
15pub struct GuestFunctionRegister<F: Copy> {
16 guest_functions: BTreeMap<String, GuestFunctionDefinition<F>>,
18}
19
20impl<F: Copy> Default for GuestFunctionRegister<F> {
21 fn default() -> Self {
22 Self {
23 guest_functions: BTreeMap::new(),
24 }
25 }
26}
27
28impl<F: Copy> GuestFunctionRegister<F> {
29 pub const fn new() -> Self {
31 Self {
32 guest_functions: BTreeMap::new(),
33 }
34 }
35
36 pub fn register(
41 &mut self,
42 guest_function: GuestFunctionDefinition<F>,
43 ) -> Option<GuestFunctionDefinition<F>> {
44 self.guest_functions
45 .insert(guest_function.function_name.clone(), guest_function)
46 }
47
48 pub fn get(&self, function_name: &str) -> Option<&GuestFunctionDefinition<F>> {
50 self.guest_functions.get(function_name)
51 }
52}
53
54impl GuestFunctionRegister<GuestFunc> {
55 pub fn register_fn<Output, Args>(
56 &mut self,
57 name: impl Into<String>,
58 f: impl AsGuestFunctionDefinition<Output, Args>,
59 ) where
60 Args: ParameterTuple,
61 Output: SupportedReturnType,
62 {
63 let gfd = f.as_guest_function_definition(name);
64 self.register(gfd);
65 }
66}
67
68pub fn register_function(function_definition: GuestFunctionDefinition<GuestFunc>) {
69 unsafe {
70 #[allow(static_mut_refs)]
73 let gfd = &mut REGISTERED_GUEST_FUNCTIONS;
74 gfd.register(function_definition);
75 }
76}
77
78pub fn register_fn<Output, Args>(
79 name: impl Into<String>,
80 f: impl AsGuestFunctionDefinition<Output, Args>,
81) where
82 Args: ParameterTuple,
83 Output: SupportedReturnType,
84{
85 unsafe {
86 #[allow(static_mut_refs)]
89 let gfd = &mut REGISTERED_GUEST_FUNCTIONS;
90 gfd.register_fn(name, f);
91 }
92}