使用 serde_cbor 在 Rust 中将 Vec<u8> 序列化为 CBOR 字节字符串

Serializing a Vec<u8> to CBOR byte string in Rust using serde_cbor

我想使用 serde_cborVec<u8> 编码为 CBOR 字节字符串。我尝试了以下代码:

use serde_cbor::{to_vec}

let data = vec![0x01, 0x23, 0x45, 0x67, 0x89, 0xab];
let encoded_data = to_vec(&data)?;
println!("encoded_data: {:x?}", encoded_data);

生成以下输出:

encoded_data: [86, 1, 18, 23, 18, 45, 18, 67, 18, 89, 18, ab]

这意味着所有元素都被编码为单个整数。但是,我想将向量编码为 CBOR 字节字符串,即:

46              # bytes(6)
   0123456789AB # "\x01#Eg\x89\xAB"

我该怎么做?

使用 serde_bytes crate and serde_bytes::Bytes 并执行 to_vec(&Bytes::new(&data[..]))?