#[derive(Debug, PartialEq)]
pub enum EepromError {
Busy,
AddressOutOfBounds,
BlockOutOfBounds,
OffsetOutOfBounds,
WriteWouldOverflow,
ReadWouldOverflow,
ReadBufferTooSmall,
}
impl core::fmt::Display for EepromError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
EepromError::Busy => write!(f, "Eeprom is busy"),
EepromError::AddressOutOfBounds => write!(f, "Address is out of bounds"),
EepromError::BlockOutOfBounds => write!(f, "Block is out of bounds"),
EepromError::OffsetOutOfBounds => write!(f, "Offset is out of bounds"),
EepromError::WriteWouldOverflow => {
write!(f, "Writing this data would overflow the EEPROM")
}
EepromError::ReadWouldOverflow => {
write!(f, "Reading this data would overflow the EEPROM")
}
EepromError::ReadBufferTooSmall => write!(f, "Allocated buffer too small for reading"),
}
}
}
#[derive(Clone, Copy)]
pub struct EepromAddress {
block: usize,
offset: usize,
}
impl EepromAddress {
pub fn new(block: usize, offset: usize) -> Self {
EepromAddress { block, offset }
}
pub fn block(&self) -> usize {
self.block
}
pub fn offset(&self) -> usize {
self.offset
}
pub fn increment(&mut self, offset_size: usize, block_size: usize) -> &mut Self {
self.offset += 1;
if self.offset >= offset_size {
self.offset = 0;
self.block += 1;
if self.block >= block_size {
self.block = 0;
}
}
self
}
}
pub trait Blocks {
fn block_size(&self) -> Result<usize, EepromError>;
fn word_index_to_address(&self, index: usize) -> Result<EepromAddress, EepromError>;
fn address_to_word_index(&self, block: &EepromAddress) -> Result<usize, EepromError>;
}
pub trait Erase {
fn erase(&mut self, address: &EepromAddress, length_bytes: usize) -> Result<(), EepromError>;
fn erase_block(&mut self, block: usize) -> Result<(), EepromError>;
}
pub trait Busy {
fn is_busy(&self) -> bool;
fn wait(&self);
}
pub trait Write {
fn write(&mut self, address: &EepromAddress, data: &[u8]) -> Result<(), EepromError>;
}
pub trait Read {
fn read(
&mut self,
address: &EepromAddress,
bytes_to_read: usize,
buffer: &mut [u8],
) -> Result<(), EepromError>;
}