0

我正在尝试使用serdebincodecrates 为特定结构实现高级序列化/反序列化方案。为了演示,以下代码有效:

use serde::{Serialize, Deserialize};
use bincode::{DefaultOptions, Options};

#[derive(Debug, Serialize, Deserialize)]
enum Command {
    Operation(u8),
    Element(Vec<u8>)
}

fn main() {
    let commands: Vec<Command> = vec![Command::Operation(150), Command::Operation(175), Command::Element(b"123".to_vec())];
    
    let bytes = DefaultOptions::new()
                    .with_varint_encoding()
                    .serialize(&commands).unwrap();

    println!("{:?}", bytes);

    let commands: Vec<Command> = DefaultOptions::new()
                    .with_varint_encoding()
                    .deserialize(&bytes[..]).unwrap();

    println!("{:?}", commands);
}

输出:

[3, 0, 150, 0, 175, 1, 3, 49, 50, 51]
[Operation(150), Operation(175), Element([49, 50, 51])]

但是,我想以更压缩的格式序列化数据。不应该有明确的标签来标识数据包含哪个变体,而是我希望它从相应的字节派生;如果字节小于 100 则为 Element Vec<u8>,否则为 Command u8。我试过这样#[serde(untagged)]设置Command

#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
enum Command {
    Operation(u8),
    Element(Vec<u8>)
}

我得到以下输出:

[3, 150, 175, 3, 49, 50, 51]
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: DeserializeAnyNotSupported', src/main.rs:45:46
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

第一次打印是正确的,但我不确定如何实现如上所述的反序列化。

4

0 回答 0