Type 5 – Maps

CBOR maps are the plain old associate hash maps known from JSON and many other formats and languages, with one exception: any CBOR data item can be a key, not just strings. This is somewhat unusual and you, as an application developer, should keep that in mind.

Maps can be either definite or indefinite, in much the same way as Type 4 – Arrays.

Corresponding cbor_type

CBOR_TYPE_MAP

Number of allocations (definite)

Two plus any manipulations with the data

Number of allocations (indefinite)

Two plus logarithmically many reallocations relative to additions

Storage requirements (definite)

sizeof(cbor_pair) * size + sizeof(cbor_item_t)

Storage requirements (indefinite)

<= sizeof(cbor_item_t) + sizeof(cbor_pair) * size * BUFFER_GROWTH

Streaming maps

Please refer to Streaming & indefinite items.

Getting metadata

size_t cbor_map_size(const cbor_item_t *item)

Get the number of pairs.

Return

The number of pairs

Parameters
  • item[borrow]: A map

size_t cbor_map_allocated(const cbor_item_t *item)

Get the size of the allocated storage.

Return

Allocated storage size (as the number of cbor_pair items)

Parameters
  • item[borrow]: A map

bool cbor_map_is_definite(const cbor_item_t *item)

Is this map definite?

Return

Is this map definite?

Parameters
  • item[borrow]: A map

bool cbor_map_is_indefinite(const cbor_item_t *item)

Is this map indefinite?

Return

Is this map indefinite?

Parameters
  • item[borrow]: A map

Reading data

struct cbor_pair *cbor_map_handle(const cbor_item_t *item)

Get the pairs storage.

Return

Array of cbor_map_size pairs. Manipulation is possible as long as references remain valid.

Parameters
  • item[borrow]: A map

Creating new items

cbor_item_t *cbor_new_definite_map(size_t size)

Create a new definite map.

Return

new definite map. NULL on malloc failure.

Parameters
  • size: The number of slots to preallocate

cbor_item_t *cbor_new_indefinite_map()

Create a new indefinite map.

Return

new definite map. NULL on malloc failure.

Parameters
  • size: The number of slots to preallocate

Modifying items

bool cbor_map_add(cbor_item_t *item, struct cbor_pair pair)

Add a pair to the map.

For definite maps, items can only be added to the preallocated space. For indefinite maps, the storage will be expanded as needed

Return

true on success, false if either reallocation failed or the preallcoated storage is full

Parameters
  • item[borrow]: A map

  • pair[incref]: The key-value pair to add (incref is member-wise)