rust-embedded-community / embedded-storage

An Embedded Storage Abstraction Layer
Apache License 2.0
63 stars 21 forks source link

RmwNorFlashStorage requires aligned reads #49

Open adri326 opened 5 months ago

adri326 commented 5 months ago

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 commented 5 months ago

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

MathiasKoch commented 1 month ago

A PR would be very welcomed :+1: