Skip to main content

Module serde

Module serde 

Source
Available on crate feature serde only.
Expand description

Serde integration for CBOR Value.

This module provides Serialize and Deserialize implementations for Value, as well as the convenience functions to_value and from_value for converting between arbitrary Rust types and Value through serde.

§Converting Rust types to Value

Any type that implements Serialize can be converted into a Value with to_value:

use cbor_core::serde::to_value;

#[derive(serde::Serialize)]
struct Sensor {
    id: u32,
    label: String,
    readings: Vec<f64>,
}

let s = Sensor {
    id: 7,
    label: "temperature".into(),
    readings: vec![20.5, 21.0, 19.8],
};

let v = to_value(&s).unwrap();
assert_eq!(v["id"].to_u32().unwrap(), 7);
assert_eq!(v["label"].as_str().unwrap(), "temperature");
assert_eq!(v["readings"][0].to_f64().unwrap(), 20.5);

§Converting Value to Rust types

from_value goes the other direction, extracting a Deserialize type from a Value:

use cbor_core::{Value, map, array};
use cbor_core::serde::from_value;

#[derive(serde::Deserialize, Debug, PartialEq)]
struct Sensor {
    id: u32,
    label: String,
    readings: Vec<f64>,
}

let v = map! {
    "id" => 7,
    "label" => "temperature",
    "readings" => array![20.5, 21.0, 19.8],
};

let s: Sensor = from_value(&v).unwrap();
assert_eq!(s.id, 7);
assert_eq!(s.label, "temperature");

§Serializing Value with other formats

Because Value implements Serialize and Deserialize, it works directly with any serde-based format such as JSON:

use cbor_core::{Value, map};

let v = map! { "x" => 1, "y" => 2 };
let json = serde_json::to_string(&v).unwrap();

let back: Value = serde_json::from_str(&json).unwrap();
assert_eq!(back["x"].to_i32().unwrap(), 1);

§Tags and CBOR-specific types

The serde data model does not have a notion of CBOR tags or simple values. During deserialization, tags are stripped and their inner content is used directly — with the exception of big integers (tags 2 and 3), which are recognized and deserialized as integers. During serialization, tags are only emitted for big integers that exceed the u64/i64 range; all other values are untagged.

Tagged values and arbitrary simple values cannot be created through the serde interface. For full control over the encoded CBOR structure, build Values directly using the constructors on Value (e.g. Value::tag, Value::simple_value).

Structs§

Error
Error type returned by serde operations on Value.

Functions§

from_value
Convert a CBOR Value into any Deserialize type.
to_value
Convert any Serialize value into a CBOR Value.