mf_persistence/
ser.rs

1//! 持久化负载的序列化辅助工具。
2//!
3//! 使用简单分帧:将各步骤的序列化字节以 `0x1E`(记录分隔符)连接。
4//! 压缩为可选,建议在分帧之后进行;校验和在压缩(或加密)后的字节上计算。
5
6use crc32fast::Hasher as Crc32;
7use zstd::stream::encode_all;
8use mf_state::Transaction;
9use serde::{Serialize, Deserialize};
10
11/// 可选的 zstd 压缩(level=1,优先速度)。
12pub fn compress_if_needed(
13    input: &[u8],
14    enable: bool,
15) -> anyhow::Result<Vec<u8>> {
16    if !enable {
17        return Ok(input.to_vec());
18    }
19    let out = encode_all(input, 1)?; // fast
20    Ok(out)
21}
22
23/// CRC32 校验,提供轻量级的数据完整性保护。
24pub fn checksum32(input: &[u8]) -> u32 {
25    let mut h = Crc32::new();
26    h.update(input);
27    h.finalize()
28}
29
30/// 将步骤序列化结果以 RS(0x1E) 作为分隔拼接。
31pub fn serialize_steps_concat(transaction: &Transaction) -> Vec<u8> {
32    let mut payload: Vec<u8> = Vec::new();
33    for step in transaction.steps.iter() {
34        if let Some(s) = step.serialize() {
35            payload.extend_from_slice(&s);
36            payload.push(0x1E);
37        }
38    }
39    payload
40}
41
42// 标准化的步骤帧格式,便于跨版本重放
43#[derive(Serialize, Deserialize, Clone, Debug)]
44pub struct TypeWrapper {
45    pub type_id: String,
46    pub data: Vec<u8>,
47}
48
49// 快照序列化载体(与 StateSerialize 的字段对应)
50#[derive(Serialize, Deserialize, Clone, Debug)]
51pub struct SnapshotData {
52    pub node_pool: Vec<u8>,
53    pub state_fields: Vec<u8>,
54}
55
56pub fn frame_steps(transaction: &Transaction) -> Vec<TypeWrapper> {
57    let mut frames: Vec<TypeWrapper> =
58        Vec::with_capacity(transaction.steps.len());
59    for step in transaction.steps.iter() {
60        if let Some(data) = step.serialize() {
61            frames.push(TypeWrapper { type_id: step.name(), data });
62        }
63    }
64    frames
65}