sensor-db 0.1.0

Append-only sensor database for NOR flash on embedded devices
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
//! Mock NOR flash implementation for testing.
//!
//! This module provides a [`MockFlash`] type that simulates NOR flash hardware
//! for testing purposes. It requires the `std` feature to be enabled.
//!
//! # Example
//!
//! ```
//! use sensor_db::mock::MockFlash;
//! use sensor_db::SensorDb;
//!
//! const PAGE: usize = 256;
//! const SECTOR: usize = 4096;
//! const SECTORS: usize = 8;
//!
//! let flash = MockFlash::<PAGE, SECTOR>::new(SECTORS * SECTOR);
//! let mut db: SensorDb<_, PAGE, SECTORS> = SensorDb::new(flash, 0, 8, 1).unwrap();
//! db.format().unwrap();
//! ```

extern crate alloc;

use alloc::vec;
use alloc::vec::Vec;
use core::fmt;
use embedded_storage::nor_flash::{
    ErrorType, NorFlash, NorFlashError, NorFlashErrorKind, ReadNorFlash,
};

/// Error type for the mock flash.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MockFlashError {
    /// Access was outside flash bounds.
    OutOfBounds,
    /// Address or size was not properly aligned.
    NotAligned,
    /// Attempted to write to a region that was not erased.
    NotErased,
    /// Simulated power loss during write.
    PowerLoss,
    /// The medium is not present (see [`RemovableFlash`]).
    NotPresent,
}

impl NorFlashError for MockFlashError {
    fn kind(&self) -> NorFlashErrorKind {
        match self {
            MockFlashError::OutOfBounds => NorFlashErrorKind::OutOfBounds,
            MockFlashError::NotAligned => NorFlashErrorKind::NotAligned,
            // Real drivers cannot distinguish these either: a yanked card and a
            // write to a dirty page both surface as `Other`. Keeping the mock
            // honest about that is the point — code above must not rely on the
            // kind to detect removal.
            MockFlashError::NotErased => NorFlashErrorKind::Other,
            MockFlashError::PowerLoss => NorFlashErrorKind::Other,
            MockFlashError::NotPresent => NorFlashErrorKind::Other,
        }
    }
}

impl fmt::Display for MockFlashError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MockFlashError::OutOfBounds => write!(f, "out of bounds"),
            MockFlashError::NotAligned => write!(f, "not aligned"),
            MockFlashError::NotErased => write!(f, "region not erased"),
            MockFlashError::PowerLoss => write!(f, "simulated power loss"),
            MockFlashError::NotPresent => write!(f, "medium not present"),
        }
    }
}

/// Behaviour when a simulated power loss occurs during a write.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PowerLossMode {
    /// The write fails cleanly -- no bytes are persisted.
    Clean,
    /// Only the first `n` bytes of the write are persisted (partial page write).
    Partial(usize),
}

/// A snapshot of a [`MockFlash`]'s operation counters.
///
/// Subtracting two snapshots gives the cost of whatever happened between them,
/// which is the portable and deterministic way to measure this crate: on real
/// hardware an erase is 100 ms or more, a page write is microseconds, and a read
/// is bus-bound, so the counts predict behaviour across parts in a way a
/// desktop wall-clock number never can.
///
/// ```
/// # use sensor_db::mock::MockFlash;
/// # use sensor_db::{SensorDb, db::DbConfig};
/// let mut db: SensorDb<MockFlash<256, 4096>, 256, 8> =
///     SensorDb::new(MockFlash::new(8 * 4096), 0, 8, 1)?;
/// db.format()?;
///
/// let before = db.driver_mut().ops();
/// db.append(1, 0, &[0xAB])?;
/// // A buffered append touches no flash at all.
/// assert_eq!(db.driver_mut().ops() - before, Default::default());
/// # Ok::<(), sensor_db::Error>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct FlashOps {
    /// Read operations.
    pub reads: u64,
    /// Bytes read. The number that matters for mount cost on a real bus.
    pub read_bytes: u64,
    /// Page-program operations, successful or torn.
    pub writes: u64,
    /// Sector-erase operations, successful or torn. The expensive one.
    pub erases: u64,
}

impl core::ops::Sub for FlashOps {
    type Output = Self;

