Skip to content

Commit 94ade25

Browse files
committed
Use serde and postcard for serialization in hyperlight-common
Signed-off-by: Jorge Prendes <jorge.prendes@gmail.com>
1 parent 70a2c15 commit 94ade25

File tree

11 files changed

+247
-2034
lines changed

11 files changed

+247
-2034
lines changed

Cargo.lock

Lines changed: 35 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/hyperlight_common/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ workspace = true
1616

1717
[dependencies]
1818
flatbuffers = { version = "25.12.19", default-features = false }
19+
postcard = { version = "1.1.3", default-features = false, features = ["alloc"] }
20+
serde = { version = "1.0.228", default-features = false, features = ["derive", "alloc"] }
1921
anyhow = { version = "1.0.100", default-features = false }
2022
log = "0.4.29"
2123
tracing = { version = "0.1.44", optional = true }

src/hyperlight_common/src/flatbuffer_wrappers/function_call.rs

Lines changed: 21 additions & 199 deletions
Original file line numberDiff line numberDiff line change
@@ -14,25 +14,19 @@ See the License for the specific language governing permissions and
1414
limitations under the License.
1515
*/
1616

17-
use alloc::string::{String, ToString};
17+
use alloc::string::String;
1818
use alloc::vec::Vec;
1919

20-
use anyhow::{Error, Result, bail};
21-
use flatbuffers::{FlatBufferBuilder, WIPOffset, size_prefixed_root};
20+
use anyhow::{Context, Result, bail};
21+
use serde::{Deserialize, Serialize};
2222
#[cfg(feature = "tracing")]
2323
use tracing::{Span, instrument};
2424

2525
use super::function_types::{ParameterValue, ReturnType};
26-
use crate::flatbuffers::hyperlight::generated::{
27-
FunctionCall as FbFunctionCall, FunctionCallArgs as FbFunctionCallArgs,
28-
FunctionCallType as FbFunctionCallType, Parameter, ParameterArgs,
29-
ParameterValue as FbParameterValue, hlbool, hlboolArgs, hldouble, hldoubleArgs, hlfloat,
30-
hlfloatArgs, hlint, hlintArgs, hllong, hllongArgs, hlstring, hlstringArgs, hluint, hluintArgs,
31-
hlulong, hlulongArgs, hlvecbytes, hlvecbytesArgs,
32-
};
26+
use crate::flatbuffer_wrappers::util::decode;
3327

