rust- 结构体与二进制数组转换

将结构体当二进制流传输是做网络编程时传输协议的常用功能。golang语言可以使用包 encoding/binary实现,例如

go 复制代码
import (
	"encoding/binary"
	"os"
)

...
err := binary.Write(f, binary.LittleEndian, p)
...

rust中可以使用 deku将结构体实例转换为bytes数组。

安装依赖

rust 复制代码
use anyhow;
use anyhow::bail;
use deku::prelude::*;
use std::net::TcpStream;
use std::{
    io::{Read, Write},
};

定义结构体

rust 复制代码
#[derive(Debug, PartialEq, DekuRead, DekuWrite, Default)]
struct Message {
    #[deku(endian = "big")]
    msgtype: u32,
    #[deku(endian = "big")]
    taskid: i32,
    #[deku(endian = "big")]
    utctime: u32,
    #[deku(endian = "big", update = "self.data.len()")]
    bodylen: u32,
    #[deku(count = "bodylen", endian = "little")]
    data: Vec<u8>,
}

注意上面的结构体,整数字段有些是使用大段规则,有些是使用小段规则,可以通过如下的宏实现

rust 复制代码
#[deku(endian = "big")]` 

或

#[deku(endian = "little")]

通常在定义协议时,需要知道协议体的长度,但是协议的body部分通常是可变的,例如data: Vec<u8>,只有在结构体初始化时才知道body的长度,所以这里使用如下宏延迟计算了协议的长度,如下

rust 复制代码
#[deku(endian = "big", update = "self.data.len()")]
#[deku(count = "bodylen", endian = "little")]

将结构体转换为字节流发送

添加如下宏后

rust 复制代码
#[derive(Debug, PartialEq, DekuRead, DekuWrite, Default)]

则可以调用 to_bytes()方法进行转换。

将转换后的二进制发送到tcp服务器,如下

rust 复制代码
impl Message {

    fn send(&self) -> anyhow::Result<()> {
        // 将结构体转换为二进制
        let binary_data = self.to_bytes()?;

        // tcp发送二进制消息
        let mut stream =
            match TcpStream::connect(self.host) {
                Ok(stream) => stream,
                Err(e) => {
                    bail!(
                        "Couldn't connect to server {} {}",
                        self.host,
                        e
                    )
                }
            };
        stream.write_all(&binary_data)?;
        stream.flush()?;

        Ok(())
    }
}
相关推荐
芒鸽18 小时前
macos上Rust 命令行工具鸿蒙化适配完全攻略
macos·rust·harmonyos
Smart-Space19 小时前
为pngme拓展加密功能与jpg格式支持
rust
古城小栈1 天前
Rust Vec与HashMap全功能解析:定义、使用与进阶技巧
算法·rust
techdashen2 天前
Rust OnceCell 深度解析:延迟初始化的优雅解决方案
开发语言·oracle·rust
superman超哥2 天前
Serde 的零成本抽象设计:深入理解 Rust 序列化框架的哲学
开发语言·rust·开发工具·编程语言·rust序列化
星辰徐哥2 天前
Rust函数与流程控制——构建逻辑清晰的系统级程序
开发语言·后端·rust
superman超哥2 天前
序列化格式的灵活切换:Serde 生态的统一抽象力量
开发语言·rust·编程语言·rust serde·序列化格式·rust序列化格式
superman超哥3 天前
派生宏(Derive Macro)的工作原理:编译时元编程的艺术
开发语言·rust·开发工具·编程语言·rust派生宏·derive macro·rust元编程
superman超哥3 天前
处理复杂数据结构:Serde 在实战中的深度应用
开发语言·rust·开发工具·编程语言·rust serde·rust数据结构
superman超哥3 天前
错误处理与验证:Serde 中的类型安全与数据完整性
开发语言·rust·编程语言·rust编程·rust错误处理与验证·rust serde