Rust宏编程库chia_streamable_macro的使用:实现高效数据流序列化与反序列化

Rust宏编程库chia_streamable_macro的使用:实现高效数据流序列化与反序列化

安装

在项目目录中运行以下Cargo命令添加依赖:

cargo add chia_streamable_macro

或者在Cargo.toml中添加:

chia_streamable_macro = "0.29.0"

示例代码

以下是一个完整的使用示例:

use chia_streamable_macro::Streamable;
use chia_streamable_derive::streamable;

// 定义可序列化的数据结构
#[derive(Streamable, Debug, PartialEq)]
struct ExampleStruct {
    field1: u32,
    field2: String,
    field3: Vec<u8>,
}

#[streamable]
struct ExampleTupleStruct(u32, String, Vec<u8>);

fn main() {
    // 创建实例
    let original = ExampleStruct {
        field1: 42,
        field2: "test".to_string(),
        field3: vec![1, 2, 3],
    };

    // 序列化为字节流
    let bytes = original.to_bytes();
    
    // 从字节流反序列化
    let deserialized = ExampleStruct::from_bytes(&bytes).unwrap();
    
    assert_eq!(original, deserialized);
    
    // 元组结构体示例
    let tuple_original = ExampleTupleStruct(42, "test".to_string(), vec![1, 2, 3]);
    let tuple_bytes = tuple_original.to_bytes();
    let tuple_deserialized = ExampleTupleStruct::from_bytes(&tuple_bytes).unwrap();
    
    assert_eq!(tuple_original, tuple_deserialized);
}

完整示例代码

// 引入必要的trait和宏
use chia_streamable_macro::Streamable;
use chia_streamable_derive::streamable;

// 定义普通结构体
#[derive(Streamable, Debug, PartialEq)]
struct Person {
    id: u64,
    name: String,
    age: u8,
    skills: Vec<String>,
    is_active: bool,
}

// 定义元组结构体
#[streamable]
struct Point3D(f32, f32, f32);

fn main() {
    // 普通结构体示例
    let person = Person {
        id: 123456,
        name: "Alice".to_string(),
        age: 30,
        skills: vec!["Rust".to_string(), "Python".to_string()],
        is_active: true,
    };

    // 序列化
    let person_bytes = person.to_bytes();
    println!("序列化字节长度: {}", person_bytes.len());

    // 反序列化
    let person_deserialized = Person::from_bytes(&person_bytes).unwrap();
    println!("反序列化结果: {:?}", person_deserialized);
    assert_eq!(person, person_deserialized);

    // 元组结构体示例
    let point = Point3D(1.0, 2.0, 3.0);
    let point_bytes = point.to_bytes();
    let point_deserialized = Point3D::from_bytes(&point_bytes).unwrap();
    println!("点坐标: {:?}", point_deserialized);
    assert_eq!(point, point_deserialized);
}

特性

  1. 通过#[derive(Streamable)]自动为结构体实现序列化/反序列化
  2. 支持结构体和元组结构体
  3. 提供to_bytes()方法将结构体序列化为字节流
  4. 提供from_bytes()方法从字节流反序列化为结构体
  5. 高效处理基本类型和常见集合类型

许可证

该项目采用Apache-2.0许可证。


1 回复

以下是基于提供内容整理的完整示例demo,包含序列化、反序列化和嵌套结构处理:

// 1. 基本结构体序列化/反序列化示例
use chia_streamable_macro::Streamable;

#[derive(Streamable, Debug, PartialEq)]
struct Point {
    x: i32,
    y: i32,
}

fn basic_usage() {
    println!("=== 基本用法示例 ===");
    
    // 序列化
    let point = Point { x: 10, y: 20 };
    let mut buffer = Vec::new();
    point.stream_to(&mut buffer).unwrap();
    println!("序列化数据: {:?}", buffer); // 输出小端字节序的字节数组
    
    // 反序列化
    let deserialized = Point::parse(&mut &buffer[..]).unwrap();
    println!("反序列化结果: {:?}", deserialized);
    assert_eq!(point, deserialized);
}

// 2. 嵌套结构体示例
#[derive(Streamable, Debug, PartialEq)]
struct Inner {
    id: u64,
    tags: Vec<String>,
}

#[derive(Streamable, Debug, PartialEq)]
struct Outer {
    version: u32,
    data: Inner,
    active: bool,
}

fn nested_usage() {
    println!("\n=== 嵌套结构示例 ===");
    
    let data = Outer {
        version: 1,
        data: Inner {
            id: 987654321,
            tags: vec!["rust".to_string(), "blockchain".to_string()],
        },
        active: true,
    };
    
    // 带预分配的序列化
    let mut buf = Vec::with_capacity(128); // 预分配缓冲区
    data.stream_to(&mut buf).unwrap();
    println!("嵌套结构序列化数据 ({}字节): {:?}", buf.len(), buf);
    
    // 反序列化验证
    let decoded = Outer::parse(&mut &buf[..]).unwrap();
    assert_eq!(data, decoded);
}

// 3. 自定义类型处理示例
#[derive(Debug, Default, PartialEq)]
struct CustomType(u32, u32);

#[derive(Streamable, Debug, PartialEq)]
struct CustomStruct {
    #[streamable(with = "custom_impl")]
    custom: CustomType,
    normal: String,
}

mod custom_impl {
    use super::CustomType;
    use std::io::{Read, Write, Result};
    
    pub fn stream_to<W: Write>(value: &CustomType, writer: &mut W) -> Result<()> {
        writer.write_all(&value.0.to_le_bytes())?;
        writer.write_all(&value.1.to_le_bytes())
    }
    
    pub fn parse<R: Read>(reader: &mut R) -> Result<CustomType> {
        let mut buf = [0u8; 4];
        reader.read_exact(&mut buf)?;
        let first = u32::from_le_bytes(buf);
        reader.read_exact(&mut buf)?;
        let second = u32::from_le_bytes(buf);
        Ok(CustomType(first, second))
    }
}

fn custom_type_usage() {
    println!("\n=== 自定义类型处理示例 ===");
    
    let data = CustomStruct {
        custom: CustomType(42, 84),
        normal: "test".to_string(),
    };
    
    let mut buf = Vec::new();
    data.stream_to(&mut buf).unwrap();
    println!("包含自定义类型的序列化数据: {:?}", buf);
    
    let decoded = CustomStruct::parse(&mut &buf[..]).unwrap();
    assert_eq!(data, decoded);
}

fn main() {
    basic_usage();
    nested_usage();
    custom_type_usage();
}

这个完整示例展示了:

  1. 基本结构体的序列化/反序列化
  2. 嵌套结构体的处理
  3. 自定义类型的处理方式
  4. 缓冲区预分配等性能优化技巧

输出示例将会显示:

  • 基本Point结构的二进制表示
  • 嵌套结构的序列化结果
  • 包含自定义类型的序列化数据

所有示例都包含断言验证,确保序列化/反序列化过程的正确性。

回到顶部