3428
/// The type of function call.
35-
#[derive(Debug, Clone, PartialEq, Eq)]
29+
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3630
pub enum FunctionCallType {
3731
/// The function call is to a guest function.
3832
Guest,
@@ -41,7 +35,7 @@ pub enum FunctionCallType {
4135
}
4236

4337
/// `Functioncall` represents a call to a function in the guest or host.
44-
#[derive(Clone)]
38+
#[derive(Clone, Serialize, Deserialize)]
4539
pub struct FunctionCall {
4640
/// The function name
4741
pub function_name: String,
@@ -72,154 +66,14 @@ impl FunctionCall {
7266
pub fn function_call_type(&self) -> FunctionCallType {
7367
self.function_call_type.clone()
7468
}
75-
76-
/// Encodes self into the given builder and returns the encoded data.
77-
///
78-
/// # Notes
79-
///
80-
/// The builder should not be reused after a call to encode, since this function
81-
/// does not reset the state of the builder. If you want to reuse the builder,
82-
/// you'll need to reset it first.
83-
pub fn encode<'a>(&self, builder: &'a mut FlatBufferBuilder) -> &'a [u8] {
84-
let function_name = builder.create_string(&self.function_name);
85-
86-
let function_call_type = match self.function_call_type {
87-
FunctionCallType::Guest => FbFunctionCallType::guest,
88-
FunctionCallType::Host => FbFunctionCallType::host,
89-
};
90-
91-
let expected_return_type = self.expected_return_type.into();
92-
93-
let parameters = match &self.parameters {
94-
Some(p) if !p.is_empty() => {
95-
let parameter_offsets: Vec<WIPOffset<Parameter>> = p
96-
.iter()
97-
.map(|param| match param {
98-
ParameterValue::Int(i) => {
99-
let hlint = hlint::create(builder, &hlintArgs { value: *i });
100-
Parameter::create(
101-
builder,
102-
&ParameterArgs {
103-
value_type: FbParameterValue::hlint,
104-
value: Some(hlint.as_union_value()),
105-
},
106-
)
107-
}
108-
ParameterValue::UInt(ui) => {
109-
let hluint = hluint::create(builder, &hluintArgs { value: *ui });
110-
Parameter::create(
111-
builder,
112-
&ParameterArgs {
113-
value_type: FbParameterValue::hluint,
114-
value: Some(hluint.as_union_value()),
115-
},
116-
)
117-
}
118-
ParameterValue::Long(l) => {
119-
let hllong = hllong::create(builder, &hllongArgs { value: *l });
120-
Parameter::create(
121-
builder,
122-
&ParameterArgs {
123-
value_type: FbParameterValue::hllong,
124-
value: Some(hllong.as_union_value()),
125-
},
126-
)
127-
}
128-
ParameterValue::ULong(ul) => {
129-
let hlulong = hlulong::create(builder, &hlulongArgs { value: *ul });
130-
Parameter::create(
131-
builder,
132-
&ParameterArgs {
133-
value_type: FbParameterValue::hlulong,
134-
value: Some(hlulong.as_union_value()),
135-
},
136-
)
137-
}
138-
ParameterValue::Float(f) => {
139-
let hlfloat = hlfloat::create(builder, &hlfloatArgs { value: *f });
140-
Parameter::create(
141-
builder,
142-
&ParameterArgs {
143-
value_type: FbParameterValue::hlfloat,
144-
value: Some(hlfloat.as_union_value()),
145-
},
146-
)
147-
}
148-
ParameterValue::Double(d) => {
149-
let hldouble = hldouble::create(builder, &hldoubleArgs { value: *d });
150-
Parameter::create(
151-
builder,
152-
&ParameterArgs {
153-
value_type: FbParameterValue::hldouble,
154-
value: Some(hldouble.as_union_value()),
155-
},
156-
)
157-
}
158-
ParameterValue::Bool(b) => {
159-
let hlbool = hlbool::create(builder, &hlboolArgs { value: *b });
160-
Parameter::create(
161-
builder,
162-
&ParameterArgs {
163-
value_type: FbParameterValue::hlbool,
164-
value: Some(hlbool.as_union_value()),
165-
},
166-
)
167-
}
168-
ParameterValue::String(s) => {
169-
let val = builder.create_string(s.as_str());
170-
let hlstring =
171-
hlstring::create(builder, &hlstringArgs { value: Some(val) });
172-
Parameter::create(
173-
builder,
174-
&ParameterArgs {
175-
value_type: FbParameterValue::hlstring,
176-
value: Some(hlstring.as_union_value()),
177-
},
178-
)
179-
}
180-
ParameterValue::VecBytes(v) => {
181-
let vec_bytes = builder.create_vector(v);
182-
let hlvecbytes = hlvecbytes::create(
183-
builder,
184-
&hlvecbytesArgs {
185-
value: Some(vec_bytes),
186-
},
187-
);
188-
Parameter::create(
189-
builder,
190-
&ParameterArgs {
191-
value_type: FbParameterValue::hlvecbytes,
192-
value: Some(hlvecbytes.as_union_value()),
193-
},
194-
)
195-
}
196-
})
197-
.collect();
198-
Some(builder.create_vector(&parameter_offsets))
199-
}
200-
_ => None,
201-
};
202-
203-
let function_call = FbFunctionCall::create(
204-
builder,
205-
&FbFunctionCallArgs {
206-
function_name: Some(function_name),
207-
parameters,
208-
function_call_type,
209-
expected_return_type,
210-
},
211-
);
212-
builder.finish_size_prefixed(function_call, None);
213-
builder.finished_data()
214-
}
21569
}
21670

