Skip to main content

sdmmc_async/
block.rs

1/// The size of a block, in bytes.
2pub const BLOCK_SIZE: usize = 512;
3
4/// A device that reads 512-byte blocks. The filesystem layer never assumes
5/// anything about the device beyond this.
6pub trait BlockDevice {
7    /// The error a read can fail with.
8    type Error;
9
10    /// Reads block number `block` (counted from 0) into `buffer`.
11    async fn read_block(
12        &mut self,
13        block: u32,
14        buffer: &mut [u8; BLOCK_SIZE],
15    ) -> Result<(), Self::Error>;
16
17    /// The number of blocks the device holds.
18    async fn num_blocks(&mut self) -> Result<u32, Self::Error>;
19}
20
21/// A device that can also write 512-byte blocks.
22///
23/// Separate from [`BlockDevice`] so a read-only device needs nothing more.
24#[cfg(feature = "write")]
25pub trait BlockWrite: BlockDevice {
26    /// Writes `buffer` to block number `block` (counted from 0). When this returns `Ok`, the card has accepted and
27    /// finished programming the block.
28    async fn write_block(
29        &mut self,
30        block: u32,
31        buffer: &[u8; BLOCK_SIZE],
32    ) -> Result<(), Self::Error>;
33}
34
35#[cfg(feature = "write")]
36impl<D: BlockWrite + ?Sized> BlockWrite for &mut D {
37    async fn write_block(
38        &mut self,
39        block: u32,
40        buffer: &[u8; BLOCK_SIZE],
41    ) -> Result<(), Self::Error> {
42        (**self).write_block(block, buffer).await
43    }
44}
45
46/// A device lent to the filesystem for a while: a mount that borrows the card and gives it back.
47impl<D: BlockDevice + ?Sized> BlockDevice for &mut D {
48    type Error = D::Error;
49
50    async fn read_block(
51        &mut self,
52        block: u32,
53        buffer: &mut [u8; BLOCK_SIZE],
54    ) -> Result<(), Self::Error> {
55        (**self).read_block(block, buffer).await
56    }
57
58    async fn num_blocks(&mut self) -> Result<u32, Self::Error> {
59        (**self).num_blocks().await
60    }
61}