Trait CBORCodable

Source
pub trait CBORCodable { }
Expand description

A trait for types that can be both encoded to and decoded from CBOR.

This trait is automatically implemented for any type that implements both CBOREncodable and CBORDecodable. It serves as a convenience marker trait to indicate full CBOR serialization support.

§Example

use dcbor::prelude::*;

// Custom type that implements both conversion directions
#[derive(Clone)]
struct Person {
    name: String,
    age: u8,
}

// Implement conversion to CBOR
impl From<Person> for CBOR {
    fn from(person: Person) -> Self {
        let mut map = Map::new();
        map.insert("name", person.name);
        map.insert("age", person.age);
        map.into()
    }
}

// Implement conversion from CBOR
impl TryFrom<CBOR> for Person {
    type Error = dcbor::Error;

    fn try_from(cbor: CBOR) -> dcbor::Result<Self> {
        if let CBORCase::Map(map) = cbor.into_case() {
            let name: String = map.extract("name")?;
            let age: u8 = map.extract("age")?;
            Ok(Person { name, age })
        } else {
            Err("Expected a CBOR map".into())
        }
    }
}

// Person now automatically implements CBORCodable
let person = Person { name: "Alice".to_string(), age: 30 };
let cbor = person.to_cbor(); // Using CBOREncodable

// Create a round-trip copy
let person_copy: Person = cbor.try_into().unwrap(); // Using CBORDecodable

Implementors§