    /// The cost between two snapshots.
    ///
    /// Saturating, so an accidentally reversed subtraction reads as zero rather
    /// than as an enormous count.
    fn sub(self, earlier: Self) -> Self {
        Self {
            reads: self.reads.saturating_sub(earlier.reads),
            read_bytes: self.read_bytes.saturating_sub(earlier.read_bytes),
            writes: self.writes.saturating_sub(earlier.writes),
            erases: self.erases.saturating_sub(earlier.erases),
        }
    }
}

/// Simulated NOR flash for testing.
///
/// This type simulates a NOR flash chip with configurable page and sector sizes.
/// It enforces the same constraints as real hardware:
/// - Writes must be page-aligned
/// - Erased regions must be 0xFF before writing
/// - Can only clear bits (1 -> 0), not set them
///
/// # Power-loss simulation
///
/// Use [`set_power_loss_after`](MockFlash::set_power_loss_after) to configure
/// deterministic power-loss injection. After the specified number of writes,
/// subsequent writes will fail according to the chosen [`PowerLossMode`].
///
/// # Type Parameters
/// - `PAGE_SIZE`: Size of a write page in bytes
/// - `SECTOR_SIZE`: Size of an erase sector in bytes
#[derive(Clone)]
pub struct MockFlash<const PAGE_SIZE: usize, const SECTOR_SIZE: usize> {
    data: Vec<u8>,
    /// Track erase counts per sector for wear analysis.
    pub erase_counts: Vec<u32>,
    /// Total number of write operations.
    pub write_count: u64,
    /// Total number of erase operations, successful or torn.
    pub erase_ops: u64,
    /// Total number of read operations.
    pub read_ops: u64,
    /// Total bytes read.
    ///
    /// The honest measure of mount cost on a real part: what a `Full` mount
    /// avoids by reading a sealed sector's footer is *bytes over the bus*, not
    /// operations. Counted here so the saving can be asserted rather than
    /// claimed.
    pub read_bytes: u64,
    /// If set, writes will fail after this many write operations.
    fail_after_n_writes: Option<u64>,
    /// How to simulate power loss.
    power_loss_mode: PowerLossMode,
    /// If set, the erase at this index is torn, leaving only the first `usize`
    /// bytes of the range erased.
    tear_erase_after: Option<(u64, usize)>,
    /// Whether power loss has been triggered.
    power_lost: bool,
}

impl<const PAGE_SIZE: usize, const SECTOR_SIZE: usize> MockFlash<PAGE_SIZE, SECTOR_SIZE> {
    /// Create a new mock flash of `size` bytes.
    ///
    /// # Panics
    /// Panics if `size` is not a multiple of `SECTOR_SIZE`.
    pub fn new(size: usize) -> Self {
        assert!(
            size.is_multiple_of(SECTOR_SIZE),
            "size must be a multiple of SECTOR_SIZE"
        );
        let sectors = size / SECTOR_SIZE;
        Self {
            data: vec![0xFF; size],
            erase_counts: vec![0; sectors],
            write_count: 0,
            erase_ops: 0,
            read_ops: 0,
            read_bytes: 0,
            fail_after_n_writes: None,
            power_loss_mode: PowerLossMode::Clean,
            tear_erase_after: None,
            power_lost: false,
        }
    }

    /// Configure deterministic power-loss injection.
    ///
    /// After `n` successful write operations (counted from creation, not from this call),
    /// all subsequent writes will fail according to the specified `mode`.
    ///
    /// # Arguments
    /// - `n`: Total write count threshold. The *n*-th write and all following writes will fail.
    /// - `mode`: How to simulate the power loss (clean fail vs. partial write).
    pub fn set_power_loss_after(&mut self, n: u64, mode: PowerLossMode) {
        self.fail_after_n_writes = Some(n);
        self.power_loss_mode = mode;
        self.power_lost = false;
    }

    /// Tear the `n`-th erase operation, leaving only its first `bytes` erased.
    ///
    /// A real erase is a long, progressive operation: cells go from 0 to 1 over
    /// milliseconds, low addresses first. Losing power part-way therefore leaves
    /// the head of the sector erased and the tail holding whatever was there
    /// before — including a stale sector header body under a freshly blank magic.
    ///
    /// The erase returns an error, and the erase *counter* for the affected
    /// sectors is not advanced: the sector is not, in any useful sense, erased.
    ///
    /// # Arguments
    /// - `n`: erase index, counted from creation. The *n*-th erase is the one torn.
    /// - `bytes`: how many bytes of the requested range actually reached 0xFF.
    pub fn set_erase_loss_after(&mut self, n: u64, bytes: usize) {
        self.tear_erase_after = Some((n, bytes));
        self.power_lost = false;
    }

