Skip to main content

hyperlight_common/func/
ret_type.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2025 The Hyperlight Authors.
3
4use alloc::string::String;
5use alloc::vec::Vec;
6
7use super::error::Error;
8use crate::flatbuffer_wrappers::function_types::{ReturnType, ReturnValue};
9
10/// This is a marker trait that is used to indicate that a type is a valid Hyperlight return type.
11///
12/// `Vec<u8>` and `Vec<Bytes>` both represent one logical byte sequence.
13/// `Vec<u8>` stores it contiguously. `Vec<Bytes>` represents it as chunks and
14/// may avoid flattening them into one allocation. Chunk boundaries are a
15/// storage detail and may change during transport. They do not delimit messages
16/// or values.
17pub trait SupportedReturnType: Sized + Clone + Send + Sync + 'static {
18    /// The return type of the supported return value
19    const TYPE: ReturnType;
20
21    /// Gets the value of the supported return value
22    fn into_value(self) -> ReturnValue;
23
24    /// Gets the inner value of the supported return type
25    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
68/// A trait to handle either a [`SupportedReturnType`] or a [`Result<impl SupportedReturnType>`]
69pub trait ResultType<E: core::fmt::Debug> {
70    /// The return type of the supported return value
71    type ReturnType: SupportedReturnType;
72
73    /// Convert the return type into a `Result<impl SupportedReturnType>`
74    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}