Crate cbor[][src]

This crate provides an implementation of RFC 7049, which specifies Concise Binary Object Representation (CBOR). CBOR adopts and modestly builds on the data model used by JSON, except the encoding is in binary form. Its primary goals include a balance of implementation size, message size and extensibility.

The implementation here is mostly complete. It includes a mechanism for serializing and deserializing your own tags, but it does not yet support indefinite length encoding.

This library is primarily used with type-based encoding and decoding via the rustc-serialize infrastructure, but the raw CBOR abstract syntax is exposed for use cases that call for it.

Example: simple type based encoding and decoding

In this crate, there is a Decoder and an Encoder. All reading and writing of CBOR must go through one of these types.

The following shows how use those types to encode and decode a sequence of data items:

use cbor::{Decoder, Encoder};

// The data we want to encode. Each element in the list is encoded as its own
// separate top-level data item.
let data = vec![(s("a"), 1), (s("b"), 2), (s("c"), 3)];

// Create an in memory encoder. Use `Encoder::from_writer` to write to anything
// that implements `Writer`.
let mut e = Encoder::from_memory();

// Create an in memory decoder. Use `Decoder::from_reader` to read from
// anything that implements `Reader`.
let mut d = Decoder::from_bytes(e.as_bytes());
let items: Vec<(String, i32)> = d.decode().collect::<Result<_, _>>().unwrap();

assert_eq!(items, data);

Example: encode and decode custom tags

This example shows how to encode and decode a custom data type as a CBOR tag:

use cbor::CborTagEncode;
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};

struct MyDataStructure {
    data: Vec<u32>,

impl Encodable for MyDataStructure {
    fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
        // See a list of tags here:
        // It is OK to choose your own tag number, but it's probably
        // best to choose one that is unassigned in the IANA registry.
        CborTagEncode::new(100_000, &

// Note that the special type `CborTagEncode` isn't needed when decoding. You
// can decode into your `MyDataStructure` type directly:
impl Decodable for MyDataStructure {
    fn decode<D: Decoder>(d: &mut D) -> Result<MyDataStructure, D::Error> {
        // Read the tag number and throw it away. YOU MUST DO THIS!
        // The *next* data item is the actual data.
        Ok(MyDataStructure { data: try!(Decodable::decode(d)) })

Any value with type MyDataStructure can now be used the encoding and decoding methods used in the first example.

Example: convert to JSON

Converting to JSON is simple because Cbor implements the ToJson trait:

use cbor::{Decoder, Encoder};
use rustc_serialize::json::{Json, ToJson};

let mut e = Encoder::from_memory();
e.encode(&[vec![(true, (), 1), (false, (), 2)]]).unwrap();

let mut d = Decoder::from_bytes(e.as_bytes());
let cbor = d.items().next().unwrap().unwrap();

assert_eq!(cbor.to_json(), Json::Array(vec![
    Json::Array(vec![Json::Boolean(true), Json::Null, Json::U64(1)]),
    Json::Array(vec![Json::Boolean(false), Json::Null, Json::U64(2)]),

This crate also defines a ToCbor trait and implements it for the Json type, so you can convert JSON to CBOR in a similar manner as above.



A byte string (major type 2).


A tag (major type 6).


A special type that can be used to encode CBOR tags.


An iterator over items decoded from CBOR into Rust values.


Read CBOR data items into Rust values from the underlying reader R.


Experimental and incomplete direct decoder.


Encodes Rust values to CBOR bytes in the underlying writer W.


An iterator over CBOR items in terms of the abstract syntax.



CBOR abstract syntax.


Errors that can be produced by a CBOR operation.


An IEEE 754 floating point number (major type 7).


A negative integer (major type 1).


An unsigned integer (major type 0).


An error produced by reading CBOR data.


All core types defined in the CBOR specification.


An error produced by writing CBOR data.



A trait for converting values to CBOR.

Type Definitions


Type synonym for Result<T, CborError>.