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.
69///
70/// Functions take at most 32 parameters.
71///
72/// ```
73/// fn takes<T: hyperlight_common::func::ParameterTuple>() {}
74/// takes::<(
75///     i32, i32, i32, i32, i32, i32, i32, i32,
76///     i32, i32, i32, i32, i32, i32, i32, i32,
77///     i32, i32, i32, i32, i32, i32, i32, i32,
78///     i32, i32, i32, i32, i32, i32, i32, i32,
79/// )>();
80/// ```
81///
82/// ```compile_fail
83/// fn takes<T: hyperlight_common::func::ParameterTuple>() {}
84/// takes::<(
85///     i32, i32, i32, i32, i32, i32, i32, i32,
86///     i32, i32, i32, i32, i32, i32, i32, i32,
87///     i32, i32, i32, i32, i32, i32, i32, i32,
88///     i32, i32, i32, i32, i32, i32, i32, i32,
89///     i32,
90/// )>();
91/// ```
92pub trait ParameterTuple: Sized + Clone + Send + Sync + 'static {
93    /// The number of parameters in the tuple
94    const SIZE: usize;
95
96    /// The underlying Hyperlight parameter types representing this tuple of `SupportedParameterType`
97    const TYPE: &[ParameterType];
98
99    /// Get the underling Hyperlight parameter value representing this
100    /// `SupportedParameterType`
101    fn into_value(self) -> Vec<ParameterValue>;
102
103    /// Get the actual inner value of this `SupportedParameterType`
104    fn from_value(value: Vec<ParameterValue>) -> Result<Self, Error>;
105}
106
107impl<T: SupportedParameterType> ParameterTuple for T {
108    const SIZE: usize = 1;
109
110    const TYPE: &[ParameterType] = &[T::TYPE];
111
112    fn into_value(self) -> Vec<ParameterValue> {
113        vec![self.into_value()]
114    }
115
116    fn from_value(value: Vec<ParameterValue>) -> Result<Self, Error> {
117        match <[ParameterValue; 1]>::try_from(value) {
118            Ok([val]) => Ok(T::from_value(val)?),
119            Err(value) => Err(Error::UnexpectedNoOfArguments(value.len(), 1)),
120        }
121    }
122}
123
124macro_rules! impl_param_tuple {
125    ([$N:expr] ($($name:ident: $param:ident),*)) => {
126        impl<$($param: SupportedParameterType),*> ParameterTuple for ($($param,)*) {
127            const SIZE: usize = $N;
128
129            const TYPE: &[ParameterType] = &[
130                $($param::TYPE),*
131            ];
132
133            fn into_value(self) -> Vec<ParameterValue> {
134                let ($($name,)*) = self;
135                vec![$($name.into_value()),*]
136            }
137
138            fn from_value(value: Vec<ParameterValue>) -> Result<Self, Error> {
139                match <[ParameterValue; $N]>::try_from(value) {
140                    Ok([$($name,)*]) => Ok(($($param::from_value($name)?,)*)),
141                    Err(value) => Err(Error::UnexpectedNoOfArguments(value.len(), $N))
142                }
143            }
144        }
145    };
146}
147
148for_each_tuple!(impl_param_tuple);
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    #[test]
155    fn byte_chunks_parameter_round_trips_without_copying() {
156        let chunks = vec![Bytes::from_static(b"hello"), Bytes::from_static(b" world")];
157        let first_chunk = chunks[0].as_ptr();
158        let value = <Vec<Bytes> as SupportedParameterType>::into_value(chunks);
159        let chunks = <Vec<Bytes> as SupportedParameterType>::from_value(value).unwrap();
160
161        assert_eq!(chunks[0].as_ptr(), first_chunk);
162        assert_eq!(
163            chunks,
164            [Bytes::from_static(b"hello"), Bytes::from_static(b" world")]
165        );
166    }
167}