embedded-storage icon indicating copy to clipboard operation
embedded-storage copied to clipboard

RmwNorFlashStorage requires aligned reads

Open adri326 opened this issue 1 year ago • 2 comments

The Storage trait does not expose any alignment information, and one would thus assume that implementations of it would allow for unaligned reads, but RmwNorFlashStorage currently does not. As an example, the following code snippets fails to run:

use embedded_storage::nor_flash::*;
use embedded_storage::ReadStorage;

/// A fake storage driver, that requires reads to be aligned to 4 bytes, and which will fill all of them with 0xFF
struct StrictApi;

impl ErrorType for StrictApi {
    type Error = NorFlashErrorKind;
}

impl ReadNorFlash for StrictApi {
    const READ_SIZE: usize = 4;

    fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
        let offset = offset as usize;

        if offset % Self::READ_SIZE != 0 || bytes.len() % Self::READ_SIZE != 0 {
            Err(NorFlashErrorKind::NotAligned)
        } else {
            for byte in bytes {
                *byte = 0xFF;
            }
            Ok(())
        }
    }

    fn capacity(&self) -> usize {
        8
    }
}

// Only required for RmwNorFlashStorage::new
impl NorFlash for StrictApi {
    const WRITE_SIZE: usize = 4;
    const ERASE_SIZE: usize = 4;

    fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> { unreachable!() }
    fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> { unreachable!() }
}

fn test_read_unaligned() {
    let mut buffer = [0x00; 4];
    let mut storage = RmwNorFlashStorage::new(StrictApi, &mut buffer);

    let mut my_buffer = [0x00; 1];
    storage.read(3, &mut my_buffer).unwrap();
    assert_eq!(my_buffer[0], 0xFF);
}

adri326 avatar Apr 03 '24 13:04 adri326

This is thankfully quite easy to fix (we already have a scratch buffer at our disposal), I'll happily submit a PR for it

adri326 avatar Apr 03 '24 13:04 adri326

A PR would be very welcomed :+1:

MathiasKoch avatar Jul 25 '24 08:07 MathiasKoch