    /// Returns `true` if a simulated power loss has been triggered.
    pub fn is_power_lost(&self) -> bool {
        self.power_lost
    }

    /// Clear any power-loss configuration, allowing writes and erases to succeed again.
    pub fn clear_power_loss(&mut self) {
        self.fail_after_n_writes = None;
        self.tear_erase_after = None;
        self.power_lost = false;
    }

    /// Total erase operations across all sectors.
    pub fn total_erases(&self) -> u64 {
        self.erase_counts.iter().map(|c| *c as u64).sum()
    }

    /// Snapshot the operation counters.
    ///
    /// Take one before an operation and one after, and subtract: see
    /// [`FlashOps`].
    pub fn ops(&self) -> FlashOps {
        FlashOps {
            reads: self.read_ops,
            read_bytes: self.read_bytes,
            writes: self.write_count,
            erases: self.erase_ops,
        }
    }

    /// Dump a range of flash as bytes (for debugging).
    pub fn hex_dump(&self, offset: usize, len: usize) -> Vec<u8> {
        self.data[offset..offset + len].to_vec()
    }
}

impl<const PAGE_SIZE: usize, const SECTOR_SIZE: usize> ErrorType
    for MockFlash<PAGE_SIZE, SECTOR_SIZE>
{
    type Error = MockFlashError;
}

impl<const PAGE_SIZE: usize, const SECTOR_SIZE: usize> ReadNorFlash
    for MockFlash<PAGE_SIZE, SECTOR_SIZE>
{
    const READ_SIZE: usize = 1;

    fn read(&mut self, offset: u32, buf: &mut [u8]) -> Result<(), Self::Error> {
        let start = offset as usize;
        let end = start + buf.len();
        if end > self.data.len() {
            return Err(MockFlashError::OutOfBounds);
        }
        buf.copy_from_slice(&self.data[start..end]);
        self.read_ops += 1;
        self.read_bytes += buf.len() as u64;
        Ok(())
    }

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

impl<const PAGE_SIZE: usize, const SECTOR_SIZE: usize> NorFlash
    for MockFlash<PAGE_SIZE, SECTOR_SIZE>
{
    const WRITE_SIZE: usize = PAGE_SIZE;
    const ERASE_SIZE: usize = SECTOR_SIZE;

    fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
        let from = from as usize;
        let to = to as usize;
        if !from.is_multiple_of(SECTOR_SIZE) || !to.is_multiple_of(SECTOR_SIZE) {
            return Err(MockFlashError::NotAligned);
        }
        if to > self.data.len() {
            return Err(MockFlashError::OutOfBounds);
        }

        if let Some((threshold, bytes)) = self.tear_erase_after
            && self.erase_ops >= threshold
        {
            self.power_lost = true;
            self.erase_ops += 1;
            let stopped_at = (from + bytes).min(to);
            self.data[from..stopped_at].fill(0xFF);
            return Err(MockFlashError::PowerLoss);
        }

        self.data[from..to].fill(0xFF);
        self.erase_ops += 1;
        // Track erases
        let sector_start = from / SECTOR_SIZE;
        let sector_end = to / SECTOR_SIZE;
        for s in sector_start..sector_end {
            self.erase_counts[s] += 1;
        }
        Ok(())
    }

    fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
        let offset_usize = offset as usize;
        if !offset_usize.is_multiple_of(PAGE_SIZE) {
            return Err(MockFlashError::NotAligned);
        }
        if !bytes.len().is_multiple_of(PAGE_SIZE) {
            return Err(MockFlashError::NotAligned);
        }
        if offset_usize + bytes.len() > self.data.len() {
            return Err(MockFlashError::OutOfBounds);
        }

        // Check for power-loss injection
        if let Some(threshold) = self.fail_after_n_writes
            && self.write_count >= threshold
        {
            self.power_lost = true;
            match self.power_loss_mode {
                PowerLossMode::Clean => {
                    // Write fails cleanly, nothing persisted
                    return Err(MockFlashError::PowerLoss);
                }
                PowerLossMode::Partial(n) => {
                    // Persist only the first `n` bytes (applying NOR constraints)
                    let to_write = n.min(bytes.len());
                    for (dst, src) in self.data[offset_usize..offset_usize + to_write]
                        .iter_mut()
                        .zip(&bytes[..to_write])
                    {
                        // NOR: can only clear bits
                        *dst &= src;
                    }
                    self.write_count += 1;
                    return Err(MockFlashError::PowerLoss);
                }
            }
        }

        // NOR flash: can only clear bits (1 -> 0). Verify constraint.
        for (i, &byte) in bytes.iter().enumerate() {
            let existing = self.data[offset_usize + i];
            if existing & byte != byte {
                return Err(MockFlashError::NotErased);
            }
        }
        self.data[offset_usize..offset_usize + bytes.len()].copy_from_slice(bytes);
        self.write_count += 1;
        Ok(())
    }
}

