RustTraining 实战指南:serde 序列化、零拷贝反序列化与二进制数据处理(Rust Patterns Book 第 11 章)
RustTraining 实战指南:serde 序列化、零拷贝反序列化与二进制数据处理(Rust Patterns Book 第 11 章)
本指南以 RustTraining 仓库中 rust-patterns-book(Rust Patterns & Engineering How-Tos)第 11 章为核心,系统讲解 Rust 生态最通用的序列化框架 serde 的派生宏、容器/字段属性与四种枚举表示,深入剖析零拷贝(zero-copy)反序列化及其生命周期约束,并覆盖
repr(C)二进制布局、zerocopy/bytemuck 安全转写与bytes::Bytes引用计数缓冲区等硬件诊断与网络协议场景的核心工具。读完本篇,你将能熟练编写"一套数据结构、多格式通用"的序列化代码,能在高吞吐读取场景中消除不必要的堆分配,并能安全、零拷贝地解析硬件寄存器布局与二进制协议报文。
本章定位与前置知识
第 11 章在整本书中属于 Intermediate(🟡) 难度:根据 ch00-introduction.md 中的难度图例与节奏指南,🟡 代表"Production codebases 中使用的模式",建议学习时长 2~3 小时,通关标准是 "Can write a custom serde deserializer(能够编写自定义 serde 反序列化器)"。它处于 Part III: Systems & Production(系统与生产)部分,前接 第 10 章错误处理(thiserror/anyhow),后接 第 12 章 Unsafe Rust(repr(C) 与 FFI 数据布局)。
阅读本章前建议掌握:
- 所有权、借用与生命周期(基础水平);
- 结构体、枚举与
Option/Result、模式匹配; - 基本 trait(
Display、Debug、Clone); - Cargo 基本操作:
cargo build、cargo test、cargo run。
serde 基础:数据模型与格式分离
serde(SERialize/DEserialize)是 Rust 的通用序列化框架,其核心设计是把数据模型(你的结构体/枚举)与格式(JSON、TOML、二进制等)彻底解耦。同一个结构体只需派生一次 Serialize/Deserialize,之后就能配合所有 serde 兼容格式使用——JSON、TOML、YAML、bincode、MessagePack、CBOR、postcard 等数十种。
use serde::{Serialize, Deserialize};
#[derive(Debug, Serialize, Deserialize)]
struct ServerConfig {
name: String,
port: u16,
#[serde(default)] // Use Default::default() if missing
max_connections: usize,
#[serde(skip_serializing_if = "Option::is_none")]
tls_cert_path: Option<String>,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Deserialize from JSON:
let json_input = r#"{
"name": "hw-diag",
"port": 8080
}"#;
let config: ServerConfig = serde_json::from_str(json_input)?;
println!("{config:?}");
// ServerConfig { name: "hw-diag", port: 8080, max_connections: 0, tls_cert_path: None }
// Serialize to JSON:
let output = serde_json::to_string_pretty(&config)?;
println!("{output}");
// Same struct, different format — no code changes:
let toml_input = r#"
name = "hw-diag"
port = 8080
"#;
let config: ServerConfig = toml::from_str(toml_input)?;
println!("{config:?}");
Ok(())
}
关键洞察:你的结构体只需派生一次
Serialize和Deserialize,随后即可用于每一种 serde 兼容格式——JSON、TOML、YAML、bincode、MessagePack、CBOR、postcard 等数十种,代码零改动。
这一"泛型 + trait 约束"的能力在本书第 1 章中也有印证:ch01-generics-the-full-picture.md 展示了用 T: serde::Serialize 泛型约束编写的通用序列化函数,这正是 serde 将类型系统用于格式抽象的直接体现:
fn serialize<T: serde::Serialize>(value: &T) -> Vec<u8> {
serde_json::to_vec(value).unwrap()
}
常用 serde 属性:容器级与字段级
serde 通过容器属性(struct/enum 上)与字段属性(字段上)提供对序列化行为的细粒度控制:
use serde::{Serialize, Deserialize};
// --- Container attributes (on the struct/enum) ---
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")] // JSON convention: field_name → fieldName
#[serde(deny_unknown_fields)] // Reject extra keys — strict parsing
struct DiagResult {
test_name: String, // Serialized as "testName"
pass_count: u32, // Serialized as "passCount"
fail_count: u32, // Serialized as "failCount"
}
// --- Field attributes ---
#[derive(Serialize, Deserialize)]
struct Sensor {
#[serde(rename = "sensor_id")] // Override field name for serialization
id: u64,
#[serde(default)] // Use Default if missing from input
enabled: bool,
#[serde(default = "default_threshold")]
threshold: f64,
#[serde(skip)] // Never serialize or deserialize
cached_value: Option<f64>,
#[serde(skip_serializing_if = "Vec::is_empty")]
tags: Vec<String>,
#[serde(flatten)] // Inline nested struct fields
metadata: Metadata,
#[serde(with = "hex_bytes")] // Custom ser/de module
raw_data: Vec<u8>,
}
fn default_threshold() -> f64 { 1.0 }
#[derive(Serialize, Deserialize)]
struct Metadata {
vendor: String,
model: String,
}
// With #[serde(flatten)], the JSON looks like:
// { "sensor_id": 1, "vendor": "Intel", "model": "X200", ... }
// NOT: { "sensor_id": 1, "metadata": { "vendor": "Intel", ... } }
最常用属性速查表:
| Attribute | Level | Effect |
|---|---|---|
rename_all = "camelCase" |
Container | Rename all fields to camelCase/snake_case/SCREAMING_SNAKE_CASE |
deny_unknown_fields |
Container | Error on unexpected keys (strict mode) |
default |
Field | Use Default::default() when field missing |
rename = "..." |
Field | Custom serialized name |
skip |
Field | Exclude from ser/de entirely |
skip_serializing_if = "fn" |
Field | Conditionally exclude (e.g., Option::is_none) |
flatten |
Field | Inline a nested struct's fields |
with = "module" |
Field | Use custom serialize/deserialize functions |
alias = "..." |
Field | Accept alternative names during deserialization |
deserialize_with = "fn" |
Field | Custom deserialize function only |
untagged |
Enum | Try each variant in order (no discriminant in output) |
其中 deny_unknown_fields 是实现"严格模式"解析的关键:配置项拼写错误会在反序列化阶段直接报错,而不是静默丢弃,这一模式与本书第 15 章讨论的 "parse, don't validate"(在边界解析,而非处处校验) 理念一致——ch15-crate-architecture-and-api-design.md 中给出的 load_config 模式就是先在边界用 serde_json::from_str 解析出 RawConfig,再通过 ValidConfig::try_from(raw) 完成全部校验。
枚举的四种表示(Representation)
在 JSON 这类格式中,serde 为枚举提供了四种表示方式,各自对应不同的数据形状与兼容性取舍:
use serde::{Serialize, Deserialize};
// 1. Externally tagged (DEFAULT):
#[derive(Serialize, Deserialize)]
enum Command {
Reboot,
RunDiag { test_name: String, timeout_secs: u64 },
SetFanSpeed(u8),
}
// "Reboot" → Command::Reboot
// {"RunDiag": {"test_name": "gpu", "timeout_secs": 60}} → Command::RunDiag { ... }
// 2. Internally tagged — #[serde(tag = "type")]:
#[derive(Serialize, Deserialize)]
#[serde(tag = "type")]
enum Event {
Start { timestamp: u64 },
Error { code: i32, message: String },
End { timestamp: u64, success: bool },
}
// {"type": "Start", "timestamp": 1706000000}
// {"type": "Error", "code": 42, "message": "timeout"}
// 3. Adjacently tagged — #[serde(tag = "t", content = "c")]:
#[derive(Serialize, Deserialize)]
#[serde(tag = "t", content = "c")]
enum Payload {
Text(String),
Binary(Vec<u8>),
}
// {"t": "Text", "c": "hello"}
// {"t": "Binary", "c": [0, 1, 2]}
// 4. Untagged — #[serde(untagged)]:
#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum StringOrNumber {
Str(String),
Num(f64),
}
// "hello" → StringOrNumber::Str("hello")
// 42.0 → StringOrNumber::Num(42.0)
// ⚠️ Tried IN ORDER — first matching variant wins
如何选择:大多数 JSON API 优先使用 internally tagged(
tag = "type")——它可读性最好,且与 Go、Python、TypeScript 社区的惯例一致。Untagged 只用于"联合类型(union)"场景,即仅凭数据形状就能区分各变体的情况。
零拷贝反序列化(Zero-Copy Deserialization)
serde 可以不分配任何新字符串完成反序列化——字段直接借用输入缓冲区中的字节。这是高性能解析的关键:
use serde::Deserialize;
// --- Owned (allocating) ---
// Each String field copies bytes from the input into new heap allocations.
#[derive(Deserialize)]
struct OwnedRecord {
name: String, // Allocates a new String
value: String, // Allocates another String
}
// --- Zero-copy (borrowing) ---
// &'de str fields borrow directly from the input — ZERO allocation.
#[derive(Deserialize)]
struct BorrowedRecord<'a> {
name: &'a str, // Points into the input buffer
value: &'a str, // Points into the input buffer
}
fn main() {
let input = r#"{"name": "cpu_temp", "value": "72.5"}"#;
// Owned: allocates two String objects
let owned: OwnedRecord = serde_json::from_str(input).unwrap();
// Zero-copy: `name` and `value` point into `input` — no allocation
let borrowed: BorrowedRecord = serde_json::from_str(input).unwrap();
// The output is lifetime-bound: borrowed can't outlive input
println!("{}: {}", borrowed.name, borrowed.value);
}
理解生命周期:Deserialize<'de> 与 DeserializeOwned
// Deserialize<'de> — the struct can borrow from data with lifetime 'de:
// struct BorrowedRecord<'a> where 'a == 'de
// Only works when the input buffer lives long enough
// DeserializeOwned — the struct owns all its data, no borrowing:
// trait DeserializeOwned: for<'de> Deserialize<'de> {}
// Works with any input lifetime (the struct is independent)
use serde::de::DeserializeOwned;
// This function requires owned types — input can be temporary
fn parse_owned<T: DeserializeOwned>(input: &str) -> T {
serde_json::from_str(input).unwrap()
}
// This function allows borrowing — more efficient but restricts lifetimes
fn parse_borrowed<'a, T: Deserialize<'a>>(input: &'a str) -> T {
serde_json::from_str(input).unwrap()
}
从类型系统的角度看,DeserializeOwned 的 for<'de> Deserialize<'de> 是一个典型的 HRTB(Higher-Ranked Trait Bound)。本书第 2 章 ch02-traits-in-depth.md 对这一点有专门讲解:for<'de> 意味着"可以从任意生命周期的数据中反序列化",即结果不借用输入;当你看到编译器报出类似 "expected a for<'de> Deserialize<'de> bound" 的错误时,说明它要求的正是一个 owned 类型约束。
何时使用 / 何时不使用零拷贝
适合使用零拷贝的场景:
- 解析大文件,且你只需要其中少量字段;
- 高吞吐管道(网络数据包、日志行解析);
- 输入缓冲区本身寿命足够长(例如 memory-mapped 文件)。
不适合使用零拷贝的场景:
- 输入是临时数据(例如会被复用的网络读缓冲区);
- 需要把结果保存到超过输入生命周期的位置;
- 字段需要变换(转义处理、规范化等)。
实用技巧:
Cow<'a, str>两全其美——能借用时借用,必要时才分配(例如 JSON 转义序列需要 unescape 时)。serde 原生支持Cow。
格式生态:一套结构,N 种格式
| Format | Crate | Human-Readable | Size | Speed | Use Case |
|---|---|---|---|---|---|
| JSON | serde_json |
✅ | Large | Good | Config files, REST APIs, logging |
| TOML | toml |
✅ | Medium | Good | Config files (Cargo.toml style) |
| YAML | serde_yaml |
✅ | Medium | Good | Config files (complex nesting) |
| bincode | bincode |
❌ | Small | Fast | IPC, caches, Rust-to-Rust |
| postcard | postcard |
❌ | Tiny | Very fast | Embedded systems, no_std |
| MessagePack | rmp-serde |
❌ | Small | Fast | Cross-language binary protocol |
| CBOR | ciborium |
❌ | Small | Fast | IoT, constrained environments |
// Same struct, many formats — serde's power:
#[derive(serde::Serialize, serde::Deserialize, Debug)]
struct DiagConfig {
name: String,
tests: Vec<String>,
timeout_secs: u64,
}
let config = DiagConfig {
name: "accel_diag".into(),
tests: vec!["memory".into(), "compute".into()],
timeout_secs: 300,
};
// JSON: {"name":"accel_diag","tests":["memory","compute"],"timeout_secs":300}
let json = serde_json::to_string(&config).unwrap(); // 67 bytes
// bincode: compact binary — ~40 bytes, no field names
let bin = bincode::serialize(&config).unwrap(); // Much smaller
// postcard: even smaller, varint encoding — great for embedded
// let post = postcard::to_allocvec(&config).unwrap();
如何选择格式:
- 人类编辑的配置文件 → TOML 或 JSON
- Rust 与 Rust 之间的 IPC/缓存 → bincode(快、紧凑,但不跨语言)
- 跨语言二进制协议 → MessagePack 或 CBOR
- 嵌入式 /
no_std→ postcard
值得注意的工程细节是:当你在自己的 crate 中把 serde 格式作为可选能力提供时,应采用 feature flag + optional dependency 的方式。ch15-crate-architecture-and-api-design.md 给出了标准写法——serde_json = { version = "1", optional = true },并通过 #[cfg(feature = "json")] 条件编译暴露 to_json 等函数,用户按需开启 json/xml 特性,这与 serde 自身"数据模型与格式解耦"的思想一脉相承。
二进制数据与 repr(C)
对硬件诊断类程序而言,解析二进制协议数据是家常便饭。Rust 提供了安全、零拷贝的二进制数据处理工具:
// --- #[repr(C)]: Predictable memory layout ---
// Ensures fields are laid out in declaration order with C padding rules.
// Essential for matching hardware register layouts and protocol headers.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
struct IpmiHeader {
rs_addr: u8,
net_fn_lun: u8,
checksum: u8,
rq_addr: u8,
rq_seq_lun: u8,
cmd: u8,
}
// --- Safe binary parsing with manual deserialization ---
impl IpmiHeader {
fn from_bytes(data: &[u8]) -> Option<Self> {
if data.len() < size_of::<Self>() {
return None;
}
Some(IpmiHeader {
rs_addr: data[0],
net_fn_lun: data[1],
checksum: data[2],
rq_addr: data[3],
rq_seq_lun: data[4],
cmd: data[5],
})
}
fn net_fn(&self) -> u8 { self.net_fn_lun >> 2 }
fn lun(&self) -> u8 { self.net_fn_lun & 0x03 }
}
// --- Endianness-aware parsing ---
fn read_u16_le(data: &[u8], offset: usize) -> u16 {
u16::from_le_bytes([data[offset], data[offset + 1]])
}
fn read_u32_be(data: &[u8], offset: usize) -> u32 {
u32::from_be_bytes([
data[offset], data[offset + 1],
data[offset + 2], data[offset + 3],
])
}
// --- #[repr(C, packed)]: Remove padding (alignment = 1) ---
#[repr(C, packed)]
#[derive(Debug, Clone, Copy)]
struct PcieCapabilityHeader {
cap_id: u8, // Capability ID
next_cap: u8, // Pointer to next capability
cap_reg: u16, // Capability-specific register
}
// ⚠️ Packed structs: taking &field creates an unaligned reference — UB.
// Always copy fields out: let id = header.cap_id; // OK (Copy)
// Never do: let r = &header.cap_reg; // UB if unaligned
这里有几个必须强调的要点:
repr(C)保证字段按声明顺序、按 C 填充规则布局,这是匹配硬件寄存器布局和协议头的必要条件;没有repr(C),Rust 可以任意重排字段。read_u16_le/read_u32_be展示了字节序感知的手工解析——网络协议与硬件寄存器通常规定明确的大端/小端字节序,from_le_bytes/from_be_bytes是标准库提供的安全转换。repr(C, packed)将对齐强制为 1、去除填充,代价是对字段取引用可能产生未对齐引用,属于未定义行为(UB)。安全做法永远是先把字段拷贝出来(Copy类型直接赋值),绝不要写&header.cap_reg这样的代码。
repr(C) 数据布局的底层语义在本书 第 12 章 Unsafe Rust 中有更深入的展开——那里会讲到 union 字段访问、FFI 边界以及用安全抽象封装 unsafe 实现的完整原则。
zerocopy 与 bytemuck:编译期校验的安全转写
与其手写 unsafe transmute,不如使用在编译期就校验布局安全性的 crate:
// --- zerocopy: Compile-time checked zero-copy conversions ---
// Cargo.toml: zerocopy = { version = "0.8", features = ["derive"] }
use zerocopy::{FromBytes, IntoBytes, KnownLayout, Immutable};
#[derive(FromBytes, IntoBytes, KnownLayout, Immutable, Debug)]
#[repr(C)]
struct SensorReading {
sensor_id: u16,
flags: u8,
_reserved: u8,
value: u32, // Fixed-point: actual = value / 1000.0
}
fn parse_sensor(raw: &[u8]) -> Option<&SensorReading> {
// Safe zero-copy: verifies alignment and size AT COMPILE TIME
SensorReading::ref_from_bytes(raw).ok()
// Returns &SensorReading pointing INTO raw — no copy, no allocation
}
// --- bytemuck: Simple, battle-tested ---
// Cargo.toml: bytemuck = { version = "1", features = ["derive"] }
use bytemuck::{Pod, Zeroable};
#[derive(Pod, Zeroable, Clone, Copy, Debug)]
#[repr(C)]
struct GpuRegister {
address: u32,
value: u32,
}
fn cast_registers(data: &[u8]) -> &[GpuRegister] {
// Safe cast: Pod guarantees all bit patterns are valid
bytemuck::cast_slice(data)
}
何时用哪个:
| Approach | Safety | Overhead | Use When |
|---|---|---|---|
| Manual field-by-field parsing | ✅ Safe | Copy fields | Small structs, complex layouts |
zerocopy |
✅ Safe | Zero-copy | Large buffers, many reads, compile-time checks |
bytemuck |
✅ Safe | Zero-copy | Simple Pod types, casting slices |
unsafe { transmute() } |
❌ Unsafe | Zero-copy | Last resort — avoid in application code |
选型要点:zerocopy 通过 FromBytes/IntoBytes 等 derive 宏在编译期验证类型大小、对齐与布局,ref_from_bytes 返回的引用直接指向输入缓冲区,零拷贝零分配;bytemuck 的 Pod(Plain Old Data)trait 保证类型的任何位模式都合法,因此可以安全地把 &[u8] 直接 cast_slice 成 &[GpuRegister]。两者都把"以前要靠 unsafe transmute 才能做的事"变成了完全安全、编译器可证明的操作。
bytes::Bytes:引用计数缓冲区
bytes crate(tokio、hyper、tonic 均依赖它)提供带引用计数的零拷贝字节缓冲区——Bytes 之于 Vec<u8>,正如 Arc<[u8]> 之于 owned slice:
use bytes::{Bytes, BytesMut, Buf, BufMut};
fn main() {
// --- BytesMut: mutable buffer for building data ---
let mut buf = BytesMut::with_capacity(1024);
buf.put_u8(0x01); // Write a byte
buf.put_u16(0x1234); // Write u16 (big-endian)
buf.put_slice(b"hello"); // Write raw bytes
buf.put(&b"world"[..]); // Write from slice
// Freeze into immutable Bytes (zero cost):
let data: Bytes = buf.freeze();
// --- Bytes: immutable, reference-counted, cloneable ---
let data2 = data.clone(); // Cheap: increments refcount, NOT deep copy
let slice = data.slice(3..8); // Zero-copy sub-slice (shares buffer)
// Read from Bytes using the Buf trait:
let mut reader = &data[..];
let byte = reader.get_u8(); // 0x01
let short = reader.get_u16(); // 0x1234
// Split without copying:
let mut original = Bytes::from_static(b"HEADER\x00PAYLOAD");
let header = original.split_to(6); // header = "HEADER", original = "\x00PAYLOAD"
println!("header: {:?}", &header[..]);
println!("payload: {:?}", &original[1..]);
}
BytesMut 负责构建(可写、可扩容),调用 freeze() 后零成本转换为不可变、可共享的 Bytes;Buf/BufMut trait 提供 get_u8/put_u16 等字节序感知的读写原语,与上一节 from_le_bytes 的手工解析互为补充。
bytes vs Vec<u8>:
| Feature | Vec<u8> |
Bytes |
|---|---|---|
| Clone cost | O(n) deep copy | O(1) refcount increment |
| Sub-slicing | Borrows with lifetime | Owned, refcount-tracked |
| Thread safety | Not Sync (needs Arc) |
Send + Sync built in |
| Mutability | Direct &mut |
Split into BytesMut first |
| Ecosystem | Standard library | tokio, hyper, tonic, axum |
何时使用 bytes:网络协议、数据包解析,以及任何"收到一个缓冲区后需要把它拆分成多个部分、交给不同组件或线程处理"的场景。零拷贝的
split_to/slice是它的杀手锏。
整体架构一览
下图(原文档所附)总结了 serde 的解耦架构:多种输入格式(JSON、TOML、bincode、MessagePack)经 Deserialize 汇入统一的 serde 数据模型,产出 Rust struct/enum;反向经 Serialize 输出到任意格式:
flowchart LR
subgraph Input
JSON["JSON"]
TOML["TOML"]
Bin["bincode"]
MsgP["MessagePack"]
end
subgraph serde["serde data model"]
Ser["Serialize"]
De["Deserialize"]
end
subgraph Output
Struct["Rust struct"]
Enum["Rust enum"]
end
JSON --> De
TOML --> De
Bin --> De
MsgP --> De
De --> Struct
De --> Enum
Struct --> Ser
Enum --> Ser
Ser --> JSON
Ser --> Bin
style JSON fill:#e8f4f8,stroke:#2980b9,color:#000
style TOML fill:#e8f4f8,stroke:#2980b9,color:#000
style Bin fill:#e8f4f8,stroke:#2980b9,color:#000
style MsgP fill:#e8f4f8,stroke:#2980b9,color:#000
style Ser fill:#fef9e7,stroke:#f1c40f,color:#000
style De fill:#fef9e7,stroke:#f1c40f,color:#000
style Struct fill:#d4efdf,stroke:#27ae60,color:#000
style Enum fill:#d4efdf,stroke:#27ae60,color:#000
实战练习:自定义 serde 反序列化(★★★,约 45 分钟)
设计一个 HumanDuration 包装类型,能够从 "30s"、"5m"、"2h" 这类人类可读字符串反序列化,并能序列化回同样的格式。这正好对应本章的通关标准——"能编写自定义 serde 反序列化器",也直接复用了 第 10 章错误处理 中 thiserror 错误定义与 serde 错误集成的思路。
🔑 参考答案
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
#[derive(Debug, Clone, PartialEq)]
struct HumanDuration(std::time::Duration);
impl HumanDuration {
fn from_str(s: &str) -> Result<Self, String> {
let s = s.trim();
if s.is_empty() { return Err("empty duration string".into()); }
let (num_str, suffix) = s.split_at(
s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len())
);
let value: u64 = num_str.parse()
.map_err(|_| format!("invalid number: {num_str}"))?;
let duration = match suffix {
"s" | "sec" => std::time::Duration::from_secs(value),
"m" | "min" => std::time::Duration::from_secs(value * 60),
"h" | "hr" => std::time::Duration::from_secs(value * 3600),
"ms" => std::time::Duration::from_millis(value),
other => return Err(format!("unknown suffix: {other}")),
};
Ok(HumanDuration(duration))
}
}
impl fmt::Display for HumanDuration {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let secs = self.0.as_secs();
if secs == 0 {
write!(f, "{}ms", self.0.as_millis())
} else if secs % 3600 == 0 {
write!(f, "{}h", secs / 3600)
} else if secs % 60 == 0 {
write!(f, "{}m", secs / 60)
} else {
write!(f, "{}s", secs)
}
}
}
impl Serialize for HumanDuration {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.to_string())
}
}
impl<'de> Deserialize<'de> for HumanDuration {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
HumanDuration::from_str(&s).map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Deserialize, Serialize)]
struct Config {
timeout: HumanDuration,
retry_interval: HumanDuration,
}
fn main() {
let json = r#"{ "timeout": "30s", "retry_interval": "5m" }"#;
let config: Config = serde_json::from_str(json).unwrap();
assert_eq!(config.timeout.0, std::time::Duration::from_secs(30));
assert_eq!(config.retry_interval.0, std::time::Duration::from_secs(300));
let serialized = serde_json::to_string(&config).unwrap();
assert!(serialized.contains("30s"));
println!("Config: {serialized}");
}
解题要点拆解:
- 解析:用
split_at在首个非数字字符处切分数字与后缀,后缀匹配s/sec、m/min、h/hr、ms; - 错误处理:所有失败路径返回
String错误,最后通过serde::de::Error::custom转成 serde 错误——这正是 第 10 章 中#[error("...")]+#[from]错误转换链在序列化场景的具体应用; - 双向对称:
Serialize走serialize_str,Deserialize走String::deserialize,保证 round-trip 一致; - 零侵入:
HumanDuration作为字段类型嵌入Config,对外完全透明。
与其他章节的关联
- 错误处理:serde 解析错误通过
thiserror的#<a href="https://link.gitcode.com/i/fc4d972dde6659b73cda529f38aaad93" target="_blank">from] serde_json::Error自动转换,详见 [第 10 章错误处理模式(其中AppError::Json(#[from] serde_json::Error)与parse_json函数即是完整示例); - Unsafe 与 FFI:
repr(C)的布局语义、union 字段访问与 FFI 数据布局详见 第 12 章 Unsafe Rust——可控的危险; - 泛型与 trait:
for<'de> Deserialize<'de>的 HRTB 机制、DeserializeOwned的语义详见 第 2 章 Traits 深入; - API 设计:可选格式依赖的 feature flag 写法、边界解析模式详见 第 15 章 crate 架构与 API 设计。
关键要点总结
- serde 的派生宏能覆盖约 90% 的用例,其余用属性(
rename、skip、default、flatten等)解决; - 零拷贝反序列化(结构体中使用
&'a str)为读密集型负载消除分配;用Cow<'a, str>在借用与分配之间取得平衡; - 硬件寄存器布局用
repr(C)+zerocopy/bytemuck(编译期安全校验,绝不手写unsafe transmute);引用计数缓冲区用bytes::Bytes,其零拷贝split_to/slice是网络协议解析的核心武器。
本仓库为只读培训材料,你可以按 README.md 的指引选择合适路径学习;本文涉及的第 11 章源码级细节与相关章节佐证均可直接在 rust-patterns-book/src/ 目录下继续查阅(书籍目录见 SUMMARY.md)。