Skip to main content

sensor_db/
partition.rs

1//! [`Partition`] — a `NorFlash` view of a sub-range of a larger device.
2//!
3//! One flash chip usually holds more than one thing: firmware, a config store,
4//! and the sensor log. `Partition` is the ecosystem's answer to that — pure
5//! address arithmetic over somebody else's driver, knowing nothing about which
6//! driver it is:
7//!
8//! ```ignore
9//! use sensor_db::{Partition, SensorDb};
10//!
11//! // 2 MB in, 2 MB long. The database sees a device of exactly that size and
12//! // cannot address a byte outside it.
13//! let region = Partition::new(flash, 0x0020_0000, 0x0020_0000)?;
14//! let mut db: SensorDb<_, 256, 512> = SensorDb::new(region, 0, 512, 2)?;
15//! ```
16//!
17//! An access outside the partition is [`PartitionError::OutOfBounds`] rather
18//! than a write to whatever happens to live there — which is the whole point.
19//! [`SensorDb::with_region`](crate::SensorDb::with_region) hands out a
20//! `Partition` for the same reason.
21//!
22//! # Two constructors, neither of them async
23//!
24//! [`new`](Partition::new) validates against the *blocking*
25//! `embedded_storage::nor_flash::NorFlash`; [`new_async`](Partition::new_async)
26//! against `embedded_storage_async`'s. The suffix names the trait family whose
27//! `ERASE_SIZE`, `WRITE_SIZE` and `capacity()` are being checked, not an
28//! `async fn` — a driver typically implements one family or the other, and the
29//! constants are what the alignment rules are read from.
30
31use embedded_storage::nor_flash::{NorFlashError, NorFlashErrorKind};
32
33use crate::error::Error;
34
35/// A `NorFlash` view of `[base, base + len)` of an underlying device.
36///
37/// Offsets passed to the flash traits are **relative to `base`**, and the
38/// reported [`capacity`](embedded_storage::nor_flash::ReadNorFlash::capacity) is
39/// `len`. Alignment granularity, and every error the device itself raises, pass
40/// through unchanged.
41///
42/// See the [module documentation](self) for why the two constructors exist.
43pub struct Partition<F> {
44    inner: F,
45    base: u32,
46    len: u32,
47}
48
49/// Failure of an access through a [`Partition`].
50///
51/// Converts into [`Error::Flash`] by way of
52/// [`NorFlashError::kind`], so a `SensorDb` over a partition reports flash
53/// errors exactly as it does over a bare driver.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum PartitionError<E> {
56    /// The access ran past the end of the partition.
57    ///
58    /// The partition is what turns this into an error instead of a write to
59    /// whatever else lives on the chip.
60    OutOfBounds,
61    /// The access was not aligned to the device's read, write or erase
62    /// granularity.
63    NotAligned,
64    /// The underlying device failed.
65    Device(E),
66}
67
68impl<E: NorFlashError> NorFlashError for PartitionError<E> {
69    fn kind(&self) -> NorFlashErrorKind {
70        match self {
71            Self::OutOfBounds => NorFlashErrorKind::OutOfBounds,
72            Self::NotAligned => NorFlashErrorKind::NotAligned,
73            Self::Device(e) => e.kind(),
74        }
75    }
76}
77
78impl<F> Partition<F> {
79    /// First byte of the partition in the underlying device's address space.
80    pub const fn base(&self) -> u32 {
81        self.base
82    }
83
84    /// Length of the partition in bytes.
85    pub const fn len(&self) -> u32 {
86        self.len
87    }
88
89    /// Whether the partition is empty. Never true — a zero length is rejected
90    /// at construction — but clippy asks for it wherever `len` exists.
91    pub const fn is_empty(&self) -> bool {
92        self.len == 0
93    }
94
95    /// Byte after the last byte of the partition.
96    pub const fn end(&self) -> u32 {
97        self.base + self.len
98    }
99
100    /// Whether `addr`, an address in the *underlying* device's space, falls
101    /// inside this partition.
102    pub const fn contains(&self, addr: u32) -> bool {
103        addr >= self.base && addr < self.end()
104    }
105
106    /// Borrow the underlying device.
107    pub const fn inner(&self) -> &F {
108        &self.inner
109    }
110
111    /// Borrow the underlying device mutably.
112    ///
113    /// This is the escape hatch out of the partition, and it is deliberately
114    /// explicit: everything reached through here is addressed in the *device's*
115    /// space, with no bound of any kind.
116    pub const fn inner_mut(&mut self) -> &mut F {
117        &mut self.inner
118    }
119
120    /// Consume the partition and return the underlying device.
121    pub fn into_inner(self) -> F {
122        self.inner
123    }
124
125    /// Bounds-check `[offset, offset + length)` and translate it into the
126    /// underlying device's address space.
127    fn translate<E>(
128        &self,
129        align: usize,
130        offset: u32,
131        length: usize,
132    ) -> Result<u32, PartitionError<E>> {
133        let end = (offset as u64)
134            .checked_add(length as u64)
135            .ok_or(PartitionError::OutOfBounds)?;
136        if end > self.len as u64 {
137            return Err(PartitionError::OutOfBounds);
138        }
139        if align > 1 && (!(offset as usize).is_multiple_of(align) || !length.is_multiple_of(align))
140        {
141            return Err(PartitionError::NotAligned);
142        }
143        // `base + len` was checked against the device's capacity at
144        // construction, and `offset <= len`, so this cannot overflow.
145        Ok(self.base + offset)
146    }
147
148    /// Bounds-check an erase range and translate it.
149    fn translate_erase<E>(
150        &self,
151        erase_size: usize,
152        from: u32,
153        to: u32,
154    ) -> Result<(u32, u32), PartitionError<E>> {
155        if from > to || to > self.len {
156            return Err(PartitionError::OutOfBounds);
157        }
158        let addr = self.translate(erase_size, from, (to - from) as usize)?;
159        Ok((addr, addr + (to - from)))
160    }
161
162    /// Shared validation for both constructors.
163    fn validate(
164        base: u32,
165        len: u32,
166        capacity: usize,
167        erase_size: usize,
168        write_size: usize,
169        read_size: usize,
170    ) -> Result<(), Error> {
171        if len == 0 || erase_size == 0 || write_size == 0 || read_size == 0 {
172            return Err(Error::InvalidConfig);
173        }
174        // Erase alignment is the load-bearing one: a partition that starts
175        // mid-sector could not erase its own first sector without erasing a
176        // neighbour's data. Write and read granularity are checked too so that
177        // a translated offset is aligned exactly when the caller's was.
178        let aligned = |v: u32| {
179            (v as usize).is_multiple_of(erase_size)
180                && (v as usize).is_multiple_of(write_size)
181                && (v as usize).is_multiple_of(read_size)
182        };
183        if !aligned(base) || !aligned(len) {
184            return Err(Error::InvalidConfig);
185        }
186        let end = (base as u64)
187            .checked_add(len as u64)
188            .ok_or(Error::Overflow)?;
189        if end > capacity as u64 {
190            return Err(Error::InvalidConfig);
191        }
192        Ok(())
193    }
194}
195
196impl<F> core::fmt::Debug for Partition<F> {
197    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
198        f.debug_struct("Partition")
199            .field("base", &self.base)
200            .field("len", &self.len)
201            .finish_non_exhaustive()
202    }
203}
204
205#[cfg(feature = "defmt")]
206impl<F> defmt::Format for Partition<F> {
207    fn format(&self, f: defmt::Formatter) {
208        defmt::write!(
209            f,
210            "Partition {{ base: {=u32}, len: {=u32} }}",
211            self.base,
212            self.len
213        )
214    }
215}
216
217impl<F: crate::spool::Removable> crate::spool::Removable for Partition<F> {
218    fn is_present(&self) -> bool {
219        self.inner.is_present()
220    }
221}
222
223// =============================================================================
224// Blocking
225// =============================================================================
226
227mod blocking_impl {
228    use embedded_storage::nor_flash::{ErrorType, NorFlash, ReadNorFlash};
229
230    use super::{Partition, PartitionError};
231    use crate::error::Error;
232
233    impl<F: NorFlash> Partition<F> {
234        /// Create a partition covering `[base, base + len)` of `inner`.
235        ///
236        /// # Errors
237        /// - `InvalidConfig` if `len` is zero, if `base` or `len` is not a
238        ///   multiple of the device's erase, write and read granularity, or if
239        ///   the range runs past the device's capacity
240        /// - `Overflow` if `base + len` does not fit in `u32`
241        pub fn new(inner: F, base: u32, len: u32) -> Result<Self, Error> {
242            Self::validate(
243                base,
244                len,
245                inner.capacity(),
246                F::ERASE_SIZE,
247                F::WRITE_SIZE,
248                F::READ_SIZE,
249            )?;
250            Ok(Self { inner, base, len })
251        }
252    }
253
254    impl<F: ErrorType> ErrorType for Partition<F> {
255        type Error = PartitionError<F::Error>;
256    }
257
258    impl<F: ReadNorFlash> ReadNorFlash for Partition<F> {
259        const READ_SIZE: usize = F::READ_SIZE;
260
261        fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
262            let addr = self.translate(F::READ_SIZE, offset, bytes.len())?;
263            self.inner.read(addr, bytes).map_err(PartitionError::Device)
264        }
265
266        fn capacity(&self) -> usize {
267            self.len as usize
268        }
269    }
270
271    impl<F: NorFlash> NorFlash for Partition<F> {
272        const WRITE_SIZE: usize = F::WRITE_SIZE;
273        const ERASE_SIZE: usize = F::ERASE_SIZE;
274
275        fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
276            let (from, to) = self.translate_erase(F::ERASE_SIZE, from, to)?;
277            self.inner.erase(from, to).map_err(PartitionError::Device)
278        }
279
280        fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
281            let addr = self.translate(F::WRITE_SIZE, offset, bytes.len())?;
282            self.inner
283                .write(addr, bytes)
284                .map_err(PartitionError::Device)
285        }
286    }
287}
288
289// =============================================================================
290// Async
291// =============================================================================
292
293#[cfg(feature = "async")]
294#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
295mod async_impl {
296    use embedded_storage_async::nor_flash::{NorFlash, ReadNorFlash};
297
298    use super::{Partition, PartitionError};
299    use crate::error::Error;
300
301    impl<F: NorFlash> Partition<F> {
302        /// Create a partition over a device implementing the *async* flash
303        /// traits.
304        ///
305        /// Not an `async fn` — see the [module documentation](super) for why the
306        /// suffix is there. Validation is otherwise identical to
307        /// [`new`](Partition::new).
308        pub fn new_async(inner: F, base: u32, len: u32) -> Result<Self, Error> {
309            Self::validate(
310                base,
311                len,
312                inner.capacity(),
313                F::ERASE_SIZE,
314                F::WRITE_SIZE,
315                F::READ_SIZE,
316            )?;
317            Ok(Self { inner, base, len })
318        }
319    }
320
321    impl<F: ReadNorFlash> ReadNorFlash for Partition<F> {
322        const READ_SIZE: usize = F::READ_SIZE;
323
324        async fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
325            let addr = self.translate(F::READ_SIZE, offset, bytes.len())?;
326            self.inner
327                .read(addr, bytes)
328                .await
329                .map_err(PartitionError::Device)
330        }
331
332        fn capacity(&self) -> usize {
333            self.len as usize
334        }
335    }
336
337    impl<F: NorFlash> NorFlash for Partition<F> {
338        const WRITE_SIZE: usize = F::WRITE_SIZE;
339        const ERASE_SIZE: usize = F::ERASE_SIZE;
340
341        async fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
342            let (from, to) = self.translate_erase(F::ERASE_SIZE, from, to)?;
343            self.inner
344                .erase(from, to)
345                .await
346                .map_err(PartitionError::Device)
347        }
348
349        async fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
350            let addr = self.translate(F::WRITE_SIZE, offset, bytes.len())?;
351            self.inner
352                .write(addr, bytes)
353                .await
354                .map_err(PartitionError::Device)
355        }
356    }
357}