如何使用 serde_cbor 打印有效的 CBOR?

How to print valid CBOR using serde_cbor?

我想将一个结构序列化为 CBOR 并打印出来,但是我不知道如何验证打印的值是否正确。我用了 CBOR.me, but every time I place the output in cbor.me it reports Out of bytes to decode: 753 + 19 > 753 where 753 is the number of bytes of CBOR provided, I get this error regardless of bytes. This happens regardless of whether I use serde_cbor::to_vec, or serde_cbor::to_vec_sd.

#![feature(custom_derive, plugin)]
#![plugin(serde_macros)]

extern crate serde;
extern crate serde_cbor;


#[derive(Deserialize, Serialize)]
struct Points {
    x: u8,
    y: u8,
}


fn main() {
    let points = Points {x: 1, y: 1};
    let cbor = serde_cbor::to_vec(&points);

    for byte in cbor {
        print!("{:x}", byte);
    }

    println!("");
}

这是你的输出和正确的输出:

a2 61 78 16 17 91
a2 61 78 01 61 79 01

你看到问题了吗?

a2 61 78  1 61 79  1
a2 61 78 01 61 79 01

您正在打印十六进制值,但没有将它们补零为 2 个字符:

print!("{:02x}", byte);