hyperlight_common/flatbuffer_wrappers/
host_function_details.rs

1/*
2Copyright 2024 The Hyperlight Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17use alloc::vec::Vec;
18
19use anyhow::{Error, Result};
20use flatbuffers::{size_prefixed_root, WIPOffset};
21#[cfg(feature = "tracing")]
22use tracing::{instrument, Span};
23
24use super::host_function_definition::HostFunctionDefinition;
25use crate::flatbuffers::hyperlight::generated::{
26    HostFunctionDefinition as FbHostFunctionDefinition,
27    HostFunctionDetails as FbHostFunctionDetails,
28    HostFunctionDetailsArgs as FbHostFunctionDetailsArgs,
29};
30
31/// `HostFunctionDetails` represents the set of functions that the host exposes to the guest.
32#[derive(Debug, Default, Clone)]
33pub struct HostFunctionDetails {
34    /// The host functions.
35    pub host_functions: Option<Vec<HostFunctionDefinition>>,
36}
37
38impl HostFunctionDetails {
39    /// Create a new `HostFunctionDetails`.
40    #[cfg_attr(feature = "tracing", instrument(skip_all, parent = Span::current(), level= "Trace"))]
41    pub fn new(host_functions: Option<Vec<HostFunctionDefinition>>) -> Self {
42        Self { host_functions }
43    }
44
45    /// Insert a host function into the host function details.
46    #[cfg_attr(feature = "tracing", instrument(skip_all, parent = Span::current(), level= "Trace"))]
47    pub fn insert_host_function(&mut self, host_function: HostFunctionDefinition) {
48        match &mut self.host_functions {
49            Some(host_functions) => host_functions.push(host_function),
50            None => {
51                let host_functions = Vec::from(&[host_function]);
52                self.host_functions = Some(host_functions);
53            }
54        }
55    }
56
57    /// Sort the host functions by name.
58    #[cfg_attr(feature = "tracing", instrument(skip_all, parent = Span::current(), level= "Trace"))]
59    pub fn sort_host_functions_by_name(&mut self) {
60        match &mut self.host_functions {
61            Some(host_functions) => {
62                host_functions.sort_by(|a, b| a.function_name.cmp(&b.function_name))
63            }
64            None => {}
65        }
66    }
67
68    /// Find a host function by name.
69    #[cfg_attr(feature = "tracing", instrument(skip_all, parent = Span::current(), level= "Trace"))]
70    pub fn find_by_function_name(&self, function_name: &str) -> Option<HostFunctionDefinition> {
71        match &self.host_functions {
72            Some(host_functions) => {
73                for host_function in host_functions {
74                    if host_function.function_name == function_name {
75                        return Some(host_function.clone());
76                    }
77                }
78
79                None
80            }
81            None => None,
82        }
83    }
84}
85
86impl TryFrom<&[u8]> for HostFunctionDetails {
87    type Error = Error;
88    #[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))]
89    fn try_from(value: &[u8]) -> Result<Self> {
90        let host_function_details_fb = size_prefixed_root::<FbHostFunctionDetails>(value)
91            .map_err(|e| anyhow::anyhow!("Error while reading HostFunctionDetails: {:?}", e))?;
92
93        let host_function_definitions = match host_function_details_fb.functions() {
94            Some(hfd) => {
95                let len = hfd.len();
96                let mut vec_hfd: Vec<HostFunctionDefinition> = Vec::with_capacity(len);
97                for i in 0..len {
98                    let fb_host_function_definition = hfd.get(i);
99                    let hfdef = HostFunctionDefinition::try_from(&fb_host_function_definition)?;
100                    vec_hfd.push(hfdef);
101                }
102
103                Some(vec_hfd)
104            }
105
106            None => None,
107        };
108
109        Ok(Self {
110            host_functions: host_function_definitions,
111        })
112    }
113}
114
115impl TryFrom<&HostFunctionDetails> for Vec<u8> {
116    type Error = Error;
117    #[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))]
118    fn try_from(value: &HostFunctionDetails) -> Result<Vec<u8>> {
119        let mut builder = flatbuffers::FlatBufferBuilder::new();
120        let vec_host_function_definitions = match &value.host_functions {
121            Some(vec_hfd) => {
122                let num_items = vec_hfd.len();
123                let mut host_function_definitions: Vec<WIPOffset<FbHostFunctionDefinition>> =
124                    Vec::with_capacity(num_items);
125
126                for hfd in vec_hfd {
127                    let host_function_definition = hfd.convert_to_flatbuffer_def(&mut builder)?;
128                    host_function_definitions.push(host_function_definition);
129                }
130
131                Some(host_function_definitions)
132            }
133            None => None,
134        };
135
136        let fb_host_function_definitions =
137            vec_host_function_definitions.map(|v| builder.create_vector(&v));
138
139        let host_function_details = FbHostFunctionDetails::create(
140            &mut builder,
141            &FbHostFunctionDetailsArgs {
142                functions: fb_host_function_definitions,
143            },
144        );
145        builder.finish_size_prefixed(host_function_details, None);
146        let res = builder.finished_data().to_vec();
147
148        Ok(res)
149    }
150}