pub trait FlashBlock {
type Error;
// Required methods
fn load<T>(&mut self) -> Result<Option<T>, Self::Error>
where T: Serialize + for<'de> Deserialize<'de>;
fn save<T>(&mut self, value: &T) -> Result<(), Self::Error>
where T: Serialize + for<'de> Deserialize<'de>;
fn clear(&mut self) -> Result<(), Self::Error>;
}Expand description
Operations on blocks of flash memory.
Platform crates implement this trait on their concrete flash block handle types.
Constructors and hardware wiring remain platform-specific; this trait defines the shared operation surface used by higher-level abstractions.
§Features
- Type safety: hash-based type checking prevents reading data written under a
different Rust type name. Trying to read a different type returns
Ok(None). - Postcard serialization: compact,
no_std-friendly binary format.
This example increments a persisted boot counter and clears a separate scratch block in the same helper.
§Example
use core::convert::Infallible;
use device_envoy_core::flash_block::FlashBlock;
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy)]
struct BootCounter(u8);
impl BootCounter {
const fn new(value: u8) -> Self {
Self(value)
}
fn increment(self) -> Self {
Self((self.0 + 1) % 10)
}
}
fn update_boot_counter_and_clear_scratch(
boot_counter_flash_block: &mut impl FlashBlock<Error = Infallible>,
scratch_flash_block: &mut impl FlashBlock<Error = Infallible>,
) -> Result<BootCounter, Infallible> {
// Load the typed value, defaulting to 0 when the block is empty.
let boot_counter = boot_counter_flash_block
.load()?
.unwrap_or(BootCounter::new(0))
.increment();
// Save the updated value back to flash.
boot_counter_flash_block.save(&boot_counter)?;
// Clear the extra scratch block.
scratch_flash_block.clear()?;
Ok(boot_counter)
}
Required Associated Types§
Required Methods§
Sourcefn load<T>(&mut self) -> Result<Option<T>, Self::Error>where
T: Serialize + for<'de> Deserialize<'de>,
fn load<T>(&mut self) -> Result<Option<T>, Self::Error>where
T: Serialize + for<'de> Deserialize<'de>,
Load a typed value from this block.
Returns Ok(None) when the block is empty or contains a different type.
See the FlashBlock trait documentation for usage examples.
Sourcefn save<T>(&mut self, value: &T) -> Result<(), Self::Error>where
T: Serialize + for<'de> Deserialize<'de>,
fn save<T>(&mut self, value: &T) -> Result<(), Self::Error>where
T: Serialize + for<'de> Deserialize<'de>,
Save a typed value to this block.
See the FlashBlock trait documentation for usage examples.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.