sensor-db 0.1.0

Append-only sensor database for NOR flash on embedded devices
Documentation
//! [`Partition`] — a `NorFlash` view of a sub-range of a larger device.
//!
//! One flash chip usually holds more than one thing: firmware, a config store,
//! and the sensor log. `Partition` is the ecosystem's answer to that — pure
//! address arithmetic over somebody else's driver, knowing nothing about which
//! driver it is:
//!
//! ```ignore
//! use sensor_db::{Partition, SensorDb};
//!
//! // 2 MB in, 2 MB long. The database sees a device of exactly that size and
//! // cannot address a byte outside it.
//! let region = Partition::new(flash, 0x0020_0000, 0x0020_0000)?;
//! let mut db: SensorDb<_, 256, 512> = SensorDb::new(region, 0, 512, 2)?;
//! ```
//!
//! An access outside the partition is [`PartitionError::OutOfBounds`] rather
//! than a write to whatever happens to live there — which is the whole point.
//! [`SensorDb::with_region`](crate::SensorDb::with_region) hands out a
//! `Partition` for the same reason.
//!
//! # Two constructors, neither of them async
//!
//! [`new`](Partition::new) validates against the *blocking*
//! `embedded_storage::nor_flash::NorFlash`; [`new_async`](Partition::new_async)
//! against `embedded_storage_async`'s. The suffix names the trait family whose
//! `ERASE_SIZE`, `WRITE_SIZE` and `capacity()` are being checked, not an
//! `async fn` — a driver typically implements one family or the other, and the
//! constants are what the alignment rules are read from.

use embedded_storage::nor_flash::{NorFlashError, NorFlashErrorKind};

use crate::error::Error;

/// A `NorFlash` view of `[base, base + len)` of an underlying device.
///
/// Offsets passed to the flash traits are **relative to `base`**, and the
/// reported [`capacity`](embedded_storage::nor_flash::ReadNorFlash::capacity) is
/// `len`. Alignment granularity, and every error the device itself raises, pass
/// through unchanged.
///
/// See the [module documentation](self) for why the two constructors exist.
pub struct Partition<F> {
    inner: F,
    base: u32,
    len: u32,
}

/// Failure of an access through a [`Partition`].
///
/// Converts into [`Error::Flash`] by way of
/// [`NorFlashError::kind`], so a `SensorDb` over a partition reports flash
/// errors exactly as it does over a bare driver.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PartitionError<E> {
    /// The access ran past the end of the partition.
    ///
    /// The partition is what turns this into an error instead of a write to
    /// whatever else lives on the chip.
    OutOfBounds,
    /// The access was not aligned to the device's read, write or erase
    /// granularity.
    NotAligned,
    /// The underlying device failed.
    Device(E),
}

impl<E: NorFlashError> NorFlashError for PartitionError<E> {
    fn kind(&self) -> NorFlashErrorKind {
        match self {
            Self::OutOfBounds => NorFlashErrorKind::OutOfBounds,
            Self::NotAligned => NorFlashErrorKind::NotAligned,
            Self::Device(e) => e.kind(),
        }
    }
}

impl<F> Partition<F> {
    /// First byte of the partition in the underlying device's address space.
    pub const fn base(&self) -> u32 {
        self.base
    }

    /// Length of the partition in bytes.
    pub const fn len(&self) -> u32 {
        self.len
    }

    /// Whether the partition is empty. Never true — a zero length is rejected
    /// at construction — but clippy asks for it wherever `len` exists.
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Byte after the last byte of the partition.
    pub const fn end(&self) -> u32 {
        self.base + self.len
    }

    /// Whether `addr`, an address in the *underlying* device's space, falls
    /// inside this partition.
    pub const fn contains(&self, addr: u32) -> bool {
        addr >= self.base && addr < self.end()
    }

    /// Borrow the underlying device.
    pub const fn inner(&self) -> &F {
        &self.inner
    }

    /// Borrow the underlying device mutably.
    ///
    /// This is the escape hatch out of the partition, and it is deliberately
    /// explicit: everything reached through here is addressed in the *device's*
    /// space, with no bound of any kind.
    pub const fn inner_mut(&mut self) -> &mut F {
        &mut self.inner
    }

    /// Consume the partition and return the underlying device.
    pub fn into_inner(self) -> F {
        self.inner
    }

    /// Bounds-check `[offset, offset + length)` and translate it into the
    /// underlying device's address space.
    fn translate<E>(
        &self,
        align: usize,
        offset: u32,
        length: usize,
    ) -> Result<u32, PartitionError<E>> {
        let end = (offset as u64)
            .checked_add(length as u64)
            .ok_or(PartitionError::OutOfBounds)?;
        if end > self.len as u64 {
            return Err(PartitionError::OutOfBounds);
        }
        if align > 1 && (!(offset as usize).is_multiple_of(align) || !length.is_multiple_of(align))
        {
            return Err(PartitionError::NotAligned);
        }
        // `base + len` was checked against the device's capacity at
        // construction, and `offset <= len`, so this cannot overflow.
        Ok(self.base + offset)
    }

    /// Bounds-check an erase range and translate it.
    fn translate_erase<E>(
        &self,
        erase_size: usize,
        from: u32,
        to: u32,
    ) -> Result<(u32, u32), PartitionError<E>> {
        if from > to || to > self.len {
            return Err(PartitionError::OutOfBounds);
        }
        let addr = self.translate(erase_size, from, (to - from) as usize)?;
        Ok((addr, addr + (to - from)))
    }

