use core::convert::Infallible;
use std::vec::Vec;
use crate::{BlockDevice, BLOCK_SIZE};
#[path = "../tests/support/images.rs"]
mod images;
pub use images::{exfat_image, exfat_image_writable, fat32_image, ExFileSpec, FileSpec};
pub struct RamCard {
image: Vec<u8>,
#[cfg(feature = "write")]
writes: usize,
#[cfg(feature = "write")]
power_loss_after: Option<usize>,
}
impl RamCard {
pub fn new(image: Vec<u8>) -> Self {
Self {
image,
#[cfg(feature = "write")]
writes: 0,
#[cfg(feature = "write")]
power_loss_after: None,
}
}
pub fn image(&self) -> &[u8] {
&self.image
}
pub fn into_image(self) -> Vec<u8> {
self.image
}
}
#[cfg(feature = "write")]
impl RamCard {
pub fn writes(&self) -> usize {
self.writes
}
pub fn lose_power_after(&mut self, writes: usize) {
self.power_loss_after = Some(self.writes + writes);
}
}
#[cfg(feature = "write")]
impl crate::BlockWrite for RamCard {
async fn write_block(
&mut self,
block: u32,
buffer: &[u8; BLOCK_SIZE],
) -> Result<(), Infallible> {
if self
.power_loss_after
.is_some_and(|limit| self.writes >= limit)
{
return Ok(());
}
let start = block as usize * BLOCK_SIZE;
let slot = self
.image
.get_mut(start..start + BLOCK_SIZE)
.unwrap_or_else(|| panic!("RamCard: write to block {block}, past the end of the card"));
slot.copy_from_slice(buffer);
self.writes += 1;
Ok(())
}
}
impl BlockDevice for RamCard {
type Error = Infallible;
async fn read_block(
&mut self,
block: u32,
buffer: &mut [u8; BLOCK_SIZE],
) -> Result<(), Infallible> {
let start = block as usize * BLOCK_SIZE;
match self.image.get(start..start + BLOCK_SIZE) {
Some(data) => buffer.copy_from_slice(data),
None => buffer.fill(0),
}
Ok(())
}
async fn num_blocks(&mut self) -> Result<u32, Infallible> {
Ok((self.image.len() / BLOCK_SIZE) as u32)
}
}