file_system/devices/memory_device.rs
1//! In-memory device implementation for testing and simulation.
2
3//!
4//! This module provides a memory-based device implementation that stores data
5//! in RAM instead of on physical storage. It's primarily used for testing,
6//! simulation, and development purposes where you need a device that behaves
7//! like storage but doesn't require actual hardware.
8
9use core::fmt::Debug;
10
11use alloc::vec::Vec;
12use alloc::{boxed::Box, vec};
13use shared::AnyByLayout;
14use synchronization::{blocking_mutex::raw::CriticalSectionRawMutex, rwlock::RwLock};
15
16use crate::block_device::GET_BLOCK_SIZE;
17use crate::{
18 ControlCommand, DirectBaseOperations, DirectBlockDevice, IoErrorKind, MountOperations, Result,
19 Size, block_device,
20};
21
22/// In-memory device implementation with configurable block size.
23///
24/// This device stores all data in memory using a `Vec<u8>` and provides the same
25/// interface as physical storage devices. It's thread-safe and supports all standard
26/// device operations. The block size is configurable at compile time through the
27/// const generic parameter.
28///
29/// # Type Parameters
30///
31/// * `Block_size` - The block size in bytes (must be a power of 2, typically 512)
32///
33/// # Examples
34///
35/// ```rust
36/// extern crate alloc;
37/// use file_system::{MemoryDevice, DirectBaseOperations, Position};
38///
39/// // Create a 1MB memory device with 512-byte blocks
40/// let device = MemoryDevice::<512>::new(1024 * 1024);
41///
42/// // Write some data
43/// let data = b"Hello, Memory Device!";
44/// device.write_sync(data, 0).unwrap();
45///
46/// // Reset position and read back
47/// device.set_position(0, &Position::Start(0)).unwrap();
48/// let mut buffer = alloc::vec![0u8; data.len()];
49/// device.read_sync(&mut buffer, 0).unwrap();
50/// assert_eq!(&buffer, data);
51/// ```
52///
53/// # Thread Safety
54///
55/// The device uses an `RwLock` to ensure thread-safe access to the underlying data.
56/// Multiple readers can access the device simultaneously, but writes are exclusive.
57pub struct MemoryDevice<const BLOCK_SIZE: u32>(RwLock<CriticalSectionRawMutex, Vec<u8>>);
58
59impl<const BLOCK_SIZE: u32> Debug for MemoryDevice<BLOCK_SIZE> {
60 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
61 f.debug_struct("MemoryDevice")
62 .field("size", &self.0.try_read().map(|data| data.len()))
63 .finish()
64 }
65}
66
67impl<const BLOCK_SIZE: u32> MemoryDevice<BLOCK_SIZE> {
68 /// Create a new memory device with the specified size.
69 ///
70 /// The device will be initialized with zeros and have the specified total size.
71 /// The size must be a multiple of the block size.
72 ///
73 /// # Arguments
74 ///
75 /// * `Size` - Total size of the device in bytes
76 ///
77 /// # Panics
78 ///
79 /// Panics if `Size` is not a multiple of `Block_size`.
80 ///
81 /// # Examples
82 ///
83 /// ```rust
84 /// # extern crate alloc;
85 /// # use file_system::MemoryDevice;
86 ///
87 /// // Create a 4KB device with 512-byte blocks
88 /// let device = MemoryDevice::<512>::new(4096);
89 /// ```
90 pub fn new(size: usize) -> Self {
91 assert!(size.is_multiple_of(BLOCK_SIZE as usize));
92
93 let data: Vec<u8> = vec![0; size];
94
95 Self(RwLock::new(data))
96 }
97
98 pub fn new_static(size: usize) -> &'static Self {
99 Box::leak(Box::new(Self::new(size)))
100 }
101
102 /// Create a memory device from existing data.
103 ///
104 /// This allows you to create a device with pre-populated data, useful for
105 /// testing with known data patterns or loading device images.
106 ///
107 /// # Arguments
108 ///
109 /// * `Data` - Vector containing the initial device data
110 ///
111 /// # Panics
112 ///
113 /// Panics if the data length is not a multiple of `Block_size`.
114 ///
115 /// # Examples
116 ///
117 /// ```rust
118 /// # extern crate alloc;
119 /// # use file_system::MemoryDevice;
120 /// # use alloc::vec;
121 ///
122 /// // Create device with specific data
123 /// let data = vec![0x42; 1024]; // 1KB of 0x42 bytes
124 /// let device = MemoryDevice::<512>::from_vec(data);
125 /// ```
126 pub fn from_vec(data: Vec<u8>) -> Self {
127 assert!(data.len().is_multiple_of(BLOCK_SIZE as usize));
128
129 Self(RwLock::new(data))
130 }
131}
132
133impl<const BLOCK_SIZE: u32> DirectBaseOperations for MemoryDevice<BLOCK_SIZE> {
134 /// Read data from the memory device.
135 ///
136 /// Reads data from the current position into the provided buffer.
137 /// The position is automatically advanced by the number of bytes read.
138 fn read(
139 &self,
140 _cx: &mut core::task::Context<'_>,
141 buffer: &mut [u8],
142 absolute_position: Size,
143 ) -> core::task::Poll<Result<usize>> {
144 crate::ready(|| {
145 let inner = self
146 .0
147 .try_write()
148 .map_err(|_| crate::IoErrorKind::WouldBlock)?;
149
150 let absolute_position = absolute_position as usize;
151
152 let read_size = buffer
153 .len()
154 .min(inner.len().saturating_sub(absolute_position));
155 buffer[..read_size]
156 .copy_from_slice(&inner[absolute_position..absolute_position + read_size]);
157 Ok(read_size as _)
158 })
159 }
160
161 fn write(
162 &self,
163 _cx: &mut core::task::Context<'_>,
164 buffer: &[u8],
165 absolute_position: Size,
166 ) -> core::task::Poll<Result<usize>> {
167 crate::ready(|| {
168 let mut inner = self
169 .0
170 .try_write()
171 .map_err(|_| crate::IoErrorKind::WouldBlock)?;
172
173 let absolute_position = absolute_position as usize;
174
175 let write_size = buffer
176 .len()
177 .min(inner.len().saturating_sub(absolute_position));
178 inner[absolute_position..absolute_position + write_size]
179 .copy_from_slice(&buffer[..write_size]);
180
181 Ok(write_size as _)
182 })
183 }
184
185 fn control(
186 &self,
187 _cx: &mut core::task::Context<'_>,
188 command: crate::ControlCommandIdentifier,
189 _: &AnyByLayout,
190 output: &mut AnyByLayout,
191 ) -> core::task::Poll<Result<()>> {
192 crate::ready(|| {
193 match command {
194 GET_BLOCK_SIZE::IDENTIFIER => {
195 let output = GET_BLOCK_SIZE::cast_output(output)?;
196 *output = BLOCK_SIZE;
197 }
198 block_device::GET_BLOCK_COUNT::IDENTIFIER => {
199 let output = block_device::GET_BLOCK_COUNT::cast_output(output)?;
200
201 *output = (self
202 .0
203 .try_read()
204 .map_err(|_| crate::IoErrorKind::WouldBlock)?
205 .len()
206 / BLOCK_SIZE as usize) as Size;
207 }
208 _ => return Err(IoErrorKind::Unsupported),
209 }
210
211 Ok(())
212 })
213 }
214}
215
216impl<const BLOCK_SIZE: u32> MountOperations for MemoryDevice<BLOCK_SIZE> {}
217
218impl<const BLOCK_SIZE: u32> DirectBlockDevice for MemoryDevice<BLOCK_SIZE> {}
219
220#[cfg(test)]
221mod tests {
222 use super::*;
223 use crate::implement_block_device_tests;
224
225 implement_block_device_tests!(MemoryDevice::<512>::new(4096));
226}