hyperlight_common/func/
param_type.rs1use 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
25pub trait SupportedParameterType: Sized + Clone + Send + Sync + 'static {
31 const TYPE: ParameterType;
33
34 fn into_value(self) -> ParameterValue;
37 fn from_value(value: ParameterValue) -> Result<Self, Error>;
39}
40
41macro_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
80pub trait ParameterTuple: Sized + Clone + Send + Sync + 'static {
82 const SIZE: usize;
84
85 const TYPE: &[ParameterType];
87
88 fn into_value(self) -> Vec<ParameterValue>;
91
92 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);