Search code examples
rustcbor

How to print valid CBOR using serde_cbor?


I want to serialize a struct into CBOR and print it out, however I don't know how to validate that the printed value is correct. I used 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!("");
}

Solution

  • Here's what your output and the correct output would be:

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

    Do you see the problem?

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

    You are printing values out as hexadecimal, but not zero-padding them to 2 characters:

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