Search code examples
rustserdecbor

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


I want to encode Vec<u8> as CBOR byte string using serde_cbor. I tried the following code:

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);

Which generates the following output:

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

This means that all elements are encoded as single integers. However, I want to encode the vector as a CBOR byte string, i.e:

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

How do I do that?


Solution

  • Use the serde_bytes crate and serde_bytes::Bytes and do to_vec(&Bytes::new(&data[..]))? instead.