mf_file/
history.rs

1use std::io;
2use serde::{Deserialize, Serialize};
3
4// 步骤帧:type_id 表示类型,data 为该类型的序列化字节
5#[derive(Debug, Clone, Serialize, Deserialize)]
6pub struct TypeWrapper {
7    pub type_id: String,
8    pub data: Vec<u8>,
9}
10
11// 编码步骤帧;可选 zstd 压缩
12pub fn encode_history_frames(
13    frames: &[TypeWrapper],
14    compress: bool,
15) -> io::Result<Vec<u8>> {
16    let bytes =
17        bincode::serde::encode_to_vec(frames, bincode::config::standard())
18            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
19    if compress {
20        Ok(zstd::stream::encode_all(&bytes[..], 1)
21            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?)
22    } else {
23        Ok(bytes)
24    }
25}
26
27// 解码步骤帧;如 compressed 为真先解压
28pub fn decode_history_frames(
29    bytes: &[u8],
30    compressed: bool,
31) -> io::Result<Vec<TypeWrapper>> {
32    let raw = if compressed {
33        zstd::stream::decode_all(bytes)
34            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?
35    } else {
36        bytes.to_vec()
37    };
38    let (frames, _) = bincode::serde::decode_from_slice::<Vec<TypeWrapper>, _>(
39        &raw,
40        bincode::config::standard(),
41    )
42    .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
43    Ok(frames)
44}