Skip to main content

slate_kv_hal/
lib.rs

1//! slate-kv-hal
2
3#![no_std]
4#![forbid(unsafe_code)]
5#![warn(missing_docs)]
6#![allow(clippy::manual_is_multiple_of)]
7#![allow(clippy::needless_range_loop)]
8
9/// Report §2.1: program-once-per-erase NOR flash with detectable tearing.
10pub trait Flash {
11    /// Flash error type.
12    type Error: core::fmt::Debug;
13    /// Program granularity.
14    fn page_size(&self) -> usize;
15    /// Erase granularity, multiple of page_size.
16    fn block_size(&self) -> usize;
17    /// Capacity in bytes, C_flash.
18    fn capacity(&self) -> u32;
19    /// Reads from flash.
20    fn read(&mut self, addr: u32, buf: &mut [u8]) -> Result<(), Self::Error>;
21    /// May only program pages that are in erased state. addr and buf.len()
22    /// must be page-aligned/page-sized multiples. Completion = durable.
23    fn program(&mut self, addr: u32, buf: &[u8]) -> Result<(), Self::Error>;
24    /// Erases a block resetting it to all 1s.
25    fn erase(&mut self, block_addr: u32) -> Result<(), Self::Error>;
26}
27
28/// Type of monotonic counter.
29#[derive(Clone, Copy, PartialEq, Eq, Debug)]
30pub enum CounterKind {
31    /// Hardware counter.
32    Hardware,
33    /// Best effort counter.
34    BestEffort,
35    /// No counter.
36    None,
37}
38
39/// Report §2.4 / §3.4: hardware monotonic counter, honest-degradation aware.
40pub trait MonotonicCounter {
41    /// Counter error type.
42    type Error: core::fmt::Debug;
43    /// Kind of the counter.
44    fn kind(&self) -> CounterKind;
45    /// Reads the counter.
46    fn read(&mut self) -> Result<u64, Self::Error>;
47    /// Must be durable before returning Ok. Fails when budget exhausted.
48    fn increment(&mut self) -> Result<u64, Self::Error>; // returns new value
49}
50
51/// Source of entropy.
52pub trait EntropySource {
53    /// Fills buffer with entropy.
54    fn fill(&mut self, buf: &mut [u8]);
55}
56
57/// Optional coarse clock for the deadline clamp (doc 008); ticks in ms.
58pub trait Clock {
59    /// Returns current time in ms.
60    fn now_ms(&self) -> u64;
61}
62
63#[cfg(feature = "embedded-storage-async")]
64pub mod storage_async;
65
66/// Async twin of [`Flash`]. Method-for-method identical, including the
67/// program-once-per-erase contract (§2.1) and the `Error` associated type.
68///
69/// `erase` is a SINGLE indivisible operation: an implementation may await
70/// internally (DMA completion, status-poll interrupt), but a caller can never
71/// observe a half-erased block, and cancellation of the returned future does
72/// NOT abort an erase already latched into the die (§7).
73pub trait AsyncFlash {
74    /// Flash error type.
75    type Error: core::fmt::Debug;
76    /// Program granularity. Never suspends — pure metadata.
77    fn page_size(&self) -> usize;
78    /// Erase granularity, multiple of page_size. Never suspends.
79    fn block_size(&self) -> usize;
80    /// Capacity in bytes, C_flash. Never suspends.
81    fn capacity(&self) -> u32;
82
83    /// Reads `buf.len()` bytes at `addr`.
84    fn read(
85        &mut self,
86        addr: u32,
87        buf: &mut [u8],
88    ) -> impl core::future::Future<Output = Result<(), Self::Error>>;
89    /// Programs one page. MUST fail if the target page was already programmed
90    /// since its last erase (identical contract to `Flash::program`).
91    fn program(
92        &mut self,
93        addr: u32,
94        buf: &[u8],
95    ) -> impl core::future::Future<Output = Result<(), Self::Error>>;
96    /// Erases one block. Indivisible; see type-level note.
97    fn erase(
98        &mut self,
99        block_addr: u32,
100    ) -> impl core::future::Future<Output = Result<(), Self::Error>>;
101}
102
103/// Async twin of [`MonotonicCounter`]. `increment` is a DURABLE write on every
104/// backend that matters (RTC-backed NVS, I2C EEPROM, secure element), so it is
105/// exactly as deserving of a yield point as `Flash::program`.
106pub trait AsyncMonotonicCounter {
107    /// Counter error type.
108    type Error: core::fmt::Debug;
109    /// Counter class. Never suspends.
110    fn kind(&self) -> CounterKind;
111    /// Reads the current value.
112    fn read(&mut self) -> impl core::future::Future<Output = Result<u64, Self::Error>>;
113    /// Increments and returns the NEW value. Durable on return.
114    fn increment(&mut self) -> impl core::future::Future<Output = Result<u64, Self::Error>>;
115}
116
117/// Lifts any blocking [`Flash`] into [`AsyncFlash`] by returning already-ready
118/// futures. This is the zero-cost bridge that keeps `targets/esp32`,
119/// `slate-kv`, `slate-kv-ffi` and every existing board crate compiling
120/// unchanged.
121pub struct BlockingFlash<F: Flash>(pub F);
122
123impl<F: Flash> AsyncFlash for BlockingFlash<F> {
124    type Error = F::Error;
125    fn page_size(&self) -> usize {
126        self.0.page_size()
127    }
128    fn block_size(&self) -> usize {
129        self.0.block_size()
130    }
131    fn capacity(&self) -> u32 {
132        self.0.capacity()
133    }
134    fn read(
135        &mut self,
136        addr: u32,
137        buf: &mut [u8],
138    ) -> impl core::future::Future<Output = Result<(), Self::Error>> {
139        core::future::ready(self.0.read(addr, buf))
140    }
141    fn program(
142        &mut self,
143        addr: u32,
144        buf: &[u8],
145    ) -> impl core::future::Future<Output = Result<(), Self::Error>> {
146        core::future::ready(self.0.program(addr, buf))
147    }
148    fn erase(
149        &mut self,
150        block_addr: u32,
151    ) -> impl core::future::Future<Output = Result<(), Self::Error>> {
152        core::future::ready(self.0.erase(block_addr))
153    }
154}
155
156/// Same bridge for the counter.
157pub struct BlockingCounter<C: MonotonicCounter>(pub C);
158
159impl<C: MonotonicCounter> AsyncMonotonicCounter for BlockingCounter<C> {
160    type Error = C::Error;
161    fn kind(&self) -> CounterKind {
162        self.0.kind()
163    }
164    fn read(&mut self) -> impl core::future::Future<Output = Result<u64, Self::Error>> {
165        core::future::ready(self.0.read())
166    }
167    fn increment(&mut self) -> impl core::future::Future<Output = Result<u64, Self::Error>> {
168        core::future::ready(self.0.increment())
169    }
170}
171
172impl<F: Flash> Flash for BlockingFlash<F> {
173    type Error = F::Error;
174    fn page_size(&self) -> usize {
175        self.0.page_size()
176    }
177    fn block_size(&self) -> usize {
178        self.0.block_size()
179    }
180    fn capacity(&self) -> u32 {
181        self.0.capacity()
182    }
183    fn read(&mut self, addr: u32, buf: &mut [u8]) -> Result<(), Self::Error> {
184        self.0.read(addr, buf)
185    }
186    fn program(&mut self, addr: u32, buf: &[u8]) -> Result<(), Self::Error> {
187        self.0.program(addr, buf)
188    }
189    fn erase(&mut self, block_addr: u32) -> Result<(), Self::Error> {
190        self.0.erase(block_addr)
191    }
192}
193
194impl<C: MonotonicCounter> MonotonicCounter for BlockingCounter<C> {
195    type Error = C::Error;
196    fn kind(&self) -> CounterKind {
197        self.0.kind()
198    }
199    fn read(&mut self) -> Result<u64, Self::Error> {
200        self.0.read()
201    }
202    fn increment(&mut self) -> Result<u64, Self::Error> {
203        self.0.increment()
204    }
205}
206
207impl<F: Flash + ?Sized> Flash for &mut F {
208    type Error = F::Error;
209    fn page_size(&self) -> usize {
210        (**self).page_size()
211    }
212    fn block_size(&self) -> usize {
213        (**self).block_size()
214    }
215    fn capacity(&self) -> u32 {
216        (**self).capacity()
217    }
218    fn read(&mut self, addr: u32, buf: &mut [u8]) -> Result<(), Self::Error> {
219        (**self).read(addr, buf)
220    }
221    fn program(&mut self, addr: u32, buf: &[u8]) -> Result<(), Self::Error> {
222        (**self).program(addr, buf)
223    }
224    fn erase(&mut self, block_addr: u32) -> Result<(), Self::Error> {
225        (**self).erase(block_addr)
226    }
227}
228
229impl<F: AsyncFlash + ?Sized> AsyncFlash for &mut F {
230    type Error = F::Error;
231    fn page_size(&self) -> usize {
232        (**self).page_size()
233    }
234    fn block_size(&self) -> usize {
235        (**self).block_size()
236    }
237    fn capacity(&self) -> u32 {
238        (**self).capacity()
239    }
240    async fn read(&mut self, addr: u32, buf: &mut [u8]) -> Result<(), Self::Error> {
241        (**self).read(addr, buf).await
242    }
243    async fn program(&mut self, addr: u32, buf: &[u8]) -> Result<(), Self::Error> {
244        (**self).program(addr, buf).await
245    }
246    async fn erase(&mut self, block_addr: u32) -> Result<(), Self::Error> {
247        (**self).erase(block_addr).await
248    }
249}
250
251impl<C: MonotonicCounter + ?Sized> MonotonicCounter for &mut C {
252    type Error = C::Error;
253    fn kind(&self) -> CounterKind {
254        (**self).kind()
255    }
256    fn read(&mut self) -> Result<u64, Self::Error> {
257        (**self).read()
258    }
259    fn increment(&mut self) -> Result<u64, Self::Error> {
260        (**self).increment()
261    }
262}
263
264impl<C: AsyncMonotonicCounter + ?Sized> AsyncMonotonicCounter for &mut C {
265    type Error = C::Error;
266    fn kind(&self) -> CounterKind {
267        (**self).kind()
268    }
269    async fn read(&mut self) -> Result<u64, Self::Error> {
270        (**self).read().await
271    }
272    async fn increment(&mut self) -> Result<u64, Self::Error> {
273        (**self).increment().await
274    }
275}
276
277#[cfg(test)]
278extern crate std;
279
280#[cfg(test)]
281#[allow(dead_code)]
282mod tests {
283    use super::*;
284    use std::vec::Vec;
285
286    #[derive(Debug)]
287    pub struct StubFlashError;
288
289    pub struct StubFlash {
290        pub mem: Vec<u8>,
291        page_size: usize,
292        block_size: usize,
293    }
294
295    impl StubFlash {
296        pub fn new(capacity: u32, page_size: usize, block_size: usize) -> Self {
297            Self {
298                mem: std::vec![0xFF; capacity as usize],
299                page_size,
300                block_size,
301            }
302        }
303    }
304
305    impl Flash for StubFlash {
306        type Error = StubFlashError;
307
308        fn page_size(&self) -> usize {
309            self.page_size
310        }
311
312        fn block_size(&self) -> usize {
313            self.block_size
314        }
315
316        fn capacity(&self) -> u32 {
317            self.mem.len() as u32
318        }
319
320        fn read(&mut self, addr: u32, buf: &mut [u8]) -> Result<(), Self::Error> {
321            let addr = addr as usize;
322            if addr + buf.len() > self.mem.len() {
323                return Err(StubFlashError);
324            }
325            buf.copy_from_slice(&self.mem[addr..addr + buf.len()]);
326            Ok(())
327        }
328
329        fn program(&mut self, addr: u32, buf: &[u8]) -> Result<(), Self::Error> {
330            let addr = addr as usize;
331            if addr % self.page_size != 0 || buf.len() % self.page_size != 0 {
332                return Err(StubFlashError);
333            }
334            if addr + buf.len() > self.mem.len() {
335                return Err(StubFlashError);
336            }
337            for i in 0..buf.len() {
338                if self.mem[addr + i] != 0xFF {
339                    return Err(StubFlashError); // Program-once-per-erase
340                }
341                self.mem[addr + i] &= buf[i];
342            }
343            Ok(())
344        }
345
346        fn erase(&mut self, block_addr: u32) -> Result<(), Self::Error> {
347            let block_addr = block_addr as usize;
348            if block_addr % self.block_size != 0 {
349                return Err(StubFlashError);
350            }
351            if block_addr + self.block_size > self.mem.len() {
352                return Err(StubFlashError);
353            }
354            for i in 0..self.block_size {
355                self.mem[block_addr + i] = 0xFF;
356            }
357            Ok(())
358        }
359    }
360
361    #[derive(Debug)]
362    pub struct StubCounterError;
363
364    pub struct StubCounter {
365        val: u64,
366        budget: u64,
367        kind: CounterKind,
368    }
369
370    impl StubCounter {
371        pub fn new(budget: u64, kind: CounterKind) -> Self {
372            Self {
373                val: 0,
374                budget,
375                kind,
376            }
377        }
378    }
379
380    impl MonotonicCounter for StubCounter {
381        type Error = StubCounterError;
382
383        fn kind(&self) -> CounterKind {
384            self.kind
385        }
386
387        fn read(&mut self) -> Result<u64, Self::Error> {
388            Ok(self.val)
389        }
390
391        fn increment(&mut self) -> Result<u64, Self::Error> {
392            if self.budget == 0 {
393                return Err(StubCounterError);
394            }
395            self.budget -= 1;
396            self.val += 1;
397            Ok(self.val)
398        }
399    }
400
401    #[test]
402    fn test_stub_flash() {
403        let mut flash = StubFlash::new(4096, 256, 4096);
404        assert_eq!(flash.capacity(), 4096);
405        let mut buf = [0u8; 256];
406        flash.read(0, &mut buf).unwrap();
407        assert_eq!(buf, [0xFF; 256]);
408
409        let prog_buf = [0xAA; 256];
410        flash.program(0, &prog_buf).unwrap();
411        flash.read(0, &mut buf).unwrap();
412        assert_eq!(buf, [0xAA; 256]);
413
414        assert!(flash.program(0, &prog_buf).is_err()); // Already programmed
415        flash.erase(0).unwrap();
416        flash.read(0, &mut buf).unwrap();
417        assert_eq!(buf, [0xFF; 256]);
418    }
419
420    #[test]
421    fn test_blocking_adapters() {
422        let flash = BlockingFlash(StubFlash::new(4096, 256, 4096));
423        assert_eq!(Flash::capacity(&flash), 4096);
424        let counter = BlockingCounter(StubCounter::new(10, CounterKind::BestEffort));
425        assert_eq!(MonotonicCounter::kind(&counter), CounterKind::BestEffort);
426    }
427}