hyperlight_common/func/
ret_type.rs1use alloc::string::String;
5use alloc::vec::Vec;
6
7use super::error::Error;
8use crate::flatbuffer_wrappers::function_types::{ReturnType, ReturnValue};
9
10pub trait SupportedReturnType: Sized + Clone + Send + Sync + 'static {
18 const TYPE: ReturnType;
20
21 fn into_value(self) -> ReturnValue;
23
24 fn from_value(value: ReturnValue) -> Result<Self, Error>;
26}
27
28#[macro_export]
29#[doc(hidden)]
30macro_rules! for_each_return_type {
31 ($macro:ident) => {
32 $macro!((), Void);
33 $macro!(String, String);
34 $macro!(i32, Int);
35 $macro!(u32, UInt);
36 $macro!(i64, Long);
37 $macro!(u64, ULong);
38 $macro!(f32, Float);
39 $macro!(f64, Double);
40 $macro!(bool, Bool);
41 $macro!(Vec<u8>, VecBytes);
42 $macro!(Vec<$crate::func::Bytes>, ByteChunks);
43 };
44}
45
46macro_rules! impl_supported_return_type {
47 ($type:ty, $enum:ident) => {
48 impl SupportedReturnType for $type {
49 const TYPE: ReturnType = ReturnType::$enum;
50
51 fn into_value(self) -> ReturnValue {
52 ReturnValue::$enum(self)
53 }
54
55 fn from_value(value: ReturnValue) -> Result<Self, Error> {
56 match value {
57 ReturnValue::$enum(i) => Ok(i),
58 other => Err(Error::ReturnValueConversionFailure(
59 other.clone(),
60 stringify!($type),
61 )),
62 }
63 }
64 }
65 };
66}
67
68pub trait ResultType<E: core::fmt::Debug> {
70 type ReturnType: SupportedReturnType;
72
73 fn into_result(self) -> Result<Self::ReturnType, E>;
75}
76
77impl<T, E> ResultType<E> for T
78where
79 T: SupportedReturnType,
80 E: core::fmt::Debug,
81{
82 type ReturnType = T;
83
84 fn into_result(self) -> Result<Self::ReturnType, E> {
85 Ok(self)
86 }
87}
88
89impl<T, E> ResultType<E> for Result<T, E>
90where
91 T: SupportedReturnType,
92 E: core::fmt::Debug,
93{
94 type ReturnType = T;
95
96 fn into_result(self) -> Result<Self::ReturnType, E> {
97 self
98 }
99}
100
101for_each_return_type!(impl_supported_return_type);
102
103#[cfg(test)]
104mod tests {
105 use super::*;
106 use crate::flatbuffer_wrappers::function_types::Bytes;
107
108 #[test]
109 fn byte_chunks_return_round_trips_without_copying() {
110 let chunks = vec![Bytes::from_static(b"hello"), Bytes::from_static(b" world")];
111 let first_chunk = chunks[0].as_ptr();
112 let value = <Vec<Bytes> as SupportedReturnType>::into_value(chunks);
113 let chunks = <Vec<Bytes> as SupportedReturnType>::from_value(value).unwrap();
114
115 assert_eq!(chunks[0].as_ptr(), first_chunk);
116 assert_eq!(
117 chunks,
118 [Bytes::from_static(b"hello"), Bytes::from_static(b" world")]
119 );
120 }
121}