// =============================================================================
// RemovableFlash — a medium that can be pulled out
// =============================================================================

/// Test double for removable media: any flash that can be made absent.
///
/// Wraps an inner flash and gates every operation on a presence flag. While
/// absent, **reads fail too**, not just writes — a card yanked between writing a
/// spool intent record and reading the next payload must exercise both paths.
///
/// The inner flash is retained while absent, so [`insert`](Self::insert) restores
/// exactly the bytes that were there before, and [`into_inner`](Self::into_inner)
/// models carrying the card to a computer.
///
/// # Example
///
/// ```
/// use sensor_db::mock::{MockFlash, RemovableFlash};
///
/// let mut card = RemovableFlash::new(MockFlash::<256, 4096>::new(8 * 4096));
/// assert!(card.is_present());
/// card.remove();
/// assert!(!card.is_present());
/// card.insert();
/// ```
#[derive(Clone)]
pub struct RemovableFlash<F> {
    inner: F,
    present: bool,
    yank_after_writes: Option<u64>,
    writes: u64,
}

impl<F> RemovableFlash<F> {
    /// Wrap a flash device. The medium starts out present.
    pub fn new(inner: F) -> Self {
        Self {
            inner,
            present: true,
            yank_after_writes: None,
            writes: 0,
        }
    }

    /// Make the medium present again, with its contents intact.
    pub fn insert(&mut self) {
        self.present = true;
        self.yank_after_writes = None;
    }

    /// Remove the medium cleanly. Subsequent reads and writes fail with
    /// [`MockFlashError::NotPresent`].
    pub fn remove(&mut self) {
        self.present = false;
        self.yank_after_writes = None;
    }

    /// Become absent after `n` further writes — a surprise yank mid-batch.
    ///
    /// The `n`-th write from now still succeeds; the one after it fails. Use
    /// this to land a removal in the middle of a multi-page operation.
    pub fn yank_after(&mut self, n: u64) {
        self.yank_after_writes = Some(self.writes + n);
    }

    /// Whether the medium is currently present.
    pub fn is_present(&self) -> bool {
        self.present
    }

    /// Total writes attempted while present.
    pub fn write_count(&self) -> u64 {
        self.writes
    }

    /// Borrow the wrapped flash, ignoring presence.
    pub fn inner(&self) -> &F {
        &self.inner
    }

    /// Mutably borrow the wrapped flash, ignoring presence.
    pub fn inner_mut(&mut self) -> &mut F {
        &mut self.inner
    }

    /// Consume the wrapper and return the flash — "carry the card to the laptop".
    pub fn into_inner(self) -> F {
        self.inner
    }

    /// Check presence and account for a pending yank. Called before each write.
    fn admit_write(&mut self) -> Result<(), MockFlashError> {
        if !self.present {
            return Err(MockFlashError::NotPresent);
        }
        if let Some(threshold) = self.yank_after_writes
            && self.writes >= threshold
        {
            self.present = false;
            return Err(MockFlashError::NotPresent);
        }
        self.writes += 1;
        Ok(())
    }

    fn admit_read(&self) -> Result<(), MockFlashError> {
        if self.present {
            Ok(())
        } else {
            Err(MockFlashError::NotPresent)
        }
    }
}

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

impl<F> ErrorType for RemovableFlash<F> {
    type Error = MockFlashError;
}

impl<F> ReadNorFlash for RemovableFlash<F>
where
    F: ReadNorFlash<Error = MockFlashError>,
{
    const READ_SIZE: usize = 1;

    fn read(&mut self, offset: u32, buf: &mut [u8]) -> Result<(), Self::Error> {
        self.admit_read()?;
        self.inner.read(offset, buf)
    }

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

impl<F> NorFlash for RemovableFlash<F>
where
    F: NorFlash<Error = MockFlashError>,
{
    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> {
        self.admit_write()?;
        self.inner.erase(from, to)
    }

    fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
        self.admit_write()?;
        self.inner.write(offset, bytes)
    }
}

