Skip to main content

hyperlight_common/func/
param_type.rs

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