API Reference: Persistence Module
Source of truth:
include/persistence/StoreTypes.hinclude/persistence/KeyValueStore.hinclude/persistence/SlotStore.hinclude/persistence/RecordCodec.hinclude/persistence/PersistenceService.hinclude/persistence/MemoryStores.hinclude/drivers/esp32/Esp32NvsStore.hinclude/drivers/esp32/SdConfig.hinclude/drivers/esp32/SdStore.hinclude/drivers/native/HostFileStore.h
Overview
The persistence module keeps small game data between runs: settings, scores, unlocks and small save records. It is compiled only when PIXELROOT32_ENABLE_PERSISTENCE=1 (default 0) and lives in pixelroot32::persistence, adapters included.
The public surface has four parts:
- Two storage models:
IKeyValueStore(named integers and blobs) andISlotStore(numbered records). - Adapters, one per medium: NVS and a FAT microSD slot store on the ESP32, one file per record on native builds, and in-RAM tables for tests.
RecordCodec, which wraps a payload in a 16-byte self-checking envelope.PersistenceService, a role registry with envelope helpers.
Engine does not own any of it: the game constructs the stores and the service. Writes are explicit - nothing is written in the background - and on the ESP32 every flash write stalls flash-resident code on both cores, so save at a safe point such as a menu. See the Persistence subsystem for the envelope layout, atomicity per adapter, measured costs and limits.
Usage
ESP32: settings in NVS
#include "persistence/PersistenceService.h"
#include "drivers/esp32/Esp32NvsStore.h"
using namespace pixelroot32::persistence;
struct Settings { // the game's own record
uint8_t volume = 8;
uint8_t brightness = 12;
};
constexpr uint16_t kSettingsSchema = 1;
Esp32NvsKeyValueStore settingsStore("mygame", 64); // namespace, max blob
Esp32NvsSlotStore saveStore("mygame", "save", 3, 256); // keys save0..save2
PersistenceService persistence;
void setupPersistence() {
if (settingsStore.init() == StoreResult::Ok) {
persistence.bindSettings(&settingsStore);
}
if (saveStore.init() == StoreResult::Ok) {
persistence.bindSaves(&saveStore);
}
// An unbound role answers Unavailable: the game runs on defaults.
}
// Call from a menu or pause screen, never mid-gameplay.
StoreResult saveSettings(const Settings& s) {
const uint8_t payload[2] = {s.volume, s.brightness}; // explicit layout
uint8_t scratch[RecordCodec::kHeaderSize + sizeof(payload)];
StoreResult r = persistence.saveSettingRecord("cfg", kSettingsSchema, payload,
sizeof(payload), scratch, sizeof(scratch));
if (r != StoreResult::Ok) {
return r;
}
return persistence.settings().commit(); // the durability point
}
Settings loadSettings() {
Settings s; // defaults
uint8_t scratch[RecordCodec::kHeaderSize + 16];
const uint8_t* payload = nullptr;
RecordInfo info{};
if (persistence.loadSettingRecord("cfg", scratch, sizeof(scratch), payload, info) ==
StoreResult::Ok &&
info.schemaVersion == kSettingsSchema && info.payloadSize == 2) {
s.volume = payload[0];
s.brightness = payload[1];
}
// NotFound (first run), Corrupt, an older schema: keep or migrate defaults.
return s;
}Save slots work the same way through saveRecord(slot, ...) and loadRecord(slot, ...).
Native (PC) builds: host files
#include "persistence/PersistenceService.h"
#include "drivers/native/HostFileStore.h"
using namespace pixelroot32::persistence;
HostFileKeyValueStore settingsStore("save_data", "mygame", 64); // root, namespace, max blob
HostFileSlotStore saveStore("save_data", "save", 3, 256); // root, prefix, slots, max record
PersistenceService persistence;
void setupPersistence() {
if (settingsStore.init() == StoreResult::Ok) { // creates save_data/mygame/
persistence.bindSettings(&settingsStore);
}
if (saveStore.init() == StoreResult::Ok) { // creates save_data/save/
persistence.bindSaves(&saveStore);
}
}The game code that saves and loads is the same as on the ESP32; only the store construction differs. A game that builds for both picks the adapter with #ifdef ESP32 / #ifdef PLATFORM_NATIVE around the store definitions.
Results and keys (StoreTypes.h)
enum class StoreResult : uint8_t {
Ok, NotFound, TooLarge, NoSpace, Corrupt, IoError, Unavailable, InvalidKey, InvalidArgument
};
inline constexpr size_t kMaxKeyLength = 15;
inline bool isValidKey(const char* key);StoreResult | Meaning |
|---|---|
Ok | The operation completed |
NotFound | The key or slot holds no record; outputs are untouched |
TooLarge | The data does not fit the caller's buffer or the medium's limit |
NoSpace | The medium is full |
Corrupt | Stored bytes failed validation (envelope, length or CRC) |
IoError | The medium reported a failure the module cannot classify further |
Unavailable | No store is bound, or the medium is not initialised |
InvalidKey | The key or namespace breaks the rules of isValidKey() |
InvalidArgument | A null pointer, an out-of-range slot or another bad parameter |
isValidKey() accepts 1..kMaxKeyLength bytes, each in [A-Za-z0-9_-], and rejects nullptr. Namespaces and slot prefixes follow the same rule. Every store checks keys before touching the medium.
IKeyValueStore
class IKeyValueStore {
public:
virtual ~IKeyValueStore() = default;
virtual StoreResult getI32(const char* key, int32_t& out) = 0;
virtual StoreResult setI32(const char* key, int32_t value) = 0;
virtual StoreResult getU32(const char* key, uint32_t& out) = 0;
virtual StoreResult setU32(const char* key, uint32_t value) = 0;
virtual StoreResult getBlob(const char* key, uint8_t* out, size_t capacity,
size_t& stored) = 0;
virtual StoreResult setBlob(const char* key, const uint8_t* data, size_t size) = 0;
virtual StoreResult erase(const char* key) = 0;
virtual StoreResult commit() = 0;
};| Rule | Detail |
|---|---|
| One value per key | A set of any type replaces whatever the key held; a typed get on a key holding another type is NotFound |
| Missing key | NotFound, every output untouched |
getBlob() capacity | Never writes past capacity. A larger blob is TooLarge, nothing written, stored set to its size |
| Size query | capacity == 0 (with out == nullptr allowed only then): TooLarge + stored for a non-empty blob, Ok + 0 for an empty one |
setBlob() limits | TooLarge above the store's per-value maximum, NoSpace when full; a null data is allowed only with size == 0 |
| Failed set | The previous value is kept |
erase() | NotFound for a missing key |
commit() | Makes every earlier set and erase durable; the game decides when |
ISlotStore
class ISlotStore {
public:
virtual ~ISlotStore() = default;
virtual uint16_t slotCount() const = 0;
virtual size_t maxRecordSize() const = 0;
virtual StoreResult query(uint16_t slot, size_t& stored) = 0;
virtual StoreResult read(uint16_t slot, uint8_t* out, size_t capacity,
size_t& stored) = 0;
virtual StoreResult write(uint16_t slot, const uint8_t* data, size_t size) = 0;
virtual StoreResult erase(uint16_t slot) = 0;
};| Rule | Detail |
|---|---|
| Slot range | 0..slotCount()-1; anything else is InvalidArgument before the medium is touched |
| Empty slot | query()/read() answer NotFound with stored = 0 |
read() capacity | Same rules as getBlob(), including the capacity == 0 size query |
write() | Replace-or-keep: after a failed or interrupted write, read() returns the old record or the new one, never a mix. TooLarge above maxRecordSize(). A zero-size record occupies the slot. An adapter on a medium that cannot replace atomically (FAT, see SdSlotStore) documents that a power loss can also leave the slot empty |
erase() | NotFound when the slot is already empty |
RecordCodec
uint32_t crc32(const uint8_t* data, size_t size, uint32_t crc = 0);
struct RecordInfo {
uint16_t schemaVersion; // game-owned, reported as stored
size_t payloadSize; // bytes after the header
};
class RecordCodec {
public:
static constexpr size_t kHeaderSize = 16;
static constexpr uint8_t kEnvelopeVersion = 1;
static StoreResult encode(uint16_t schema, const uint8_t* payload, size_t size,
uint8_t* out, size_t capacity, size_t& written);
static StoreResult decode(const uint8_t* in, size_t size, const uint8_t*& payload,
RecordInfo& info);
};encode()writeskHeaderSize + sizebytes intoout. It answersTooLargewhencapacityis smaller,InvalidArgumentfor a nullout, a nullpayloadwith a non-zero size, or a size beyond 32 bits.writtenis0on failure and nothing is written.decode()validates a whole record of exactlysizebytes. It answersCorruptfor a truncated record, wrong magic, unknown envelope version, non-zero reserved byte, a length mismatch or a CRC mismatch, andInvalidArgumentfor a nullin. OnOk,payloadpoints atin + kHeaderSize; on failurepayloadandinfoare untouched. The schema version is reported, never judged.crc32()is CRC-32/IEEE (zlib/PNG). Passing a previous result ascrccontinues the stream.
PersistenceService
class PersistenceService {
public:
void bindSettings(IKeyValueStore* store); // nullptr unbinds; not owned
void bindSaves(ISlotStore* store); // nullptr unbinds; not owned
IKeyValueStore& settings(); // never null
ISlotStore& saves(); // never null
bool hasSettings() const;
bool hasSaves() const;
StoreResult saveRecord(uint16_t slot, uint16_t schema, const uint8_t* payload, size_t size,
uint8_t* scratch, size_t scratchCapacity);
StoreResult loadRecord(uint16_t slot, uint8_t* scratch, size_t scratchCapacity,
const uint8_t*& payload, RecordInfo& info);
StoreResult saveSettingRecord(const char* key, uint16_t schema, const uint8_t* payload,
size_t size, uint8_t* scratch, size_t scratchCapacity);
StoreResult loadSettingRecord(const char* key, uint8_t* scratch, size_t scratchCapacity,
const uint8_t*& payload, RecordInfo& info);
};- An unbound role returns a null store:
NullKeyValueStoreorNullSlotStore, both public. Every call on them answersUnavailable;NullSlotStorereportsslotCount() == 0andmaxRecordSize() == 0. saveRecord()/saveSettingRecord()check in this order:Unavailablewhen the role is unbound,InvalidArgumentfor a nullscratch, the codec's result (TooLargewhenscratchCapacityis belowkHeaderSize + size) with the store untouched, then the store'swrite()/setBlob()result unchanged.loadRecord()/loadSettingRecord()checkUnavailable, thenInvalidArgumentfor a nullscratch, then pass the store'sread()/getBlob()result unchanged (NotFound,TooLarge, ...), then answerCorruptwhen the envelope fails to decode. OnOk,payloadpoints insidescratch.- The service never calls
commit(). Callsettings().commit()yourself at a safe point. - The service holds no buffer and does not validate keys itself: the store answers
InvalidKey.
Adapters
All adapters are in pixelroot32::persistence. Every adapter with an init() answers Unavailable to every operation until init() returns Ok; slotCount() and maxRecordSize() report the configuration at any time.
Esp32NvsKeyValueStore and Esp32NvsSlotStore (ESP32)
inline constexpr const char* kNvsDefaultPartition = "nvs";
class Esp32NvsKeyValueStore final : public IKeyValueStore {
public:
Esp32NvsKeyValueStore(const char* nameSpace, size_t maxBlobBytes,
const char* partition = kNvsDefaultPartition) noexcept;
StoreResult init() noexcept;
size_t maxBlobSize() const noexcept;
// ... IKeyValueStore
};
class Esp32NvsSlotStore final : public ISlotStore {
public:
Esp32NvsSlotStore(const char* nameSpace, const char* prefix, uint16_t slots,
size_t maxRecordBytes,
const char* partition = kNvsDefaultPartition) noexcept;
StoreResult init() noexcept;
// ... ISlotStore
};- Guarded by
ESP32. One NVS namespace per store; slotiis the blob under<prefix><i>, andinit()rejects a prefix that leaves no room for the slot digits within 15 characters (InvalidKey). init()initialises the partition if nobody has and opens the namespace. It never erases: a partition that needs an erase answersCorrupt. Other results:InvalidKey,InvalidArgument(zero maximum, zero slots, null or empty partition label),IoError(including a missing partition).- Blobs are byte-compatible with Arduino
Preferences::putBytes()/getBytes()in the same namespace. - Sets reach flash immediately (NVS has no write-back cache);
commit()callsnvs_commit. Both stall flash-resident code on both cores. - Non-copyable; the destructor closes the handle. The namespace and partition strings must stay valid until
init()has run; the slot prefix must outlive the slot store. String literals are the intended use.
HostFileKeyValueStore and HostFileSlotStore (native)
inline constexpr size_t kHostFileMaxPathBytes = 260;
inline constexpr size_t kHostFileNameReserveBytes = 1 + 2 * kMaxKeyLength + 7;
class HostFileKeyValueStore final : public IKeyValueStore {
public:
HostFileKeyValueStore(const char* rootDir, const char* nameSpace,
size_t maxBlobBytes) noexcept;
StoreResult init() noexcept;
size_t maxBlobSize() const noexcept;
void setFailBeforeReplace(bool fail) noexcept; // test hook
// ... IKeyValueStore
};
class HostFileSlotStore final : public ISlotStore {
public:
HostFileSlotStore(const char* rootDir, const char* prefix, uint16_t slots,
size_t maxRecordBytes) noexcept;
StoreResult init() noexcept;
void setFailBeforeReplace(bool fail) noexcept; // test hook
// ... ISlotStore
};- Guarded by
PLATFORM_NATIVE. Files live in<rootDir>/<nameSpace>/or<rootDir>/<prefix>/;init()creates the directory and its parents. init()answersInvalidArgumentfor a null or empty root, a zero maximum, zero slots or a root too long forkHostFileMaxPathBytes;InvalidKeyfor an invalid namespace or prefix;IoErrorwhen the directory cannot be created.- Every write goes to a temp file and is moved over the final file in one step, so replace-or-keep holds.
commit()answersOk. - A malformed file reads as
IoError. The constructor copies its strings. setFailBeforeReplace(true)simulates a crash between the temp write and the move: the set answersIoErrorand the old value is kept.
SdSlotStore (ESP32)
inline constexpr size_t kSdMaxPathBytes = 160;
class SdSlotStore final : public ISlotStore {
public:
SdSlotStore(const char* rootDir, const char* prefix, uint16_t slots,
size_t maxRecordBytes) noexcept;
StoreResult init(const SdConfig& config) noexcept;
// ... ISlotStore
};- Guarded by
ESP32andPIXELROOT32_ENABLE_SD_STORAGE. The hardware description is a plainSdConfig(include/drivers/esp32/SdConfig.h):SPIClass* spi,int sck/miso/mosi/cs(-1= bus default) anduint32_t frequencyHz, which defaults tokSdDefaultFrequencyHz(4 MHz). No board pin lives in the adapter. init()validates before touching the medium: a non-emptyrootDirwith a leading/and short enough forkSdMaxPathBytes(160) together with the prefix and one slot file, aprefixthat passesisValidKey()(1..15 bytes of[A-Za-z0-9_-]), non-zeroslotsandmaxRecordBytes, a non-nullspi, acspin in 0..127 andsck/miso/mosiin -1..127. A bad argument isInvalidArgument(InvalidKeyfor the prefix) and nothing is mounted or created.- One file per slot at
<rootDir>/<prefix>/<i>.slot;rootDiris a path under the mountpoint the ArduinoSDlibrary uses, sorootDir"/pr32demo"and prefix"save"give/pr32demo/save/0.sloton the card. A missing file is an empty slot.rootDirandprefixare held by pointer and must outlive the store (string literals are the intended use). init(config)is non-destructive: it brings up the SPI bus, mounts the card and creates the directory. It never formats, erases or repairs. Until it returnsOkevery operation answersUnavailable; a missing or unmountable card answersUnavailableatinit(), so a game boots and keeps running.- Replace-or-keep is remove then rename. A write goes to
<file>.tmp, is flushed (fsync) and closed, the old file is removed, thenSD.renamemoves the new file into place, because FAT cannot rename over an existing destination. A power loss before the removal keeps the old record; one during the rename yields the new record or a torn one thatRecordCodecrejects asCorrupt; one in the gap between remove and rename leaves an empty slot (NotFound). - Removable media. A card pulled after
init()is not detected up front: the ArduinoSDlibrary caches the card type at mount, so the call that touches the card answersIoError(orNotFoundfor a missing file). Callinit()again after reinserting: it probes the store directory, releases the dead volume (SD.end()) and mounts again, so recovery needs no reboot. A full card isNoSpace; an oversized or malformed file isIoError, never a silent empty slot. - There is no
commit(): each write is already flushed and in place.
It is opt-in and ESP32 only:
build_flags =
-D PIXELROOT32_ENABLE_PERSISTENCE=1
-D PIXELROOT32_ENABLE_SD_STORAGE=1PIXELROOT32_ENABLE_SD_STORAGE defaults to 0. Asking for it without PIXELROOT32_ENABLE_PERSISTENCE=1, or on a target that is not ESP32, fails the build with an explicit #error. There is no new lib_deps: the adapter mounts through the Arduino SD library that ships with the ESP32 core. FATFS costs several KB of RAM once linked.
The CYD (ESP32-2432S028R) microSD reader is on SPI/VSPI:
#include "persistence/PersistenceService.h"
#include "drivers/esp32/SdStore.h"
using namespace pixelroot32::persistence;
SdConfig sdConfig;
sdConfig.spi = &SPI;
sdConfig.cs = 5;
sdConfig.sck = 18;
sdConfig.miso = 19;
sdConfig.mosi = 23;
sdConfig.frequencyHz = 4000000; // conservative first bring-up clock
SdSlotStore saveStore("/pr32demo", "save", 3, 256);
PersistenceService persistence;
if (saveStore.init(sdConfig) == StoreResult::Ok) {
persistence.bindSaves(&saveStore); // settings may stay on NVS
}The persistence example's opt-in esp32sd environment wires exactly this, next to its default NVS build: examples/persistence.
On a CYD the card reader owns VSPI, so the panel has to move off it: build TFT_eSPI with -D USE_HSPI_PORT. Otherwise SD.begin() reconfigures the VSPI bus and the panel loses its data lines — the backlight stays on and the screen stays empty. Panel on HSPI, card on VSPI is the combination that works.
MemoryKeyValueStore and MemorySlotStore (any target)
template <size_t Entries, size_t BlobBytes>
class MemoryKeyValueStore final : public IKeyValueStore {
public:
// ... IKeyValueStore
void setFailWrites(bool fail);
StoreResult corruptByte(const char* key, size_t index);
uint32_t writes() const;
uint32_t commits() const;
};
template <uint16_t Slots, size_t RecordBytes>
class MemorySlotStore final : public ISlotStore {
public:
// ... ISlotStore
void setFailWrites(bool fail);
StoreResult corruptByte(uint16_t slot, size_t index);
uint32_t writes() const;
};- Header-only, no heap, no
init(). Contents are lost with the object. - A new key beyond
EntriesisNoSpace; a blob aboveBlobBytesor a record aboveRecordBytesisTooLarge. - Test hooks:
setFailWrites(true)makes writes, erases (and, for KV,commit()) answerIoErrorwithout changing anything;corruptByte()flips one stored byte;writes()andcommits()count successful calls.
Public headers
| Header | Contents |
|---|---|
include/persistence/StoreTypes.h | StoreResult, kMaxKeyLength, isValidKey() |
include/persistence/KeyValueStore.h | IKeyValueStore |
include/persistence/SlotStore.h | ISlotStore |
include/persistence/RecordCodec.h | RecordCodec, RecordInfo, crc32() |
include/persistence/PersistenceService.h | PersistenceService, NullKeyValueStore, NullSlotStore |
include/persistence/MemoryStores.h | MemoryKeyValueStore, MemorySlotStore |
include/drivers/esp32/Esp32NvsStore.h | Esp32NvsKeyValueStore, Esp32NvsSlotStore, kNvsDefaultPartition (guarded by ESP32) |
include/drivers/esp32/SdConfig.h | SdConfig, kSdDefaultFrequencyHz (guarded by ESP32 + PIXELROOT32_ENABLE_SD_STORAGE) |
include/drivers/esp32/SdStore.h | SdSlotStore, kSdMaxPathBytes (guarded by ESP32 + PIXELROOT32_ENABLE_SD_STORAGE) |
include/drivers/native/HostFileStore.h | HostFileKeyValueStore, HostFileSlotStore, path limits (guarded by PLATFORM_NATIVE) |
The headers are the source of truth for signatures and exact wording.
Related documentation
- Persistence guide - setup per platform, settings and save slots, schema versions, when to save.
- Persistence subsystem - envelope, atomicity, flash stall, memory and limits.
- Configuration -
PIXELROOT32_ENABLE_PERSISTENCE. - API index - all modules.
