Dictionary
Dictionary data type for Arduino / ESP8266 / ESP32
A small key-value store for microcontrollers. Keys are short strings; values are
text, integers, floats, booleans or null. Pairs keep their insertion order, lookups
use a hash index, and every pair is a single heap allocation. Built for holding
configuration loaded from JSON on ESP8266 and ESP32, but architecture-independent.
Table of Contents
What is new in 4.0
- One structure, one allocation per pair. An insertion-ordered array of entries,
each holding its type, lengths, key and value in one block, plus an optional hash
index for large dictionaries. The binary tree and the second index array are gone.
- Order survives removal.
remove() keeps the order of the remaining pairs and
never allocates.
- Typed values.
set() stores text, integers, floats, booleans and null;
getInt(), getFloat(), getBool(), getString() read them back, converting
when needed. json() writes numbers and booleans unquoted.
- One built-in compressor for values, used only when it makes a value smaller.
SHOCO and SMAZ were removed.
- Rewritten JSON loader: empty values, standard escapes (including
\uXXXX),
a length cap on every token, clear error codes, nested structures rejected.
- Less memory: on the benchmark data a 4.0 dictionary without compression is about
as small as a 3.6 dictionary with compression, and one with compression is about 37%
smaller than 3.6 without (see Benchmarks).
reserve(), json(Print&), zero-copy peek() and keyAt(), const read methods,
move semantics.
Migrating from 3.x
Existing sketches keep compiling. The 3.x calls are kept as wrappers with their 3.x
behavior (values stored as text) and produce a compile-time deprecation warning:
| 3.x call |
4.0 replacement |
d.insert(key, value), d(key, value) |
d.set(key, value) |
d.search(key) |
d.getString(key) (or d[key], still supported) |
d(key) (exists?) |
d.has(key) |
d(i) (i-th key) |
d.key(i) or d.keyAt(i) |
d[i] (i-th value) |
d.value(i) |
Define _DICT_NO_DEPRECATION_WARNINGS to silence the warnings.
Behavior that changed:
- Positions no longer shuffle after
remove(); the remaining pairs keep their order.
d == other compares types as well as values: the text "80" is not equal to the number 80.
Two dictionaries that differ only in keys with empty values are no longer reported equal.
size() reports the heap bytes of the new layout; jsize() is exact (json().length() + 1).
jload() accepts empty values, decodes standard escapes, keeps spaces inside unquoted values
(is ok stays is ok), rejects nested objects and arrays, and returns the real error code.
- Copy construction (
Dictionary b(a), passing by value) does not compile (since 3.6.1).
Use assignment or merge(); moving works.
- The constructor is
explicit.
- These build flags are ignored with a
#warning: _DICT_CRC, _DICT_PACK_STRUCTURES.
_DICT_COMPRESS_SHOCO and _DICT_COMPRESS_SMAZ now enable the built-in compressor (_DICT_COMPRESS).
BufferStream (ReadBufferStream, WriteBufferStream) and the _LIBDEBUG_ print helpers were removed.
- Keys given with
F() are not supported; use String(F("key")). Values with F() are.
Requirements
- An Arduino-compatible toolchain (Arduino IDE or PlatformIO) with C++11.
- Primarily targeted at ESP8266 and ESP32, but
architectures=* / platforms=*.
AVR boards build too, but hold only a handful of pairs in 2 KB of RAM.
Installation
Arduino IDE / Library Manager: open Tools -> Manage Libraries..., search for
Dictionary by Anatoli Arkhipenko, and click Install.
PlatformIO: add it to platformio.ini:
lib_deps =
arkhipenko/Dictionary
Manual: download this repository as a ZIP and use Sketch -> Include Library -> Add .ZIP Library....
Quick start
#include <Dictionary.h>
Dictionary d;
void setup() {
Serial.begin(115200);
d.set("ssid", "my_wifi");
d.set("port", 80);
d.set("debug", true);
Serial.println(d["ssid"]); // my_wifi
Serial.println(d.getInt("port", 8080)); // 80
Serial.println(d.getInt("retries", 3)); // 3 (missing: default)
Serial.println(d.json()); // {"ssid":"my_wifi","port":80,"debug":true}
d.jload("{\"url\": \"http://ota.home.lan\", \"timeout\": 30}");
Serial.println(d.getInt("timeout")); // 30 (stored as text "30", converted on read)
if (d.has("ssid")) d.remove("ssid");
}
void loop() {}
API reference
key is a const char* or a String. Methods that change the dictionary return an
int8_t result code: 0 (DICTIONARY_OK) or a negative error code,
so if (d.set(...)) tests for failure.
Writing
| Call |
Description |
d.set(key, value) |
Insert or replace. value: const char*, String, F("..."), bool, any integer type, float, double. A replaced pair keeps its position. |
d.setNull(key) |
Store a null value. d.set(key, (const char*)NULL) does the same. |
d.remove(key) |
Remove a pair. A missing key is not an error. Never allocates. |
d.destroy() |
Remove everything and free all memory. The object stays usable. |
d.reserve(n) |
Pre-allocate room (array and index) for n pairs, e.g. before a large jload(). |
d.merge(other) |
Copy every pair of other into d; shared keys take other's value. Stops at the first error. |
d = other |
Replace d with a copy of other (errors are not reported; use destroy() + merge() for that). |
Dictionary b(std::move(a)), b = std::move(a) |
Move: b takes over; a is left empty and usable. |
d.jload(json [, n]) |
Load pairs from a const char*, String or Stream (at most n when n > 0). See JSON. |
Reading
A missing key, or a value that cannot be converted, returns def.
| Call |
Returns |
Description |
d.count() |
size_t |
Number of pairs. |
d.has(key) |
bool |
Whether key exists. |
d.type(key) |
DictType |
DICT_STR, DICT_INT, DICT_FLOAT, DICT_BOOL, DICT_NULL (DICT_INT64, DICT_DOUBLE with wide numbers), or DICT_NONE when missing. |
d.getInt(key, def = 0) |
int32_t |
See conversion. |
d.getFloat(key, def = 0) |
float |
|
d.getBool(key, def = false) |
bool |
|
d.getInt64(key, def), d.getDouble(key, def) |
|
With _DICT_WIDE_NUMBERS. |
d.getString(key, def = "") / d[key] |
String |
Any value as text. |
d.getString(key, buf, size) |
size_t |
Any value as text into your buffer, no heap. Returns the full length (like snprintf), so a result >= size means it was cut. |
d.peek(key) |
const char* |
Pointer to a plain text value inside the dictionary, no copy; NULL for other types and compressed values. Valid until the next change to d. |
Positional access (insertion order)
| Call |
Returns |
Description |
d.keyAt(i) |
const char* |
i-th key, no copy; NULL when i >= count(). Valid until the next change. |
d.typeAt(i) |
DictType |
DICT_NONE when out of range. |
d.key(i) / d.value(i) |
String |
i-th key / value as text; empty when out of range. |
Delete everything one by one with while (d.count()) d.remove(d.keyAt(0)); - or just call destroy().
JSON and sizes
| Call |
Returns |
Description |
d.json() |
String |
JSON object of all pairs in insertion order. |
d.json(out) |
size_t |
Write the JSON to any Print (Serial, a File, ...) without building a String. |
d.jsize() |
size_t |
json().length() + 1 (exact). |
d.esize() |
size_t |
Sum of key length + 1 + value text length + 1 (e.g. to size an EEPROM area). |
d.size() |
size_t |
Heap bytes requested by the dictionary (entries, array, index), excluding allocator overhead. |
d == other, d != other |
bool |
Same pairs with the same types and values (order ignored). |
Typed values and conversion
set() stores what it is given:
- text as text;
double as float unless _DICT_WIDE_NUMBERS is defined;
- integers as
int32_t (int64_t with _DICT_WIDE_NUMBERS); an integer outside that range
is stored as decimal text, so it is never altered;
bool and null take no space beyond the key.
Getters convert on read by default:
| Stored |
getInt |
getFloat |
getBool |
getString |
| text |
the whole text parsed as a decimal integer |
the whole text parsed as a number |
true/false (any case), 1/0 |
as stored |
| int |
value |
value |
value != 0 |
decimal |
| float |
value if integral and in range, else def |
value |
def |
up to _DICT_FLOAT_DECIMALS decimals, trailing zeros trimmed |
| bool |
1 / 0 |
1 / 0 |
value |
true / false |
| null |
def |
def |
def |
null |
With _DICT_STRICT_GET there is no conversion: getInt accepts only integers, getFloat
only numbers, getBool only booleans; anything else returns def. getString always works.
JSON
Output. json() writes a flat object in insertion order. Text is quoted and escaped
(", \, and control characters as \n, \t, \r, \b, \f, \u00XX); numbers,
booleans and null are written unquoted. A float that is nan or inf is written as null.
Input. jload() reads a lenient, flat JSON-like format:
- Braces are optional. Pairs are separated by
,, a newline or }. A trailing comma is fine.
- Keys and values may be quoted (
"...", with standard escapes including \uXXXX, written as UTF-8)
or bare. A bare token runs to the next separator; spaces inside it are kept, spaces around it
are trimmed. A bare value may contain : (URLs work unquoted).
# outside quotes starts a comment that runs to the end of the line.
- Nested objects and arrays are rejected with
DICTIONARY_FMT.
- Values are stored as given, as text, so
json() of loaded data looks like the input
(and like 3.x). With _DICT_TYPED_JSON, bare numbers, true/false and null are stored typed.
Quoted values are always text.
- A later duplicate key replaces the earlier value.
- Not atomic: pairs loaded before an error stay in the dictionary.
- A
Stream is read until read()