// =============================================================================
// Async mocks
// =============================================================================

/// Thin async adapter over any sync flash, implementing the async flash traits.
///
/// The wrapped devices here are in-memory, so the "async" operations complete
/// immediately — they delegate straight to the sync implementation. This exists
/// so async code can be exercised without an executor or real hardware.
///
/// Page and sector geometry is inherited from the wrapped device, so this
/// composes with [`RemovableFlash`] without restating the constants.
#[cfg(feature = "async")]
#[derive(Clone)]
pub struct AsyncFlash<F> {
    inner: F,
}

/// An async [`MockFlash`] of the given geometry.
#[cfg(feature = "async")]
pub type MockFlashAsync<const PAGE_SIZE: usize, const SECTOR_SIZE: usize> =
    AsyncFlash<MockFlash<PAGE_SIZE, SECTOR_SIZE>>;

#[cfg(feature = "async")]
impl<const PAGE_SIZE: usize, const SECTOR_SIZE: usize>
    AsyncFlash<MockFlash<PAGE_SIZE, SECTOR_SIZE>>
{
    /// Create a new async mock flash of `size` bytes.
    ///
    /// # Panics
    /// Panics if `size` is not a multiple of `SECTOR_SIZE`.
    pub fn new(size: usize) -> Self {
        Self {
            inner: MockFlash::<PAGE_SIZE, SECTOR_SIZE>::new(size),
        }
    }
}

#[cfg(feature = "async")]
impl<F> AsyncFlash<F> {
    /// Wrap an existing flash device in the async adapter.
    pub fn wrap(inner: F) -> Self {
        Self { inner }
    }

    /// Borrow the wrapped device (e.g. to configure power-loss injection).
    pub fn inner(&self) -> &F {
        &self.inner
    }

    /// Mutably borrow the wrapped device.
    pub fn inner_mut(&mut self) -> &mut F {
        &mut self.inner
    }

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

#[cfg(feature = "async")]
impl<F: ErrorType> embedded_storage_async::nor_flash::ErrorType for AsyncFlash<F> {
    type Error = F::Error;
}

#[cfg(feature = "async")]
impl<F: ReadNorFlash> embedded_storage_async::nor_flash::ReadNorFlash for AsyncFlash<F> {
    const READ_SIZE: usize = F::READ_SIZE;

    async fn read(&mut self, offset: u32, buf: &mut [u8]) -> Result<(), Self::Error> {
        self.inner.read(offset, buf)
    }

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

#[cfg(feature = "async")]
impl<F: NorFlash> embedded_storage_async::nor_flash::NorFlash for AsyncFlash<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> {
        self.inner.erase(from, to)
    }

    async fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
        self.inner.write(offset, bytes)
    }
}

#[cfg(feature = "async")]
impl<F: crate::spool::Removable> crate::spool::Removable for AsyncFlash<F> {
    fn is_present(&self) -> bool {
        self.inner.is_present()
    }
}

/// Drive a future to completion on the current thread, for tests and examples.
///
/// This is a deliberately minimal executor: it polls once and panics if the
/// future is not immediately ready. That is correct for the in-memory mocks
/// above, whose "async" operations never actually yield, and it turns an
/// accidental real await into a loud failure rather than a hang.
///
/// # Panics
/// Panics if the future returns `Poll::Pending`.
#[cfg(feature = "async")]
#[allow(unsafe_code, clippy::never_loop)]
pub fn block_on<T>(fut: impl core::future::Future<Output = T>) -> T {
    use core::pin::pin;
    use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};

    fn dummy_raw_waker() -> RawWaker {
        fn no_op(_: *const ()) {}
        fn clone(data: *const ()) -> RawWaker {
            RawWaker::new(data, &VTABLE)
        }
        const VTABLE: RawWakerVTable = RawWakerVTable::new(clone, no_op, no_op, no_op);
        RawWaker::new(core::ptr::null(), &VTABLE)
    }

    // SAFETY: The RawWaker vtable functions are valid no-ops, and the waker is
    // only used within this function's scope for polling.
    let waker = unsafe { Waker::from_raw(dummy_raw_waker()) };
    let mut cx = Context::from_waker(&waker);
    let mut fut = pin!(fut);

    loop {
        match fut.as_mut().poll(&mut cx) {
            Poll::Ready(val) => return val,
            Poll::Pending => panic!("async operation returned Pending in sync mock"),
        }
    }
}