Skip to main content

sim_lib_server/
codecio.rs

1use sim_codec::{DecodeLimits, Input, Output, decode_with_codec_and_limits, encode_with_codec};
2use sim_kernel::{Cx, EncodeOptions, Expr, ReadPolicy, Result, Symbol};
3
4/// Encodes an expression with `codec` and returns the frame payload bytes.
5///
6/// Text output is returned as its UTF-8 bytes; byte output is returned as-is.
7pub fn encode_frame_payload(
8    cx: &mut Cx,
9    codec: &Symbol,
10    expr: &Expr,
11    options: EncodeOptions,
12) -> Result<Vec<u8>> {
13    match encode_with_codec(cx, codec, expr, options)? {
14        Output::Text(text) => Ok(text.into_bytes()),
15        Output::Bytes(bytes) => Ok(bytes),
16    }
17}
18
19/// Decodes a frame payload back into an expression using `codec`.
20///
21/// The `read_policy` and `limits` bound how the payload bytes are parsed.
22pub fn decode_frame_payload(
23    cx: &mut Cx,
24    codec: &Symbol,
25    payload: &[u8],
26    read_policy: ReadPolicy,
27    limits: DecodeLimits,
28) -> Result<Expr> {
29    decode_with_codec_and_limits(
30        cx,
31        codec,
32        Input::Bytes(payload.to_vec()),
33        read_policy,
34        limits,
35    )
36}