pub trait CBORDecodable: TryFrom<CBOR, Error = Error> {
// Provided method
fn try_from_cbor(cbor: &CBOR) -> Result<Self> { ... }
}Expand description
A trait for types that can be decoded from CBOR.
This trait is automatically implemented for any type that implements
TryFrom<CBOR>. It serves as a marker trait to indicate that a type
supports being created from CBOR data.
§Example
use dcbor::prelude::*;
// Custom type that implements TryFrom<CBOR>
struct Person {
name: String,
age: u8,
}
// 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())
}
}
}
// The CBORDecodable trait is automatically implemented
// Convert a CBOR object to our type
// Create a sample CBOR map
let mut map = Map::new();
map.insert("name", "Alice");
map.insert("age", 42);
let cbor = map.to_cbor();
// Parse from CBOR to our type
let person: Person = cbor.try_into().unwrap();Provided Methods§
fn try_from_cbor(cbor: &CBOR) -> Result<Self>
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.