    /// Shared validation for both constructors.
    fn validate(
        base: u32,
        len: u32,
        capacity: usize,
        erase_size: usize,
        write_size: usize,
        read_size: usize,
    ) -> Result<(), Error> {
        if len == 0 || erase_size == 0 || write_size == 0 || read_size == 0 {
            return Err(Error::InvalidConfig);
        }
        // Erase alignment is the load-bearing one: a partition that starts
        // mid-sector could not erase its own first sector without erasing a
        // neighbour's data. Write and read granularity are checked too so that
        // a translated offset is aligned exactly when the caller's was.
        let aligned = |v: u32| {
            (v as usize).is_multiple_of(erase_size)
                && (v as usize).is_multiple_of(write_size)
                && (v as usize).is_multiple_of(read_size)
        };
        if !aligned(base) || !aligned(len) {
            return Err(Error::InvalidConfig);
        }
        let end = (base as u64)
            .checked_add(len as u64)
            .ok_or(Error::Overflow)?;
        if end > capacity as u64 {
            return Err(Error::InvalidConfig);
        }
        Ok(())
    }
}

impl<F> core::fmt::Debug for Partition<F> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Partition")
            .field("base", &self.base)
            .field("len", &self.len)
            .finish_non_exhaustive()
    }
}

#[cfg(feature = "defmt")]
impl<F> defmt::Format for Partition<F> {
    fn format(&self, f: defmt::Formatter) {
        defmt::write!(
            f,
            "Partition {{ base: {=u32}, len: {=u32} }}",
            self.base,
            self.len
        )
    }
}

impl<F: crate::spool::Removable> crate::spool::Removable for Partition<F> {
    fn is_present(&self) -> bool {
        self.inner.is_present()
    }
}

// =============================================================================
// Blocking
// =============================================================================

mod blocking_impl {
    use embedded_storage::nor_flash::{ErrorType, NorFlash, ReadNorFlash};

    use super::{Partition, PartitionError};
    use crate::error::Error;

    impl<F: NorFlash> Partition<F> {
        /// Create a partition covering `[base, base + len)` of `inner`.
        ///
        /// # Errors
        /// - `InvalidConfig` if `len` is zero, if `base` or `len` is not a
        ///   multiple of the device's erase, write and read granularity, or if
        ///   the range runs past the device's capacity
        /// - `Overflow` if `base + len` does not fit in `u32`
        pub fn new(inner: F, base: u32, len: u32) -> Result<Self, Error> {
            Self::validate(
                base,
                len,
                inner.capacity(),
                F::ERASE_SIZE,
                F::WRITE_SIZE,
                F::READ_SIZE,
            )?;
            Ok(Self { inner, base, len })
        }
    }

    impl<F: ErrorType> ErrorType for Partition<F> {
        type Error = PartitionError<F::Error>;
    }

    impl<F: ReadNorFlash> ReadNorFlash for Partition<F> {
        const READ_SIZE: usize = F::READ_SIZE;

        fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
            let addr = self.translate(F::READ_SIZE, offset, bytes.len())?;
            self.inner.read(addr, bytes).map_err(PartitionError::Device)
        }

        fn capacity(&self) -> usize {
            self.len as usize
        }
    }

    impl<F: NorFlash> NorFlash for Partition<F> {
        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> {
            let (from, to) = self.translate_erase(F::ERASE_SIZE, from, to)?;
            self.inner.erase(from, to).map_err(PartitionError::Device)
        }

        fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
            let addr = self.translate(F::WRITE_SIZE, offset, bytes.len())?;
            self.inner
                .write(addr, bytes)
                .map_err(PartitionError::Device)
        }
    }
}

// =============================================================================
// Async
// =============================================================================

#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
mod async_impl {
    use embedded_storage_async::nor_flash::{NorFlash, ReadNorFlash};

    use super::{Partition, PartitionError};
    use crate::error::Error;

    impl<F: NorFlash> Partition<F> {
        /// Create a partition over a device implementing the *async* flash
        /// traits.
        ///
        /// Not an `async fn` — see the [module documentation](super) for why the
        /// suffix is there. Validation is otherwise identical to
        /// [`new`](Partition::new).
        pub fn new_async(inner: F, base: u32, len: u32) -> Result<Self, Error> {
            Self::validate(
                base,
                len,
                inner.capacity(),
                F::ERASE_SIZE,
                F::WRITE_SIZE,
                F::READ_SIZE,
            )?;
            Ok(Self { inner, base, len })
        }
    }

    impl<F: ReadNorFlash> ReadNorFlash for Partition<F> {
        const READ_SIZE: usize = F::READ_SIZE;

        async fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
            let addr = self.translate(F::READ_SIZE, offset, bytes.len())?;
            self.inner
                .read(addr, bytes)
                .await
                .map_err(PartitionError::Device)
        }

        fn capacity(&self) -> usize {
            self.len as usize
        }
    }

    impl<F: NorFlash> NorFlash for Partition<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> {
            let (from, to) = self.translate_erase(F::ERASE_SIZE, from, to)?;
            self.inner
                .erase(from, to)
                .await
                .map_err(PartitionError::Device)
        }

        async fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
            let addr = self.translate(F::WRITE_SIZE, offset, bytes.len())?;
            self.inner
                .write(addr, bytes)
                .await
                .map_err(PartitionError::Device)
        }
    }
}