extern crate alloc;
use alloc::vec;
use alloc::vec::Vec;
use core::fmt;
use embedded_storage::nor_flash::{
ErrorType, NorFlash, NorFlashError, NorFlashErrorKind, ReadNorFlash,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MockFlashError {
OutOfBounds,
NotAligned,
NotErased,
PowerLoss,
NotPresent,
}
impl NorFlashError for MockFlashError {
fn kind(&self) -> NorFlashErrorKind {
match self {
MockFlashError::OutOfBounds => NorFlashErrorKind::OutOfBounds,
MockFlashError::NotAligned => NorFlashErrorKind::NotAligned,
MockFlashError::NotErased => NorFlashErrorKind::Other,
MockFlashError::PowerLoss => NorFlashErrorKind::Other,
MockFlashError::NotPresent => NorFlashErrorKind::Other,
}
}
}
impl fmt::Display for MockFlashError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MockFlashError::OutOfBounds => write!(f, "out of bounds"),
MockFlashError::NotAligned => write!(f, "not aligned"),
MockFlashError::NotErased => write!(f, "region not erased"),
MockFlashError::PowerLoss => write!(f, "simulated power loss"),
MockFlashError::NotPresent => write!(f, "medium not present"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PowerLossMode {
Clean,
Partial(usize),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct FlashOps {
pub reads: u64,
pub read_bytes: u64,
pub writes: u64,
pub erases: u64,
}
impl core::ops::Sub for FlashOps {
type Output = Self;
fn sub(self, earlier: Self) -> Self {
Self {
reads: self.reads.saturating_sub(earlier.reads),
read_bytes: self.read_bytes.saturating_sub(earlier.read_bytes),
writes: self.writes.saturating_sub(earlier.writes),
erases: self.erases.saturating_sub(earlier.erases),
}
}
}
#[derive(Clone)]
pub struct MockFlash<const PAGE_SIZE: usize, const SECTOR_SIZE: usize> {
data: Vec<u8>,
pub erase_counts: Vec<u32>,
pub write_count: u64,
pub erase_ops: u64,
pub read_ops: u64,
pub read_bytes: u64,
fail_after_n_writes: Option<u64>,
power_loss_mode: PowerLossMode,
tear_erase_after: Option<(u64, usize)>,
power_lost: bool,
}
impl<const PAGE_SIZE: usize, const SECTOR_SIZE: usize> MockFlash<PAGE_SIZE, SECTOR_SIZE> {
pub fn new(size: usize) -> Self {
assert!(
size.is_multiple_of(SECTOR_SIZE),
"size must be a multiple of SECTOR_SIZE"
);
let sectors = size / SECTOR_SIZE;
Self {
data: vec![0xFF; size],
erase_counts: vec![0; sectors],
write_count: 0,
erase_ops: 0,
read_ops: 0,
read_bytes: 0,
fail_after_n_writes: None,
power_loss_mode: PowerLossMode::Clean,
tear_erase_after: None,
power_lost: false,
}
}
pub fn set_power_loss_after(&mut self, n: u64, mode: PowerLossMode) {
self.fail_after_n_writes = Some(n);
self.power_loss_mode = mode;
self.power_lost = false;
}
pub fn set_erase_loss_after(&mut self, n: u64, bytes: usize) {
self.tear_erase_after = Some((n, bytes));
self.power_lost = false;
}
pub fn is_power_lost(&self) -> bool {
self.power_lost
}
pub fn clear_power_loss(&mut self) {
self.fail_after_n_writes = None;
self.tear_erase_after = None;
self.power_lost = false;
}
pub fn total_erases(&self) -> u64 {
self.erase_counts.iter().map(|c| *c as u64).sum()
}
pub fn ops(&self) -> FlashOps {
FlashOps {
reads: self.read_ops,
read_bytes: self.read_bytes,
writes: self.write_count,
erases: self.erase_ops,
}
}
pub fn hex_dump(&self, offset: usize, len: usize) -> Vec<u8> {
self.data[offset..offset + len].to_vec()
}
}
impl<const PAGE_SIZE: usize, const SECTOR_SIZE: usize> ErrorType
for MockFlash<PAGE_SIZE, SECTOR_SIZE>
{
type Error = MockFlashError;
}
impl<const PAGE_SIZE: usize, const SECTOR_SIZE: usize> ReadNorFlash
for MockFlash<PAGE_SIZE, SECTOR_SIZE>
{
const READ_SIZE: usize = 1;
fn read(&mut self, offset: u32, buf: &mut [u8]) -> Result<(), Self::Error> {
let start = offset as usize;
let end = start + buf.len();
if end > self.data.len() {
return Err(MockFlashError::OutOfBounds);
}
buf.copy_from_slice(&self.data[start..end]);
self.read_ops += 1;
self.read_bytes += buf.len() as u64;
Ok(())
}
fn capacity(&self) -> usize {
self.data.len()
}
}
impl<const PAGE_SIZE: usize, const SECTOR_SIZE: usize> NorFlash
for MockFlash<PAGE_SIZE, SECTOR_SIZE>
{
const WRITE_SIZE: usize = PAGE_SIZE;
const ERASE_SIZE: usize = SECTOR_SIZE;
fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
let from = from as usize;
let to = to as usize;
if !from.is_multiple_of(SECTOR_SIZE) || !to.is_multiple_of(SECTOR_SIZE) {
return Err(MockFlashError::NotAligned);
}
if to > self.data.len() {
return Err(MockFlashError::OutOfBounds);
}
if let Some((threshold, bytes)) = self.tear_erase_after
&& self.erase_ops >= threshold
{
self.power_lost = true;
self.erase_ops += 1;
let stopped_at = (from + bytes).min(to);
self.data[from..stopped_at].fill(0xFF);
return Err(MockFlashError::PowerLoss);
}
self.data[from..to].fill(0xFF);
self.erase_ops += 1;
let sector_start = from / SECTOR_SIZE;
let sector_end = to / SECTOR_SIZE;
for s in sector_start..sector_end {
self.erase_counts[s] += 1;
}
Ok(())
}
fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
let offset_usize = offset as usize;
if !offset_usize.is_multiple_of(PAGE_SIZE) {
return Err(MockFlashError::NotAligned);
}
if !bytes.len().is_multiple_of(PAGE_SIZE) {
return Err(MockFlashError::NotAligned);
}
if offset_usize + bytes.len() > self.data.len() {
return Err(MockFlashError::OutOfBounds);
}
if let Some(threshold) = self.fail_after_n_writes
&& self.write_count >= threshold
{
self.power_lost = true;
match self.power_loss_mode {
PowerLossMode::Clean => {
return Err(MockFlashError::PowerLoss);
}
PowerLossMode::Partial(n) => {
let to_write = n.min(bytes.len());
for (dst, src) in self.data[offset_usize..offset_usize + to_write]
.iter_mut()
.zip(&bytes[..to_write])
{
*dst &= src;
}
self.write_count += 1;
return Err(MockFlashError::PowerLoss);
}
}
}
for (i, &byte) in bytes.iter().enumerate() {
let existing = self.data[offset_usize + i];
if existing & byte != byte {
return Err(MockFlashError::NotErased);
}
}
self.data[offset_usize..offset_usize + bytes.len()].copy_from_slice(bytes);
self.write_count += 1;
Ok(())
}
}
#[derive(Clone)]
pub struct RemovableFlash<F> {
inner: F,
present: bool,
yank_after_writes: Option<u64>,
writes: u64,
}
impl<F> RemovableFlash<F> {
pub fn new(inner: F) -> Self {
Self {
inner,
present: true,
yank_after_writes: None,
writes: 0,
}
}
pub fn insert(&mut self) {
self.present = true;
self.yank_after_writes = None;
}
pub fn remove(&mut self) {
self.present = false;
self.yank_after_writes = None;
}
pub fn yank_after(&mut self, n: u64) {
self.yank_after_writes = Some(self.writes + n);
}
pub fn is_present(&self) -> bool {
self.present
}
pub fn write_count(&self) -> u64 {
self.writes
}
pub fn inner(&self) -> &F {
&self.inner
}
pub fn inner_mut(&mut self) -> &mut F {
&mut self.inner
}
pub fn into_inner(self) -> F {
self.inner
}
fn admit_write(&mut self) -> Result<(), MockFlashError> {
if !self.present {
return Err(MockFlashError::NotPresent);
}
if let Some(threshold) = self.yank_after_writes
&& self.writes >= threshold
{
self.present = false;
return Err(MockFlashError::NotPresent);
}
self.writes += 1;
Ok(())
}
fn admit_read(&self) -> Result<(), MockFlashError> {
if self.present {
Ok(())
} else {
Err(MockFlashError::NotPresent)
}
}
}
impl<F> crate::spool::Removable for RemovableFlash<F> {
fn is_present(&self) -> bool {
self.present
}
}
impl<F> ErrorType for RemovableFlash<F> {
type Error = MockFlashError;
}
impl<F> ReadNorFlash for RemovableFlash<F>
where
F: ReadNorFlash<Error = MockFlashError>,
{
const READ_SIZE: usize = 1;
fn read(&mut self, offset: u32, buf: &mut [u8]) -> Result<(), Self::Error> {
self.admit_read()?;
self.inner.read(offset, buf)
}
fn capacity(&self) -> usize {
self.inner.capacity()
}
}
impl<F> NorFlash for RemovableFlash<F>
where
F: NorFlash<Error = MockFlashError>,
{
const WRITE_SIZE: usize = F::WRITE_SIZE;
const ERASE_SIZE: usize = F::ERASE_SIZE;
fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
self.admit_write()?;
self.inner.erase(from, to)
}
fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
self.admit_write()?;
self.inner.write(offset, bytes)
}
}
#[cfg(feature = "async")]
#[derive(Clone)]
pub struct AsyncFlash<F> {
inner: F,
}
#[cfg(feature = "async")]
pub type MockFlashAsync<const PAGE_SIZE: usize, const SECTOR_SIZE: usize> =
AsyncFlash<MockFlash<PAGE_SIZE, SECTOR_SIZE>>;
#[cfg(feature = "async")]
impl<const PAGE_SIZE: usize, const SECTOR_SIZE: usize>
AsyncFlash<MockFlash<PAGE_SIZE, SECTOR_SIZE>>
{
pub fn new(size: usize) -> Self {
Self {
inner: MockFlash::<PAGE_SIZE, SECTOR_SIZE>::new(size),
}
}
}
#[cfg(feature = "async")]
impl<F> AsyncFlash<F> {
pub fn wrap(inner: F) -> Self {
Self { inner }
}
pub fn inner(&self) -> &F {
&self.inner
}
pub fn inner_mut(&mut self) -> &mut F {
&mut self.inner
}
pub fn into_inner(self) -> F {
self.inner
}
}
#[cfg(feature = "async")]
impl<F: ErrorType> embedded_storage_async::nor_flash::ErrorType for AsyncFlash<F> {
type Error = F::Error;
}
#[cfg(feature = "async")]
impl<F: ReadNorFlash> embedded_storage_async::nor_flash::ReadNorFlash for AsyncFlash<F> {
const READ_SIZE: usize = F::READ_SIZE;
async fn read(&mut self, offset: u32, buf: &mut [u8]) -> Result<(), Self::Error> {
self.inner.read(offset, buf)
}
fn capacity(&self) -> usize {
self.inner.capacity()
}
}
#[cfg(feature = "async")]
impl<F: NorFlash> embedded_storage_async::nor_flash::NorFlash for AsyncFlash<F> {
const WRITE_SIZE: usize = F::WRITE_SIZE;
const ERASE_SIZE: usize = F::ERASE_SIZE;
async fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
self.inner.erase(from, to)
}
async fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
self.inner.write(offset, bytes)
}
}
#[cfg(feature = "async")]
impl<F: crate::spool::Removable> crate::spool::Removable for AsyncFlash<F> {
fn is_present(&self) -> bool {
self.inner.is_present()
}
}
#[cfg(feature = "async")]
#[allow(unsafe_code, clippy::never_loop)]
pub fn block_on<T>(fut: impl core::future::Future<Output = T>) -> T {
use core::pin::pin;
use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
fn dummy_raw_waker() -> RawWaker {
fn no_op(_: *const ()) {}
fn clone(data: *const ()) -> RawWaker {
RawWaker::new(data, &VTABLE)
}
const VTABLE: RawWakerVTable = RawWakerVTable::new(clone, no_op, no_op, no_op);
RawWaker::new(core::ptr::null(), &VTABLE)
}
let waker = unsafe { Waker::from_raw(dummy_raw_waker()) };
let mut cx = Context::from_waker(&waker);
let mut fut = pin!(fut);
loop {
match fut.as_mut().poll(&mut cx) {
Poll::Ready(val) => return val,
Poll::Pending => panic!("async operation returned Pending in sync mock"),
}
}
}