Skip to main content

Table store

Availability: Linux and embedded runtimes

A table is a named collection of values of one type. Each entry has a key, chosen by the caller or generated by the runtime.

When to use

Use a table for a named collection whose entries need keys, a count, or reading in key order.

Operations

  • Declare a typed table, fixed at compile time, and which scope it belongs to.
  • Insert a value under a key of your own, or let the runtime generate one.
  • Read a value, remove one, or count the entries.
  • Read the entries or the keys in either direction, with a callback, as an iterator, or all at once.

Example

use myrmic_sdk::db::table::Table;
use myrmic_sdk::Metadata;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct Device {
label: myrmic_sdk::String,
}

const DEVICES: Table<Device> = Table::new("devices");

#[myrmic_sdk::cmd]
fn register(_md: Metadata) -> myrmic_sdk::Result {
let device = Device { label: "sensor 01".into() };

// Choosing the key is what makes the entry addressable later.
DEVICES.insert_with("sensor-01", &device)?;

// Letting the runtime choose one does not say what it chose.
DEVICES.insert(&device)?;

// An absent entry reads as nothing rather than as an error.
if let Some(saved) = DEVICES.get("sensor-01")? {
let _ = saved.label;
}

// A callback, in key order. A value that cannot be decoded is skipped
// silently, while a failed read stops the traversal.
DEVICES.for_each(|device| {
let _ = device;
})?;

// An iterator instead, in reverse key order. It lazy loads one entry per
// step, and each failure reaches the caller.
for entry in DEVICES.iter_rev() {
let (_key, _device) = entry?;
}

// Nothing is lazy loaded here: the whole table is held in memory at once.
let _all = DEVICES.list()?;
let _by_key = DEVICES.to_map()?;

// The keys alone, lazy loaded, without reading any value.
for key in DEVICES.keys() {
let _key = key?;
}

// Or all the keys at once.
let _ids = DEVICES.ids()?;

let _total = DEVICES.count()?;

Ok(())
}

Behavior

Normal

A table fixes the value's type, its name, and its scope.

Entries are ordered by their encoded key, never by a field inside the value, and can be read in either direction.

Errors

Encoding, decoding, storage access, and traversal can all fail.

Limits

Each value is read through a fixed buffer of 4 KiB, so anything larger cannot be read back. Inserting has no such limit.

Reading a table costs one call to the runtime per entry, whichever form is used.

Letting the runtime generate a key does not tell the caller what it generated, so choose the key whenever the entry has to be reached again.

API documentation

See the API documentation for myrmic_sdk::db::table, which covers every table operation and its iterators.

Cookie Policy