Skip to main content

Module stateful

Module stateful 

Source
Expand description

Opt-in persistable state trait for widgets. Opt-in trait for widgets with persistable state.

The Stateful trait defines a contract for widgets that can save and restore their state across sessions or configuration changes. It is orthogonal to StatefulWidget — a widget can implement both (render-time state mutation + persistence) or just one.

§Design Invariants

  1. Round-trip fidelity: restore_state(save_state()) must produce an equivalent observable state. Fields that are purely derived (e.g., cached layout) may differ, but user-facing state (scroll position, selection, expanded nodes) must survive the round trip.

  2. Graceful version mismatch: When VersionedState detects a version mismatch (stored.version != T::state_version()), the caller should fall back to T::State::default() rather than panic. Migration logic belongs in the downstream state migration system (bd-30g1.5).

  3. Key uniqueness: Two distinct widget instances must produce distinct StateKey values. The (widget_type, instance_id) pair is the primary uniqueness invariant.

  4. No side effects: save_state must be a pure read; restore_state must only mutate self (no I/O, no global state).

§Failure Modes

FailureCauseFallback
Deserialization errorSchema drift, corrupt dataUse Default::default()
Version mismatchWidget upgradedUse Default::default()
Missing stateFirst run, key changedUse Default::default()
Duplicate keyBug in state_key() implLast-write-wins (logged)

§Feature Gate

This module is always available, but the serde-based VersionedState wrapper requires the state-persistence feature for serialization support.

Structs§

MigrationChain
A chain of migrations that can upgrade state through multiple versions.
StateKey
Unique identifier for a widget’s persisted state.
VersionedState
Version-tagged wrapper for serialized widget state.

Enums§

MigrationError
Error that can occur during state migration.
RestoreResult
Result of attempting state restoration with migration.

Traits§

ErasedMigration
A type-erased migration step for use in migration chains.
StateMigration
A single-step migration from version N to version N+1.
Stateful
Opt-in trait for widgets with persistable state.