hyperlight_common/func/
param_type.rs

1/*
2Copyright 2025  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::string::String;
18use alloc::vec;
19use alloc::vec::Vec;
20
21use super::error::Error;
22use super::utils::for_each_tuple;
23use crate::flatbuffer_wrappers::function_types::{ParameterType, ParameterValue};
24
25/// This is a marker trait that is used to indicate that a type is a
26/// valid Hyperlight parameter type.
27///
28/// For each parameter type Hyperlight supports in host functions, we
29/// provide an implementation for `SupportedParameterType`
30pub trait SupportedParameterType: Sized + Clone + Send + Sync + 'static {
31    /// The underlying Hyperlight parameter type representing this `SupportedParameterType`
32    const TYPE: ParameterType;
33
34    /// Get the underling Hyperlight parameter value representing this
35    /// `SupportedParameterType`
36    fn into_value(self) -> ParameterValue;
37    /// Get the actual inner value of this `SupportedParameterType`
38    fn from_value(value: ParameterValue) -> Result<Self, Error>;
39}
40
41// We can then implement these traits for each type that Hyperlight supports as a parameter or return type
42macro_rules! for_each_param_type {
43    ($macro:ident) => {
44        $macro!(String, String);
45        $macro!(i32, Int);
46        $macro!(u32, UInt);
47        $macro!(i64, Long);
48        $macro!(u64, ULong);
49        $macro!(f32, Float);
50        $macro!(f64, Double);
51        $macro!(bool, Bool);
52        $macro!(Vec<u8>, VecBytes);
53    };
54}
55
56macro_rules! impl_supported_param_type {
57    ($type:ty, $enum:ident) => {
58        impl SupportedParameterType for $type {
59            const TYPE: ParameterType = ParameterType::$enum;
60
61            fn into_value(self) -> ParameterValue {
62                ParameterValue::$enum(self)
63            }
64
65            fn from_value(value: ParameterValue) -> Result<Self, Error> {
66                match value {
67                    ParameterValue::$enum(i) => Ok(i),
68                    other => Err(Error::ParameterValueConversionFailure(
69                        other.clone(),
70                        stringify!($type),
71                    )),
72                }
73            }
74        }
75    };
76}
77
78for_each_param_type!(impl_supported_param_type);
79
80/// A trait to describe the tuple of parameters that a host function can take.
81pub trait ParameterTuple: Sized + Clone + Send + Sync + 'static {
82    /// The number of parameters in the tuple
83    const SIZE: usize;
84
85    /// The underlying Hyperlight parameter types representing this tuple of `SupportedParameterType`
86    const TYPE: &[ParameterType];
87
88    /// Get the underling Hyperlight parameter value representing this
89    /// `SupportedParameterType`
90    fn into_value(self) -> Vec<ParameterValue>;
91
92    /// Get the actual inner value of this `SupportedParameterType`
93    fn from_value(value: Vec<ParameterValue>) -> Result<Self, Error>;
94}
95
96impl<T: SupportedParameterType> ParameterTuple for T {
97    const SIZE: usize = 1;
98
99    const TYPE: &[ParameterType] = &[T::TYPE];
100
101    fn into_value(self) -> Vec<ParameterValue> {
102        vec![self.into_value()]
103    }
104
105    fn from_value(value: Vec<ParameterValue>) -> Result<Self, Error> {
106        match <[ParameterValue; 1]>::try_from(value) {
107            Ok([val]) => Ok(T::from_value(val)?),
108            Err(value) => Err(Error::UnexpectedNoOfArguments(value.len(), 1)),
109        }
110    }
111}
112
113macro_rules! impl_param_tuple {
114    ([$N:expr] ($($name:ident: $param:ident),*)) => {
115        impl<$($param: SupportedParameterType),*> ParameterTuple for ($($param,)*) {
116            const SIZE: usize = $N;
117
118            const TYPE: &[ParameterType] = &[
119                $($param::TYPE),*
120            ];
121
122            fn into_value(self) -> Vec<ParameterValue> {
123                let ($($name,)*) = self;
124                vec![$($name.into_value()),*]
125            }
126
127            fn from_value(value: Vec<ParameterValue>) -> Result<Self, Error> {
128                match <[ParameterValue; $N]>::try_from(value) {
129                    Ok([$($name,)*]) => Ok(($($param::from_value($name)?,)*)),
130                    Err(value) => Err(Error::UnexpectedNoOfArguments(value.len(), $N))
131                }
132            }
133        }
134    };
135}
136
137for_each_tuple!(impl_param_tuple);