sensor_db/mock.rs
1//! Mock NOR flash implementation for testing.
2//!
3//! This module provides a [`MockFlash`] type that simulates NOR flash hardware
4//! for testing purposes. It requires the `std` feature to be enabled.
5//!
6//! # Example
7//!
8//! ```
9//! use sensor_db::mock::MockFlash;
10//! use sensor_db::SensorDb;
11//!
12//! const PAGE: usize = 256;
13//! const SECTOR: usize = 4096;
14//! const SECTORS: usize = 8;
15//!
16//! let flash = MockFlash::<PAGE, SECTOR>::new(SECTORS * SECTOR);
17//! let mut db: SensorDb<_, PAGE, SECTORS> = SensorDb::new(flash, 0, 8, 1).unwrap();
18//! db.format().unwrap();
19//! ```
20
21extern crate alloc;
22
23use alloc::vec;
24use alloc::vec::Vec;
25use core::fmt;
26use embedded_storage::nor_flash::{
27 ErrorType, NorFlash, NorFlashError, NorFlashErrorKind, ReadNorFlash,
28};
29
30/// Error type for the mock flash.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum MockFlashError {
33 /// Access was outside flash bounds.
34 OutOfBounds,
35 /// Address or size was not properly aligned.
36 NotAligned,
37 /// Attempted to write to a region that was not erased.
38 NotErased,
39 /// Simulated power loss during write.
40 PowerLoss,
41 /// The medium is not present (see [`RemovableFlash`]).
42 NotPresent,
43}
44
45impl NorFlashError for MockFlashError {
46 fn kind(&self) -> NorFlashErrorKind {
47 match self {
48 MockFlashError::OutOfBounds => NorFlashErrorKind::OutOfBounds,
49 MockFlashError::NotAligned => NorFlashErrorKind::NotAligned,
50 // Real drivers cannot distinguish these either: a yanked card and a
51 // write to a dirty page both surface as `Other`. Keeping the mock
52 // honest about that is the point — code above must not rely on the
53 // kind to detect removal.
54 MockFlashError::NotErased => NorFlashErrorKind::Other,
55 MockFlashError::PowerLoss => NorFlashErrorKind::Other,
56 MockFlashError::NotPresent => NorFlashErrorKind::Other,
57 }
58 }
59}
60
61impl fmt::Display for MockFlashError {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 match self {
64 MockFlashError::OutOfBounds => write!(f, "out of bounds"),
65 MockFlashError::NotAligned => write!(f, "not aligned"),
66 MockFlashError::NotErased => write!(f, "region not erased"),
67 MockFlashError::PowerLoss => write!(f, "simulated power loss"),
68 MockFlashError::NotPresent => write!(f, "medium not present"),
69 }
70 }
71}
72
73/// Behaviour when a simulated power loss occurs during a write.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum PowerLossMode {
76 /// The write fails cleanly -- no bytes are persisted.
77 Clean,
78 /// Only the first `n` bytes of the write are persisted (partial page write).
79 Partial(usize),
80}
81
82/// A snapshot of a [`MockFlash`]'s operation counters.
83///
84/// Subtracting two snapshots gives the cost of whatever happened between them,
85/// which is the portable and deterministic way to measure this crate: on real
86/// hardware an erase is 100 ms or more, a page write is microseconds, and a read
87/// is bus-bound, so the counts predict behaviour across parts in a way a
88/// desktop wall-clock number never can.
89///
90/// ```
91/// # use sensor_db::mock::MockFlash;
92/// # use sensor_db::{SensorDb, db::DbConfig};
93/// let mut db: SensorDb<MockFlash<256, 4096>, 256, 8> =
94/// SensorDb::new(MockFlash::new(8 * 4096), 0, 8, 1)?;
95/// db.format()?;
96///
97/// let before = db.driver_mut().ops();
98/// db.append(1, 0, &[0xAB])?;
99/// // A buffered append touches no flash at all.
100/// assert_eq!(db.driver_mut().ops() - before, Default::default());
101/// # Ok::<(), sensor_db::Error>(())
102/// ```
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
104pub struct FlashOps {
105 /// Read operations.
106 pub reads: u64,
107 /// Bytes read. The number that matters for mount cost on a real bus.
108 pub read_bytes: u64,
109 /// Page-program operations, successful or torn.
110 pub writes: u64,
111 /// Sector-erase operations, successful or torn. The expensive one.
112 pub erases: u64,
113}
114
115impl core::ops::Sub for FlashOps {
116 type Output = Self;
117
118 /// The cost between two snapshots.
119 ///
120 /// Saturating, so an accidentally reversed subtraction reads as zero rather
121 /// than as an enormous count.
122 fn sub(self, earlier: Self) -> Self {
123 Self {
124 reads: self.reads.saturating_sub(earlier.reads),
125 read_bytes: self.read_bytes.saturating_sub(earlier.read_bytes),
126 writes: self.writes.saturating_sub(earlier.writes),
127 erases: self.erases.saturating_sub(earlier.erases),
128 }
129 }
130}
131
132/// Simulated NOR flash for testing.
133///
134/// This type simulates a NOR flash chip with configurable page and sector sizes.
135/// It enforces the same constraints as real hardware:
136/// - Writes must be page-aligned
137/// - Erased regions must be 0xFF before writing
138/// - Can only clear bits (1 -> 0), not set them
139///
140/// # Power-loss simulation
141///
142/// Use [`set_power_loss_after`](MockFlash::set_power_loss_after) to configure
143/// deterministic power-loss injection. After the specified number of writes,
144/// subsequent writes will fail according to the chosen [`PowerLossMode`].
145///
146/// # Type Parameters
147/// - `PAGE_SIZE`: Size of a write page in bytes
148/// - `SECTOR_SIZE`: Size of an erase sector in bytes
149#[derive(Clone)]
150pub struct MockFlash<const PAGE_SIZE: usize, const SECTOR_SIZE: usize> {
151 data: Vec<u8>,
152 /// Track erase counts per sector for wear analysis.
153 pub erase_counts: Vec<u32>,
154 /// Total number of write operations.
155 pub write_count: u64,
156 /// Total number of erase operations, successful or torn.
157 pub erase_ops: u64,
158 /// Total number of read operations.
159 pub read_ops: u64,
160 /// Total bytes read.
161 ///
162 /// The honest measure of mount cost on a real part: what a `Full` mount
163 /// avoids by reading a sealed sector's footer is *bytes over the bus*, not
164 /// operations. Counted here so the saving can be asserted rather than
165 /// claimed.
166 pub read_bytes: u64,
167 /// If set, writes will fail after this many write operations.
168 fail_after_n_writes: Option<u64>,
169 /// How to simulate power loss.
170 power_loss_mode: PowerLossMode,
171 /// If set, the erase at this index is torn, leaving only the first `usize`
172 /// bytes of the range erased.
173 tear_erase_after: Option<(u64, usize)>,
174 /// Whether power loss has been triggered.
175 power_lost: bool,
176}
177
178impl<const PAGE_SIZE: usize, const SECTOR_SIZE: usize> MockFlash<PAGE_SIZE, SECTOR_SIZE> {
179 /// Create a new mock flash of `size` bytes.
180 ///
181 /// # Panics
182 /// Panics if `size` is not a multiple of `SECTOR_SIZE`.
183 pub fn new(size: usize) -> Self {
184 assert!(
185 size.is_multiple_of(SECTOR_SIZE),
186 "size must be a multiple of SECTOR_SIZE"
187 );
188 let sectors = size / SECTOR_SIZE;
189 Self {
190 data: vec![0xFF; size],
191 erase_counts: vec![0; sectors],
192 write_count: 0,
193 erase_ops: 0,
194 read_ops: 0,
195 read_bytes: 0,
196 fail_after_n_writes: None,
197 power_loss_mode: PowerLossMode::Clean,
198 tear_erase_after: None,
199 power_lost: false,
200 }
201 }
202
203 /// Configure deterministic power-loss injection.
204 ///
205 /// After `n` successful write operations (counted from creation, not from this call),
206 /// all subsequent writes will fail according to the specified `mode`.
207 ///
208 /// # Arguments
209 /// - `n`: Total write count threshold. The *n*-th write and all following writes will fail.
210 /// - `mode`: How to simulate the power loss (clean fail vs. partial write).
211 pub fn set_power_loss_after(&mut self, n: u64, mode: PowerLossMode) {
212 self.fail_after_n_writes = Some(n);
213 self.power_loss_mode = mode;
214 self.power_lost = false;
215 }
216
217 /// Tear the `n`-th erase operation, leaving only its first `bytes` erased.
218 ///
219 /// A real erase is a long, progressive operation: cells go from 0 to 1 over
220 /// milliseconds, low addresses first. Losing power part-way therefore leaves
221 /// the head of the sector erased and the tail holding whatever was there
222 /// before — including a stale sector header body under a freshly blank magic.
223 ///
224 /// The erase returns an error, and the erase *counter* for the affected
225 /// sectors is not advanced: the sector is not, in any useful sense, erased.
226 ///
227 /// # Arguments
228 /// - `n`: erase index, counted from creation. The *n*-th erase is the one torn.
229 /// - `bytes`: how many bytes of the requested range actually reached 0xFF.
230 pub fn set_erase_loss_after(&mut self, n: u64, bytes: usize) {
231 self.tear_erase_after = Some((n, bytes));
232 self.power_lost = false;
233 }
234
235 /// Returns `true` if a simulated power loss has been triggered.
236 pub fn is_power_lost(&self) -> bool {
237 self.power_lost
238 }
239
240 /// Clear any power-loss configuration, allowing writes and erases to succeed again.
241 pub fn clear_power_loss(&mut self) {
242 self.fail_after_n_writes = None;
243 self.tear_erase_after = None;
244 self.power_lost = false;
245 }
246
247 /// Total erase operations across all sectors.
248 pub fn total_erases(&self) -> u64 {
249 self.erase_counts.iter().map(|c| *c as u64).sum()
250 }
251
252 /// Snapshot the operation counters.
253 ///
254 /// Take one before an operation and one after, and subtract: see
255 /// [`FlashOps`].
256 pub fn ops(&self) -> FlashOps {
257 FlashOps {
258 reads: self.read_ops,
259 read_bytes: self.read_bytes,
260 writes: self.write_count,
261 erases: self.erase_ops,
262 }
263 }
264
265 /// Dump a range of flash as bytes (for debugging).
266 pub fn hex_dump(&self, offset: usize, len: usize) -> Vec<u8> {
267 self.data[offset..offset + len].to_vec()
268 }
269}
270
271impl<const PAGE_SIZE: usize, const SECTOR_SIZE: usize> ErrorType
272 for MockFlash<PAGE_SIZE, SECTOR_SIZE>
273{
274 type Error = MockFlashError;
275}
276
277impl<const PAGE_SIZE: usize, const SECTOR_SIZE: usize> ReadNorFlash
278 for MockFlash<PAGE_SIZE, SECTOR_SIZE>
279{
280 const READ_SIZE: usize = 1;
281
282 fn read(&mut self, offset: u32, buf: &mut [u8]) -> Result<(), Self::Error> {
283 let start = offset as usize;
284 let end = start + buf.len();
285 if end > self.data.len() {
286 return Err(MockFlashError::OutOfBounds);
287 }
288 buf.copy_from_slice(&self.data[start..end]);
289 self.read_ops += 1;
290 self.read_bytes += buf.len() as u64;
291 Ok(())
292 }
293
294 fn capacity(&self) -> usize {
295 self.data.len()
296 }
297}
298
299impl<const PAGE_SIZE: usize, const SECTOR_SIZE: usize> NorFlash
300 for MockFlash<PAGE_SIZE, SECTOR_SIZE>
301{
302 const WRITE_SIZE: usize = PAGE_SIZE;
303 const ERASE_SIZE: usize = SECTOR_SIZE;
304
305 fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
306 let from = from as usize;
307 let to = to as usize;
308 if !from.is_multiple_of(SECTOR_SIZE) || !to.is_multiple_of(SECTOR_SIZE) {
309 return Err(MockFlashError::NotAligned);
310 }
311 if to > self.data.len() {
312 return Err(MockFlashError::OutOfBounds);
313 }
314
315 if let Some((threshold, bytes)) = self.tear_erase_after
316 && self.erase_ops >= threshold
317 {
318 self.power_lost = true;
319 self.erase_ops += 1;
320 let stopped_at = (from + bytes).min(to);
321 self.data[from..stopped_at].fill(0xFF);
322 return Err(MockFlashError::PowerLoss);
323 }
324
325 self.data[from..to].fill(0xFF);
326 self.erase_ops += 1;
327 // Track erases
328 let sector_start = from / SECTOR_SIZE;
329 let sector_end = to / SECTOR_SIZE;
330 for s in sector_start..sector_end {
331 self.erase_counts[s] += 1;
332 }
333 Ok(())
334 }
335
336 fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
337 let offset_usize = offset as usize;
338 if !offset_usize.is_multiple_of(PAGE_SIZE) {
339 return Err(MockFlashError::NotAligned);
340 }
341 if !bytes.len().is_multiple_of(PAGE_SIZE) {
342 return Err(MockFlashError::NotAligned);
343 }
344 if offset_usize + bytes.len() > self.data.len() {
345 return Err(MockFlashError::OutOfBounds);
346 }
347
348 // Check for power-loss injection
349 if let Some(threshold) = self.fail_after_n_writes
350 && self.write_count >= threshold
351 {
352 self.power_lost = true;
353 match self.power_loss_mode {
354 PowerLossMode::Clean => {
355 // Write fails cleanly, nothing persisted
356 return Err(MockFlashError::PowerLoss);
357 }
358 PowerLossMode::Partial(n) => {
359 // Persist only the first `n` bytes (applying NOR constraints)
360 let to_write = n.min(bytes.len());
361 for (dst, src) in self.data[offset_usize..offset_usize + to_write]
362 .iter_mut()
363 .zip(&bytes[..to_write])
364 {
365 // NOR: can only clear bits
366 *dst &= src;
367 }
368 self.write_count += 1;
369 return Err(MockFlashError::PowerLoss);
370 }
371 }
372 }
373
374 // NOR flash: can only clear bits (1 -> 0). Verify constraint.
375 for (i, &byte) in bytes.iter().enumerate() {
376 let existing = self.data[offset_usize + i];
377 if existing & byte != byte {
378 return Err(MockFlashError::NotErased);
379 }
380 }
381 self.data[offset_usize..offset_usize + bytes.len()].copy_from_slice(bytes);
382 self.write_count += 1;
383 Ok(())
384 }
385}
386
387// =============================================================================
388// RemovableFlash — a medium that can be pulled out
389// =============================================================================
390
391/// Test double for removable media: any flash that can be made absent.
392///
393/// Wraps an inner flash and gates every operation on a presence flag. While
394/// absent, **reads fail too**, not just writes — a card yanked between writing a
395/// spool intent record and reading the next payload must exercise both paths.
396///
397/// The inner flash is retained while absent, so [`insert`](Self::insert) restores
398/// exactly the bytes that were there before, and [`into_inner`](Self::into_inner)
399/// models carrying the card to a computer.
400///
401/// # Example
402///
403/// ```
404/// use sensor_db::mock::{MockFlash, RemovableFlash};
405///
406/// let mut card = RemovableFlash::new(MockFlash::<256, 4096>::new(8 * 4096));
407/// assert!(card.is_present());
408/// card.remove();
409/// assert!(!card.is_present());
410/// card.insert();
411/// ```
412#[derive(Clone)]
413pub struct RemovableFlash<F> {
414 inner: F,
415 present: bool,
416 yank_after_writes: Option<u64>,
417 writes: u64,
418}
419
420impl<F> RemovableFlash<F> {
421 /// Wrap a flash device. The medium starts out present.
422 pub fn new(inner: F) -> Self {
423 Self {
424 inner,
425 present: true,
426 yank_after_writes: None,
427 writes: 0,
428 }
429 }
430
431 /// Make the medium present again, with its contents intact.
432 pub fn insert(&mut self) {
433 self.present = true;
434 self.yank_after_writes = None;
435 }
436
437 /// Remove the medium cleanly. Subsequent reads and writes fail with
438 /// [`MockFlashError::NotPresent`].
439 pub fn remove(&mut self) {
440 self.present = false;
441 self.yank_after_writes = None;
442 }
443
444 /// Become absent after `n` further writes — a surprise yank mid-batch.
445 ///
446 /// The `n`-th write from now still succeeds; the one after it fails. Use
447 /// this to land a removal in the middle of a multi-page operation.
448 pub fn yank_after(&mut self, n: u64) {
449 self.yank_after_writes = Some(self.writes + n);
450 }
451
452 /// Whether the medium is currently present.
453 pub fn is_present(&self) -> bool {
454 self.present
455 }
456
457 /// Total writes attempted while present.
458 pub fn write_count(&self) -> u64 {
459 self.writes
460 }
461
462 /// Borrow the wrapped flash, ignoring presence.
463 pub fn inner(&self) -> &F {
464 &self.inner
465 }
466
467 /// Mutably borrow the wrapped flash, ignoring presence.
468 pub fn inner_mut(&mut self) -> &mut F {
469 &mut self.inner
470 }
471
472 /// Consume the wrapper and return the flash — "carry the card to the laptop".
473 pub fn into_inner(self) -> F {
474 self.inner
475 }
476
477 /// Check presence and account for a pending yank. Called before each write.
478 fn admit_write(&mut self) -> Result<(), MockFlashError> {
479 if !self.present {
480 return Err(MockFlashError::NotPresent);
481 }
482 if let Some(threshold) = self.yank_after_writes
483 && self.writes >= threshold
484 {
485 self.present = false;
486 return Err(MockFlashError::NotPresent);
487 }
488 self.writes += 1;
489 Ok(())
490 }
491
492 fn admit_read(&self) -> Result<(), MockFlashError> {
493 if self.present {
494 Ok(())
495 } else {
496 Err(MockFlashError::NotPresent)
497 }
498 }
499}
500
501impl<F> crate::spool::Removable for RemovableFlash<F> {
502 fn is_present(&self) -> bool {
503 self.present
504 }
505}
506
507impl<F> ErrorType for RemovableFlash<F> {
508 type Error = MockFlashError;
509}
510
511impl<F> ReadNorFlash for RemovableFlash<F>
512where
513 F: ReadNorFlash<Error = MockFlashError>,
514{
515 const READ_SIZE: usize = 1;
516
517 fn read(&mut self, offset: u32, buf: &mut [u8]) -> Result<(), Self::Error> {
518 self.admit_read()?;
519 self.inner.read(offset, buf)
520 }
521
522 fn capacity(&self) -> usize {
523 self.inner.capacity()
524 }
525}
526
527impl<F> NorFlash for RemovableFlash<F>
528where
529 F: NorFlash<Error = MockFlashError>,
530{
531 const WRITE_SIZE: usize = F::WRITE_SIZE;
532 const ERASE_SIZE: usize = F::ERASE_SIZE;
533
534 fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
535 self.admit_write()?;
536 self.inner.erase(from, to)
537 }
538
539 fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
540 self.admit_write()?;
541 self.inner.write(offset, bytes)
542 }
543}
544
545// =============================================================================
546// Async mocks
547// =============================================================================
548
549/// Thin async adapter over any sync flash, implementing the async flash traits.
550///
551/// The wrapped devices here are in-memory, so the "async" operations complete
552/// immediately — they delegate straight to the sync implementation. This exists
553/// so async code can be exercised without an executor or real hardware.
554///
555/// Page and sector geometry is inherited from the wrapped device, so this
556/// composes with [`RemovableFlash`] without restating the constants.
557#[cfg(feature = "async")]
558#[derive(Clone)]
559pub struct AsyncFlash<F> {
560 inner: F,
561}
562
563/// An async [`MockFlash`] of the given geometry.
564#[cfg(feature = "async")]
565pub type MockFlashAsync<const PAGE_SIZE: usize, const SECTOR_SIZE: usize> =
566 AsyncFlash<MockFlash<PAGE_SIZE, SECTOR_SIZE>>;
567
568#[cfg(feature = "async")]
569impl<const PAGE_SIZE: usize, const SECTOR_SIZE: usize>
570 AsyncFlash<MockFlash<PAGE_SIZE, SECTOR_SIZE>>
571{
572 /// Create a new async mock flash of `size` bytes.
573 ///
574 /// # Panics
575 /// Panics if `size` is not a multiple of `SECTOR_SIZE`.
576 pub fn new(size: usize) -> Self {
577 Self {
578 inner: MockFlash::<PAGE_SIZE, SECTOR_SIZE>::new(size),
579 }
580 }
581}
582
583#[cfg(feature = "async")]
584impl<F> AsyncFlash<F> {
585 /// Wrap an existing flash device in the async adapter.
586 pub fn wrap(inner: F) -> Self {
587 Self { inner }
588 }
589
590 /// Borrow the wrapped device (e.g. to configure power-loss injection).
591 pub fn inner(&self) -> &F {
592 &self.inner
593 }
594
595 /// Mutably borrow the wrapped device.
596 pub fn inner_mut(&mut self) -> &mut F {
597 &mut self.inner
598 }
599
600 /// Consume the adapter and return the wrapped device.
601 pub fn into_inner(self) -> F {
602 self.inner
603 }
604}
605
606#[cfg(feature = "async")]
607impl<F: ErrorType> embedded_storage_async::nor_flash::ErrorType for AsyncFlash<F> {
608 type Error = F::Error;
609}
610
611#[cfg(feature = "async")]
612impl<F: ReadNorFlash> embedded_storage_async::nor_flash::ReadNorFlash for AsyncFlash<F> {
613 const READ_SIZE: usize = F::READ_SIZE;
614
615 async fn read(&mut self, offset: u32, buf: &mut [u8]) -> Result<(), Self::Error> {
616 self.inner.read(offset, buf)
617 }
618
619 fn capacity(&self) -> usize {
620 self.inner.capacity()
621 }
622}
623
624#[cfg(feature = "async")]
625impl<F: NorFlash> embedded_storage_async::nor_flash::NorFlash for AsyncFlash<F> {
626 const WRITE_SIZE: usize = F::WRITE_SIZE;
627 const ERASE_SIZE: usize = F::ERASE_SIZE;
628
629 async fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
630 self.inner.erase(from, to)
631 }
632
633 async fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
634 self.inner.write(offset, bytes)
635 }
636}
637
638#[cfg(feature = "async")]
639impl<F: crate::spool::Removable> crate::spool::Removable for AsyncFlash<F> {
640 fn is_present(&self) -> bool {
641 self.inner.is_present()
642 }
643}
644
645/// Drive a future to completion on the current thread, for tests and examples.
646///
647/// This is a deliberately minimal executor: it polls once and panics if the
648/// future is not immediately ready. That is correct for the in-memory mocks
649/// above, whose "async" operations never actually yield, and it turns an
650/// accidental real await into a loud failure rather than a hang.
651///
652/// # Panics
653/// Panics if the future returns `Poll::Pending`.
654#[cfg(feature = "async")]
655#[allow(unsafe_code, clippy::never_loop)]
656pub fn block_on<T>(fut: impl core::future::Future<Output = T>) -> T {
657 use core::pin::pin;
658 use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
659
660 fn dummy_raw_waker() -> RawWaker {
661 fn no_op(_: *const ()) {}
662 fn clone(data: *const ()) -> RawWaker {
663 RawWaker::new(data, &VTABLE)
664 }
665 const VTABLE: RawWakerVTable = RawWakerVTable::new(clone, no_op, no_op, no_op);
666 RawWaker::new(core::ptr::null(), &VTABLE)
667 }
668
669 // SAFETY: The RawWaker vtable functions are valid no-ops, and the waker is
670 // only used within this function's scope for polling.
671 let waker = unsafe { Waker::from_raw(dummy_raw_waker()) };
672 let mut cx = Context::from_waker(&waker);
673 let mut fut = pin!(fut);
674
675 loop {
676 match fut.as_mut().poll(&mut cx) {
677 Poll::Ready(val) => return val,
678 Poll::Pending => panic!("async operation returned Pending in sync mock"),
679 }
680 }
681}