rktk_drivers_common/storage/
flash_sequential_map.rs1use core::fmt::Debug;
4use embedded_storage_async::nor_flash::{MultiwriteNorFlash, NorFlash, ReadNorFlash};
5use rktk::{
6 drivers::interface::{Error, storage::StorageDriver},
7 utils::Mutex,
8};
9pub use sequential_storage;
10use sequential_storage::{
11 cache::NoCache,
12 map::{MapConfig, MapStorage},
13};
14
15#[derive(Debug)]
18#[cfg_attr(feature = "defmt", derive(defmt::Format))]
19pub enum FlashSequentialMapStorageError<E: Debug> {
20 Storage(#[cfg_attr(feature = "defmt", defmt(Debug2Format))] sequential_storage::Error<E>),
21 NotFound,
22}
23impl<E: Debug> Error for FlashSequentialMapStorageError<E> {}
24
25impl<E: Debug> From<sequential_storage::Error<E>> for FlashSequentialMapStorageError<E> {
26 fn from(e: sequential_storage::Error<E>) -> Self {
27 Self::Storage(e)
28 }
29}
30
31pub struct FlashSequentialMapStorage<F: NorFlash + ReadNorFlash + MultiwriteNorFlash> {
34 storage: Mutex<MapStorage<u64, F, NoCache>>,
35}
36
37impl<F: NorFlash + ReadNorFlash + MultiwriteNorFlash> FlashSequentialMapStorage<F> {
38 pub fn new(flash: F, start_address: u32, storage_size: u32) -> Self {
39 let storage = MapStorage::new(
40 flash,
41 MapConfig::new(start_address..start_address + storage_size),
42 NoCache,
43 );
44 Self {
45 storage: Mutex::new(storage),
46 }
47 }
48}
49
50impl<F: NorFlash + ReadNorFlash + MultiwriteNorFlash> StorageDriver
51 for FlashSequentialMapStorage<F>
52{
53 type Error = FlashSequentialMapStorageError<F::Error>;
54
55 async fn format(&self) -> Result<(), Self::Error> {
56 let mut storage = self.storage.lock().await;
57 storage.remove_all_items(&mut [0; 1024]).await?;
58 Ok(())
59 }
60
61 async fn read<const N: usize>(&self, key: u64, buf: &mut [u8]) -> Result<(), Self::Error> {
62 let mut storage = self.storage.lock().await;
63 let val: [u8; N] = storage
64 .fetch_item(&mut [0; 1024], &key)
65 .await?
66 .ok_or(FlashSequentialMapStorageError::NotFound)?;
67 buf.copy_from_slice(&val);
68 Ok(())
69 }
70
71 async fn write<const N: usize>(&self, key: u64, item_buf: &[u8]) -> Result<(), Self::Error> {
72 let mut storage = self.storage.lock().await;
73 storage.store_item(&mut [0; 1024], &key, &item_buf).await?;
74 Ok(())
75 }
76}