Map

Struct Map 

Source
pub struct Map(/* private fields */);
Expand description

§Map Support in dCBOR

A deterministic CBOR map implementation that ensures maps with the same content always produce identical binary encodings, regardless of insertion order.

§Deterministic Map Representation

The Map type follows strict deterministic encoding rules as specified by dCBOR:

  • Map keys are always sorted in lexicographic order of their encoded CBOR bytes
  • Duplicate keys are not allowed (enforced by the implementation)
  • Keys and values can be any type that implements Into<CBOR>
  • Numeric reduction is applied (e.g., 3.0 is stored as integer 3)

This deterministic encoding ensures that equivalent maps always produce identical byte representations, which is crucial for applications that rely on consistent hashing, digital signatures, or other cryptographic operations.

§Features

The Map type provides:

  • Built-in conversions from standard Rust collections like HashMap and BTreeMap
  • Type-safe conversions when extracting values with get<K, V>() and extract<K, V>()
  • Automatic deterministic ordering of keys
  • Prevention of duplicate keys
  • Support for heterogeneous key and value types

§Examples

§Creating and using maps

use std::collections::HashMap;

use dcbor::prelude::*;

// Create a new Map directly
let mut map = Map::new();
map.insert(1, "one"); // Integer key
map.insert("two", 2); // String key
map.insert([1, 2, 3], "array key"); // Array key
map.insert(3.0, "numeric reduction"); // Float key (stored as integer 3)

// Check the map size
assert_eq!(map.len(), 4);

// Create a CBOR value from the map
let cbor_map: CBOR = map.into();

// Round-trip through binary encoding
let encoded = cbor_map.to_cbor_data();
let decoded = CBOR::try_from_data(&encoded).unwrap();

// View the diagnostic representation
assert!(decoded.diagnostic_flat().contains(r#""two": 2"#));

§Converting from standard Rust collections

use std::collections::{BTreeMap, HashMap};

use dcbor::prelude::*;

// Convert HashMap to CBOR Map
let mut hash_map = HashMap::new();
hash_map.insert("a", 1);
hash_map.insert("b", 2);
let cbor_from_hashmap: CBOR = hash_map.into();

// Convert BTreeMap to CBOR Map
let mut btree_map = BTreeMap::new();
btree_map.insert("x", "value1");
btree_map.insert("y", "value2");
let cbor_from_btree: CBOR = btree_map.into();

§Type-safe extraction of values

use dcbor::prelude::*;

// Create a map with various types
let mut typed_map = Map::new();
typed_map.insert("number", 42);
typed_map.insert("text", "hello");
typed_map.insert("array", vec![1, 2, 3]);

// Type-safe extraction
let number: i32 = typed_map.extract("number").unwrap();
let text: String = typed_map.extract("text").unwrap();
let array: Vec<i32> = typed_map.extract("array").unwrap();

assert_eq!(number, 42);
assert_eq!(text, "hello");
assert_eq!(array, vec![1, 2, 3]);

// Using get() for optional extraction
let present: Option<i32> = typed_map.get("number");
let absent: Option<i32> = typed_map.get("missing");

assert_eq!(present, Some(42));
assert_eq!(absent, None);

§Implementation Details

The Map implementation:

  • Uses a BTreeMap internally to maintain the sorted order of keys
  • Encodes keys with their CBOR representation for lexicographic sorting
  • Applies all dCBOR deterministic encoding rules automatically

Implementations§

Source§

impl Map

Source

pub fn new() -> Map

Makes a new, empty CBOR Map.

Source

pub fn len(&self) -> usize

Returns the number of entries in the map.

Source

pub fn is_empty(&self) -> bool

Checks if the map is empty.

Source

pub fn iter(&self) -> MapIter<'_>

Gets an iterator over the entries of the CBOR map, sorted by key.

Key sorting order is lexicographic by the key’s binary-encoded CBOR.

Source

pub fn insert(&mut self, key: impl Into<CBOR>, value: impl Into<CBOR>)

Inserts a key-value pair into the map.

Source

pub fn get<K, V>(&self, key: K) -> Option<V>
where K: Into<CBOR>, V: TryFrom<CBOR>,

Get a value from the map, given a key.

Returns Some if the key is present in the map, None otherwise.

Source

pub fn contains_key<K>(&self, key: K) -> bool
where K: Into<CBOR>,

Tests if the map contains a key.

Source

pub fn extract<K, V>(&self, key: K) -> Result<V, Error>
where K: Into<CBOR>, V: TryFrom<CBOR>,

Get a value from the map, given a key.

Returns Ok if the key is present in the map, Err otherwise.

Source§

impl Map

Source

pub fn cbor_data(&self) -> Vec<u8>

Trait Implementations§

Source§

impl Clone for Map

Source§

fn clone(&self) -> Map

Returns a duplicate of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Map

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for Map

Source§

fn default() -> Map

Returns the “default value” for a type. Read more
Source§

impl EnvelopeEncodable for Map

Source§

fn into_envelope(self) -> Envelope

Converts this value into a Gordian Envelope. Read more
Source§

fn to_envelope(&self) -> Envelope
where Self: Clone,

Converts a reference to this value into a Gordian Envelope. Read more
Source§

impl From<&Map> for CBOR

Source§

fn from(value: &Map) -> CBOR

Converts to this type from the input type.
Source§

impl From<Map> for CBOR

Source§

fn from(value: Map) -> CBOR

Converts to this type from the input type.
Source§

impl<T, K, V> From<T> for Map
where T: IntoIterator<Item = (K, V)>, K: Into<CBOR>, V: Into<CBOR>,

Convert a container to a CBOR Map where the container’s items are pairs of CBOREncodable values.

Source§

fn from(container: T) -> Map

Converts to this type from the input type.
Source§

impl Hash for Map

Source§

fn hash<H>(&self, state: &mut H)
where H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Map

Source§

fn eq(&self, other: &Map) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl TryFrom<Map> for Assertion

Attempts to convert a CBOR map to an assertion.

The map must have exactly one entry, where the key represents the predicate and the value represents the object. This is used in the deserialization process.

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from(map: Map) -> Result<Self>

Performs the conversion.
Source§

impl Eq for Map

Auto Trait Implementations§

§

impl Freeze for Map

§

impl RefUnwindSafe for Map

§

impl Send for Map

§

impl Sync for Map

§

impl Unpin for Map

§

impl UnwindSafe for Map

Blanket Implementations§

§

impl<T> Any for T
where T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for T
where T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for T
where T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CBOREncodable for T
where T: Into<CBOR> + Clone,

Source§

fn to_cbor(&self) -> CBOR

Converts this value to a CBOR object. Read more
Source§

fn to_cbor_data(&self) -> Vec<u8>

Converts this value directly to binary CBOR data. Read more
§

impl<T> CloneToUninit for T
where T: Clone,

§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T, U> Into<U> for T
where U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V