Skip to main content

prns_runtime_embassy/runtime/
shared_flash.rs

1use embassy_sync::blocking_mutex::raw::RawMutex;
2use embassy_sync::mutex::Mutex;
3use embedded_storage_async::nor_flash::{ErrorType, NorFlash, ReadNorFlash};
4
5/// A copyable view of one asynchronously serialized NOR flash device.
6///
7/// Each operation holds the device lock through completion. Higher-level stores may interleave
8/// operations safely when their flash regions are disjoint.
9pub struct SharedNorFlash<'a, M, F>
10where
11    M: RawMutex,
12{
13    flash: &'a Mutex<M, F>,
14    capacity: usize,
15}
16
17impl<'a, M, F> SharedNorFlash<'a, M, F>
18where
19    M: RawMutex,
20{
21    #[must_use]
22    pub const fn new(flash: &'a Mutex<M, F>, capacity: usize) -> Self {
23        Self { flash, capacity }
24    }
25}
26
27impl<M, F> Clone for SharedNorFlash<'_, M, F>
28where
29    M: RawMutex,
30{
31    fn clone(&self) -> Self {
32        *self
33    }
34}
35
36impl<M, F> Copy for SharedNorFlash<'_, M, F> where M: RawMutex {}
37
38impl<M, F> ErrorType for SharedNorFlash<'_, M, F>
39where
40    M: RawMutex,
41    F: ErrorType,
42{
43    type Error = F::Error;
44}
45
46impl<M, F> ReadNorFlash for SharedNorFlash<'_, M, F>
47where
48    M: RawMutex,
49    F: ReadNorFlash,
50{
51    const READ_SIZE: usize = F::READ_SIZE;
52
53    async fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
54        self.flash.lock().await.read(offset, bytes).await
55    }
56
57    fn capacity(&self) -> usize {
58        self.capacity
59    }
60}
61
62impl<M, F> NorFlash for SharedNorFlash<'_, M, F>
63where
64    M: RawMutex,
65    F: NorFlash,
66{
67    const WRITE_SIZE: usize = F::WRITE_SIZE;
68    const ERASE_SIZE: usize = F::ERASE_SIZE;
69
70    async fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
71        self.flash.lock().await.erase(from, to).await
72    }
73
74    async fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
75        self.flash.lock().await.write(offset, bytes).await
76    }
77}