21771
#[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))]
21872
pub fn validate_guest_function_call_buffer(function_call_buffer: &[u8]) -> Result<()> {
219-
let guest_function_call_fb = size_prefixed_root::<FbFunctionCall>(function_call_buffer)
220-
.map_err(|e| anyhow::anyhow!("Error reading function call buffer: {:?}", e))?;
221-
match guest_function_call_fb.function_call_type() {
222-
FbFunctionCallType::guest => Ok(()),
73+
let guest_function_call: FunctionCall =
74+
decode(function_call_buffer).context("Error reading function call buffer")?;
75+
match guest_function_call.function_call_type {
76+
FunctionCallType::Guest => Ok(()),
22377
other => {
22478
bail!("Invalid function call type: {:?}", other);
22579
}
@@ -228,61 +82,28 @@ pub fn validate_guest_function_call_buffer(function_call_buffer: &[u8]) -> Resul
22882

22983
#[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))]
23084
pub fn validate_host_function_call_buffer(function_call_buffer: &[u8]) -> Result<()> {
231-
let host_function_call_fb = size_prefixed_root::<FbFunctionCall>(function_call_buffer)
232-
.map_err(|e| anyhow::anyhow!("Error reading function call buffer: {:?}", e))?;
233-
match host_function_call_fb.function_call_type() {
234-
FbFunctionCallType::host => Ok(()),
85+
let host_function_call: FunctionCall =
86+
decode(function_call_buffer).context("Error reading function call buffer")?;
87+
match host_function_call.function_call_type {
88+
FunctionCallType::Host => Ok(()),
23589
other => {
23690
bail!("Invalid function call type: {:?}", other);
23791
}
23892
}
23993
}
24094

241-
impl TryFrom<&[u8]> for FunctionCall {
242-
type Error = Error;
243-
#[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))]
244-
fn try_from(value: &[u8]) -> Result<Self> {
245-
let function_call_fb = size_prefixed_root::<FbFunctionCall>(value)
246-
.map_err(|e| anyhow::anyhow!("Error reading function call buffer: {:?}", e))?;
247-
let function_name = function_call_fb.function_name();
248-
let function_call_type = match function_call_fb.function_call_type() {
249-
FbFunctionCallType::guest => FunctionCallType::Guest,
250-
FbFunctionCallType::host => FunctionCallType::Host,
251-
other => {
252-
bail!("Invalid function call type: {:?}", other);
253-
}
254-
};
255-
let expected_return_type = function_call_fb.expected_return_type().try_into()?;
256-
257-
let parameters = function_call_fb
258-
.parameters()
259-
.map(|v| {
260-
v.iter()
261-
.map(|p| p.try_into())
262-
.collect::<Result<Vec<ParameterValue>>>()
263-
})
264-
.transpose()?;
265-
266-
Ok(Self {
267-
function_name: function_name.to_string(),
268-
parameters,
269-
function_call_type,
270-
expected_return_type,
271-
})
272-
}
273-
}
274-
27595
#[cfg(test)]
27696
mod tests {
97+
use alloc::string::ToString;
27798
use alloc::vec;
27899

279100
use super::*;
280101
use crate::flatbuffer_wrappers::function_types::ReturnType;
102+
use crate::flatbuffer_wrappers::util::encode;
281103

282104
#[test]
283105
fn read_from_flatbuffer() -> Result<()> {
284-
let mut builder = FlatBufferBuilder::new();
285-
let test_data = FunctionCall::new(
106+
let value = FunctionCall::new(
286107
"PrintTwelveArgs".to_string(),
287108
Some(vec![
288109
ParameterValue::String("1".to_string()),
@@ -300,10 +121,11 @@ mod tests {
300121
]),
301122
FunctionCallType::Guest,
302123
ReturnType::Int,
303-
)
304-
.encode(&mut builder);
124+
);
125+
126+
let test_data = encode(&value)?;
305127

306-
let function_call = FunctionCall::try_from(test_data)?;
128+
let function_call: FunctionCall = decode(&test_data)?;
307129
assert_eq!(function_call.function_name, "PrintTwelveArgs");
308130
assert!(function_call.parameters.is_some());
309131
let parameters = function_call.parameters.unwrap();

0 commit comments

Comments
 (0)