#[derive(AFastSerialize)]
{
// Attributes available to this derive:
#[afast]
}
Expand description
为结构体或枚举生成 AFastSerialize trait 实现。
Generates an AFastSerialize trait implementation for a struct or enum.
§生成的代码 / Generated Code
§结构体 / Struct
为每个字段调用 to_bytes(),并将结果依次追加到字节缓冲区中。
Calls to_bytes() on each field, appending the results to a byte buffer
sequentially.
// 以下为生成代码的示意(非实际代码)
// The following is an illustration of generated code (not actual code)
impl AFastSerialize for MyStruct {
fn to_bytes(&self) -> Vec<u8> {
let mut bytes = Vec::new();
bytes.extend(AFastSerialize::to_bytes(&self.field1));
bytes.extend(AFastSerialize::to_bytes(&self.field2));
// ... 依次处理每个字段 / remaining fields processed similarly
bytes
}
}§枚举 / Enum
先写入 u8 变体索引(从 0 开始),再写入变体的字段数据。
Unit 变体只写入索引。可通过 feature 切换为 u16 或 u32。
Writes a u8 variant index (starting from 0), then the variant’s field data.
Unit variants only write the index. Switchable to u16 or u32 via features.
// 以下为生成代码的示意(非实际代码)
// The following is an illustration of generated code (not actual code)
impl AFastSerialize for MyEnum {
fn to_bytes(&self) -> Vec<u8> {
let mut bytes = Vec::new();
match self {
MyEnum::Variant1 => {
bytes.extend(0u8.to_le_bytes());
}
MyEnum::Variant2(field) => {
bytes.extend(1u8.to_le_bytes());
bytes.extend(AFastSerialize::to_bytes(field));
}
// ...
}
bytes
}
}§泛型 / Generics
如果目标类型包含泛型参数,生成的 impl 会自动为这些参数添加
AFastSerialize 约束。
If the target type contains generic parameters, the generated impl automatically
adds AFastSerialize bounds to those parameters.
§Panics
对 union 类型使用此宏会触发编译 panic。
Using this macro on a union type will trigger a compile-time panic.