hyperlight_guest_bin/guest_function/
register.rs1use alloc::collections::BTreeMap;
18use alloc::string::String;
19
20use hyperlight_common::func::{ParameterTuple, SupportedReturnType};
21
22use super::definition::{GuestFunc, GuestFunctionDefinition};
23use crate::REGISTERED_GUEST_FUNCTIONS;
24use crate::guest_function::definition::AsGuestFunctionDefinition;
25
26#[derive(Debug, Clone)]
28pub struct GuestFunctionRegister<F: Copy> {
29 guest_functions: BTreeMap<String, GuestFunctionDefinition<F>>,
31}
32
33impl<F: Copy> Default for GuestFunctionRegister<F> {
34 fn default() -> Self {
35 Self {
36 guest_functions: BTreeMap::new(),
37 }
38 }
39}
40
41impl<F: Copy> GuestFunctionRegister<F> {
42 pub const fn new() -> Self {
44 Self {
45 guest_functions: BTreeMap::new(),
46 }
47 }
48
49 pub fn register(
54 &mut self,
55 guest_function: GuestFunctionDefinition<F>,
56 ) -> Option<GuestFunctionDefinition<F>> {
57 self.guest_functions
58 .insert(guest_function.function_name.clone(), guest_function)
59 }
60
61 pub fn get(&self, function_name: &str) -> Option<&GuestFunctionDefinition<F>> {
63 self.guest_functions.get(function_name)
64 }
65}
66
67impl GuestFunctionRegister<GuestFunc> {
68 pub fn register_fn<Output, Args>(
69 &mut self,
70 name: impl Into<String>,
71 f: impl AsGuestFunctionDefinition<Output, Args>,
72 ) where
73 Args: ParameterTuple,
74 Output: SupportedReturnType,
75 {
76 let gfd = f.as_guest_function_definition(name);
77 self.register(gfd);
78 }
79}
80
81pub fn register_function(function_definition: GuestFunctionDefinition<GuestFunc>) {
82 unsafe {
83 #[allow(static_mut_refs)]
86 let gfd = &mut REGISTERED_GUEST_FUNCTIONS;
87 gfd.register(function_definition);
88 }
89}
90
91pub fn register_fn<Output, Args>(
92 name: impl Into<String>,
93 f: impl AsGuestFunctionDefinition<Output, Args>,
94) where
95 Args: ParameterTuple,
96 Output: SupportedReturnType,
97{
98 unsafe {
99 #[allow(static_mut_refs)]
102 let gfd = &mut REGISTERED_GUEST_FUNCTIONS;
103 gfd.register_fn(name, f);
104 }
105}