pub struct CBOR(/* private fields */);Expand description
A symbolic representation of CBOR data.
The CBOR type is the central type in the dCBOR library, representing any CBOR data item using
a reference-counted wrapper around a CBORCase enum. This design allows efficient sharing
of CBOR data structures in memory without excessive copying.
§Features
- Deterministic encoding: Guarantees that semantically equivalent data structures will always be encoded to identical byte sequences
- Reference counting: Enables efficient sharing of CBOR structures
- Type safety: Uses Rust’s type system to safely handle different CBOR data types
- Conversion traits: Implements Rust’s standard conversion traits for ergonomic use
§Thread Safety
With the multithreaded feature enabled, CBOR uses Arc for reference counting, making
it thread-safe. Without this feature, it uses Rc, which is more efficient but not thread-safe.
§Example
use dcbor::prelude::*;
// 1. Create and round-trip a homogeneous array
let array = CBOR::from(vec![1, 2, 3]);
// Encode to bytes
let encoded = array.to_cbor_data();
assert_eq!(hex::encode(&encoded), "83010203");
// Decode from bytes
let decoded = CBOR::try_from_data(&encoded).unwrap();
assert_eq!(decoded, array);
// 2. Create and round-trip a heterogeneous array
let mixed_array: Vec<CBOR> = vec![
1.into(),
"Hello".into(),
vec![1, 2, 3].into(),
];
let mixed = CBOR::from(mixed_array);
// Encode the heterogeneous array to bytes
let mixed_encoded = mixed.to_cbor_data();
assert_eq!(hex::encode(&mixed_encoded), "83016548656c6c6f83010203");
// Decode from bytes
let mixed_decoded = CBOR::try_from_data(&mixed_encoded).unwrap();
assert_eq!(mixed_decoded, mixed);
// Use diagnostic_flat() for a compact single-line representation
assert_eq!(mixed_decoded.diagnostic_flat(), r#"[1, "Hello", [1, 2, 3]]"#);Implementations§
Source§impl CBOR
Methods for decoding CBOR from binary representation and encoding to binary.
impl CBOR
Methods for decoding CBOR from binary representation and encoding to binary.
Sourcepub fn try_from_data(data: impl AsRef<[u8]>) -> Result<CBOR>
pub fn try_from_data(data: impl AsRef<[u8]>) -> Result<CBOR>
Decodes binary data into CBOR symbolic representation.
This method parses the provided binary data according to the CBOR and dCBOR specifications, validating that it follows all deterministic encoding rules.
§Arguments
data- The binary data to decode, which can be any type that can be referenced as a byte slice (e.g.,Vec<u8>,&[u8], etc.)
§Returns
Ok(CBOR)- A CBOR value if decoding was successfulErr- If the data is not valid CBOR or violates dCBOR encoding rules
§Examples
use dcbor::prelude::*;
// Decode a CBOR array [1, 2, 3]
let data = hex_literal::hex!("83010203");
let cbor = CBOR::try_from_data(&data).unwrap();
// Get the array contents
let array: Vec<u64> = cbor.try_into().unwrap();
assert_eq!(array, vec![1, 2, 3]);§Errors
This method will return an error if:
- The data is not valid CBOR
- The data violates dCBOR encoding rules (e.g., non-canonical integer encoding)
- The data has content after the end of the CBOR item
Sourcepub fn try_from_hex(hex: &str) -> Result<CBOR>
pub fn try_from_hex(hex: &str) -> Result<CBOR>
Decodes a hexadecimal string into CBOR symbolic representation.
This is a convenience method that converts a hexadecimal string to binary data
and then calls try_from_data.
§Arguments
hex- A string containing hexadecimal characters (no spaces or other characters)
§Returns
Ok(CBOR)- A CBOR value if decoding was successfulErr- If the hex string is invalid or the resulting data is not valid dCBOR
§Examples
use dcbor::prelude::*;
// Decode a CBOR array [1, 2, 3] from hex
let cbor = CBOR::try_from_hex("83010203").unwrap();
assert_eq!(cbor.diagnostic(), "[1, 2, 3]");§Panics
This method will panic if the hex string is not well-formed hexadecimal (contains non-hex characters or an odd number of digits).
Sourcepub fn to_cbor_data(&self) -> Vec<u8> ⓘ
pub fn to_cbor_data(&self) -> Vec<u8> ⓘ
Encodes this CBOR value to binary data following dCBOR encoding rules.
This method converts the CBOR value to a byte vector according to the dCBOR specification, ensuring deterministic encoding.
§Returns
A Vec<u8> containing the encoded CBOR data.
§Examples
use dcbor::prelude::*;
// Create a CBOR map
let mut map = Map::new();
map.insert(CBOR::from("key"), CBOR::from(123));
let cbor = CBOR::from(map);
// Encode to binary
let encoded = cbor.to_cbor_data();
assert_eq!(hex::encode(&encoded), "a1636b6579187b");
// Round-trip through encoding and decoding
let decoded = CBOR::try_from_data(&encoded).unwrap();
assert_eq!(decoded, cbor);Source§impl CBOR
Factory methods for creating CBOR values.
impl CBOR
Factory methods for creating CBOR values.
Sourcepub fn to_byte_string(data: impl AsRef<[u8]>) -> CBOR
pub fn to_byte_string(data: impl AsRef<[u8]>) -> CBOR
Creates a new CBOR value representing a byte string.
This method creates a CBOR byte string (major type 2) from any type that can be referenced as a byte slice.
§Arguments
data- The bytes to include in the byte string, which can be any type that can be referenced as a byte slice (e.g.,Vec<u8>,&[u8], etc.)
§Returns
A new CBOR value representing the byte string.
§Examples
use dcbor::prelude::*;
// Create a CBOR byte string from a byte slice
let bytes = vec![0x01, 0x02, 0x03];
let cbor = CBOR::to_byte_string(&bytes);
// Encode to CBOR binary
let encoded = cbor.to_cbor_data();
assert_eq!(hex::encode(&encoded), "43010203");
// Convert back to bytes
let recovered: Vec<u8> = cbor.try_into().unwrap();
assert_eq!(recovered, vec![0x01, 0x02, 0x03]);Sourcepub fn to_byte_string_from_hex(hex: impl AsRef<str>) -> CBOR
pub fn to_byte_string_from_hex(hex: impl AsRef<str>) -> CBOR
Creates a new CBOR value representing a byte string from a hexadecimal string.
This is a convenience method that converts a hexadecimal string to a byte array and then creates a CBOR byte string value.
§Arguments
hex- A string containing hexadecimal characters (no spaces or other characters)
§Returns
A new CBOR value representing the byte string.
§Examples
use dcbor::prelude::*;
// Create a CBOR byte string from a hex string
let cbor = CBOR::to_byte_string_from_hex("010203");
// Get the diagnostic representation
assert_eq!(cbor.diagnostic(), "h'010203'");§Panics
This method will panic if the hex string is not well-formed hexadecimal (contains non-hex characters or an odd number of digits).
Sourcepub fn to_tagged_value(tag: impl Into<Tag>, item: impl Into<CBOR>) -> CBOR
pub fn to_tagged_value(tag: impl Into<Tag>, item: impl Into<CBOR>) -> CBOR
Creates a new CBOR value representing a tagged value.
This method creates a CBOR tagged value (major type 6) by applying a tag to another CBOR value. Tags provide semantic information about how the tagged data should be interpreted.
§Arguments
tag- The tag to apply, which can be any type that can be converted to aTagitem- The CBOR value to tag, which can be any type that can be converted toCBOR
§Returns
A new CBOR value representing the tagged value.
§Examples
use dcbor::prelude::*;
// Create a CBOR value with tag 42 applied to the string "hello"
let tagged = CBOR::to_tagged_value(42, "hello");
// Get the diagnostic representation
assert_eq!(tagged.diagnostic(), "42(\"hello\")");
// Extract the tag and the tagged value
let (tag, value) = tagged.try_into_tagged_value().unwrap();
assert_eq!(tag.value(), 42);
let s: String = value.try_into().unwrap();
assert_eq!(s, "hello");Source§impl CBOR
impl CBOR
Sourcepub fn try_into_byte_string(self) -> Result<Vec<u8>>
pub fn try_into_byte_string(self) -> Result<Vec<u8>>
Extract the CBOR value as a byte string.
Returns Ok if the value is a byte string, Err otherwise.
pub fn into_byte_string(self) -> Option<Vec<u8>>
Sourcepub fn try_into_text(self) -> Result<String>
pub fn try_into_text(self) -> Result<String>
Extract the CBOR value as a text string.
Returns Ok if the value is a text string, Err otherwise.
Sourcepub fn try_into_array(self) -> Result<Vec<CBOR>>
pub fn try_into_array(self) -> Result<Vec<CBOR>>
Extract the CBOR value as an array.
Returns Ok if the value is an array, Err otherwise.
Sourcepub fn try_into_map(self) -> Result<Map>
pub fn try_into_map(self) -> Result<Map>
Extract the CBOR value as a map.
Returns Ok if the value is a map, Err otherwise.
Sourcepub fn try_into_tagged_value(self) -> Result<(Tag, CBOR)>
pub fn try_into_tagged_value(self) -> Result<(Tag, CBOR)>
Extract the CBOR value as a tagged value.
Returns Ok if the value is a tagged value, Err otherwise.
Sourcepub fn try_into_expected_tagged_value(
self,
expected_tag: impl Into<Tag>,
) -> Result<CBOR>
pub fn try_into_expected_tagged_value( self, expected_tag: impl Into<Tag>, ) -> Result<CBOR>
Extract the CBOR value as an expected tagged value.
Returns Ok if the value is a tagged value with the expected tag, Err
otherwise.
Sourcepub fn try_into_simple_value(self) -> Result<Simple>
pub fn try_into_simple_value(self) -> Result<Simple>
Extract the CBOR value as a simple value.
Returns Ok if the value is a simple value, Err otherwise.
Source§impl CBOR
Affordances for viewing CBOR in diagnostic notation.
impl CBOR
Affordances for viewing CBOR in diagnostic notation.
Sourcepub fn diagnostic_opt(
&self,
annotate: bool,
summarize: bool,
flat: bool,
tags: Option<&dyn TagsStoreTrait>,
) -> String
pub fn diagnostic_opt( &self, annotate: bool, summarize: bool, flat: bool, tags: Option<&dyn TagsStoreTrait>, ) -> String
Returns a representation of this CBOR in diagnostic notation.
Optionally annotates the output, e.g. formatting dates and adding names of known tags.
Sourcepub fn diagnostic(&self) -> String
pub fn diagnostic(&self) -> String
Returns a representation of this CBOR in diagnostic notation.
Sourcepub fn diagnostic_annotated(&self) -> String
pub fn diagnostic_annotated(&self) -> String
Returns a representation of this CBOR in diagnostic notation, with annotations.
pub fn diagnostic_flat(&self) -> String
pub fn summary(&self) -> String
pub fn summary_opt(&self, tags: &dyn TagsStoreTrait) -> String
Source§impl CBOR
Affordances for viewing the encoded binary representation of CBOR as hexadecimal.
impl CBOR
Affordances for viewing the encoded binary representation of CBOR as hexadecimal.
Sourcepub fn hex_opt(
&self,
annotate: bool,
tags: Option<&dyn TagsStoreTrait>,
) -> String
pub fn hex_opt( &self, annotate: bool, tags: Option<&dyn TagsStoreTrait>, ) -> String
Returns the encoded hexadecimal representation of this CBOR.
Optionally annotates the output, e.g. breaking the output up into semantically meaningful lines, formatting dates, and adding names of known tags.
Sourcepub fn hex_annotated(&self) -> String
pub fn hex_annotated(&self) -> String
Returns the encoded hexadecimal representation of this CBOR, with annotations.
Trait Implementations§
Source§impl From<&str> for CBOR
§Text Strings in dCBOR
dCBOR encodes text strings according to strict deterministic rules:
impl From<&str> for CBOR
§Text Strings in dCBOR
dCBOR encodes text strings according to strict deterministic rules:
- All strings must be in Unicode Normalization Form C (NFC)
- This ensures that semantically equivalent strings (like composed vs decomposed characters) are always encoded identically
dCBOR provides conversions for both String and &str types through the
Into<CBOR> trait, making it easy to create CBOR values from Rust strings.
§Examples
use dcbor::prelude::*;
// Create CBOR from string literals
let cbor_str: CBOR = "Hello, world!".into();
// Create CBOR from owned String
let string = String::from("Hello, dCBOR!");
let cbor_string: CBOR = string.into();
// Use in collections
let mut map = Map::new();
map.insert("key", "value");
map.insert("array", [1, 2, 3]);
// Convert back to String
let value: String = cbor_str.try_into().unwrap();
assert_eq!(value, "Hello, world!");§Unicode Normalization
dCBOR automatically ensures strings are in NFC form, which guarantees consistent encoding across platforms. This is important for applications that rely on deterministic encoding for hashing or signing operations.
For example, characters like “é” can be represented as either a single code point (U+00E9, NFC) or as “e” followed by the combining acute accent (U+0065 U+0301, NFD). dCBOR ensures these are always encoded consistently in NFC form.
Source§impl From<ByteString> for CBOR
Converts a ByteString into a CBOR byte string value.
impl From<ByteString> for CBOR
Converts a ByteString into a CBOR byte string value.
This conversion creates a CBOR item of major type 2 (byte string) containing the byte string’s data.
§Examples
use dcbor::prelude::*;
let bytes = ByteString::new([1, 2, 3, 4]);
let cbor = CBOR::from(bytes);
// The result is a CBOR byte string
assert_eq!(cbor.diagnostic(), "h'01020304'");
// The encoding follows dCBOR rules
assert_eq!(cbor.to_cbor_data(), vec![0x44, 0x01, 0x02, 0x03, 0x04]);
// 0x44: byte string (major type 2) of length 4Source§fn from(value: ByteString) -> Self
fn from(value: ByteString) -> Self
Source§impl From<Simple> for CBOR
Converts a Simple value into a CBOR representation.
impl From<Simple> for CBOR
Converts a Simple value into a CBOR representation.
This conversion allows Simple values to be seamlessly used where CBOR values
are expected, creating a CBOR value of type CBORCase::Simple that wraps the
simple value.
§Note
This conversion is primarily used internally. Users should generally prefer
converting from Rust’s native types (bool, f64) directly to CBOR instead of
using the Simple type.
Source§impl<T> From<Vec<T>> for CBOR
§Array Support in dCBOR
dCBOR provides convenient conversions to and from CBOR arrays through implementation of the
From<T> and TryFrom<CBOR> traits for various collection types. This enables idiomatic
conversions using Rust’s .into() method.
impl<T> From<Vec<T>> for CBOR
§Array Support in dCBOR
dCBOR provides convenient conversions to and from CBOR arrays through implementation of the
From<T> and TryFrom<CBOR> traits for various collection types. This enables idiomatic
conversions using Rust’s .into() method.
Supported collection types:
- Rust arrays (
[T; N]) - Vectors (
Vec<T>) - VecDeque (
VecDeque<T>) - HashSet (
HashSet<T>)
For all of these, the elements must be convertible to CBOR via the Into<CBOR> trait.
§Examples
use dcbor::prelude::*;
// Create CBOR from Rust array (fixed size)
let array_cbor: CBOR = [1, 2, 3].into();
// Create CBOR from Vec
let vec = vec![1, 2, 3];
let vec_cbor: CBOR = vec.into();
// Mixed types in Vec
let mixed_vec: Vec<CBOR> = vec![
1.into(), // Integer
"hello".into(), // String
[1, 2, 3].into(), // Nested array
true.into() // Boolean
];
let mixed_cbor: CBOR = mixed_vec.into();
// Convert back to Vec
let numbers: Vec<i32> = array_cbor.try_into().unwrap();
assert_eq!(numbers, vec![1, 2, 3]);Source§impl From<bool> for CBOR
§Boolean Values in dCBOR
dCBOR supports boolean values through the major type 7 (simple values),
where false is encoded as 0xf4 and true as 0xf5.
impl From<bool> for CBOR
§Boolean Values in dCBOR
dCBOR supports boolean values through the major type 7 (simple values),
where false is encoded as 0xf4 and true as 0xf5.
Per the dCBOR specification, only a limited set of simple values are valid:
- Boolean values (
true,false) null- Floating point values
§Examples
use dcbor::prelude::*;
// Create CBOR from boolean values using `into()`
let cbor_true: CBOR = true.into();
let cbor_false: CBOR = false.into();
// Use in collections
let array: Vec<CBOR> = vec![true.into(), false.into(), 42.into()];
let cbor_array: CBOR = array.into();
// Maps can use boolean keys
let mut map = Map::new();
map.insert(true, "this is true");
map.insert(false, "this is false");
// Convert back to boolean
let value: bool = cbor_true.try_into().unwrap();
assert_eq!(value, true);Source§impl TryFrom<CBOR> for ByteString
Attempts to convert a CBOR value into a ByteString.
impl TryFrom<CBOR> for ByteString
Attempts to convert a CBOR value into a ByteString.
This conversion succeeds if the CBOR value is a byte string (major type 2),
otherwise it returns a WrongType error.
§Examples
use dcbor::prelude::*;
// Converting from a CBOR byte string works
let cbor = CBOR::to_byte_string([1, 2, 3, 4]);
let bytes: ByteString = cbor.try_into().unwrap();
assert_eq!(bytes.data(), &[1, 2, 3, 4]);
// Converting from a different CBOR type fails
let cbor = CBOR::from(42);
let result: dcbor::Result<ByteString> = cbor.try_into();
assert!(result.is_err());Source§impl TryFrom<CBOR> for Simple
Attempts to convert a CBOR value to a Simple value.
impl TryFrom<CBOR> for Simple
Attempts to convert a CBOR value to a Simple value.
If the CBOR value is a CBORCase::Simple, this conversion will succeed.
For any other CBOR type, it will return a WrongType error.
§Note
This conversion is primarily used internally. Users should generally prefer
converting CBOR values to Rust’s native types (bool, f64, etc.) instead of
to the Simple type.