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::{Cache, Uncached},
12 map::{MapConfig, MapStorage},
13};
14
15type NoCache = Cache<Uncached, Uncached, Uncached, u64>;
16
17#[derive(Debug)]
20#[cfg_attr(feature = "defmt", derive(defmt::Format))]
21pub enum FlashSequentialMapStorageError<E: Debug> {
22 Storage(#[cfg_attr(feature = "defmt", defmt(Debug2Format))] sequential_storage::Error<E>),
23 NotFound,
24}
25impl<E: Debug> Error for FlashSequentialMapStorageError<E> {}
26
27impl<E: Debug> From<sequential_storage::Error<E>> for FlashSequentialMapStorageError<E> {
28 fn from(e: sequential_storage::Error<E>) -> Self {
29 Self::Storage(e)
30 }
31}
32
33pub struct FlashSequentialMapStorage<F: NorFlash + ReadNorFlash + MultiwriteNorFlash> {
36 storage: Mutex<MapStorage<u64, F, NoCache>>,
37}
38
39impl<F: NorFlash + ReadNorFlash + MultiwriteNorFlash> FlashSequentialMapStorage<F> {
40 pub fn new(flash: F, start_address: u32, storage_size: u32) -> Self {
41 let storage = MapStorage::new(
42 flash,
43 MapConfig::new(start_address..start_address + storage_size),
44 Cache::new_uncached(),
45 );
46 Self { storage: Mutex::new(storage) }
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}