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
/* Copyright (c) [2023] [Syswonder Community]
* [Rukos] is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
//! Mock block devices that store data in RAM.
extern crate alloc;
use crate::BlockDriverOps;
use alloc::{vec, vec::Vec};
use driver_common::{BaseDriverOps, DevError, DevResult, DeviceType};
const BLOCK_SIZE: usize = 512;
/// A RAM disk that stores data in a vector.
#[derive(Default)]
pub struct RamDisk {
size: usize,
data: Vec<u8>,
}
impl RamDisk {
/// Creates a new RAM disk with the given size hint.
///
/// The actual size of the RAM disk will be aligned upwards to the block
/// size (512 bytes).
pub fn new(size_hint: usize) -> Self {
let size = align_up(size_hint);
Self {
size,
data: vec![0; size],
}
}
/// Creates a new RAM disk from the exiting data.
///
/// The actual size of the RAM disk will be aligned upwards to the block
/// size (512 bytes).
pub fn from(buf: &[u8]) -> Self {
let size = align_up(buf.len());
let mut data = vec![0; size];
data[..buf.len()].copy_from_slice(buf);
Self { size, data }
}
/// Returns the size of the RAM disk in bytes.
pub const fn size(&self) -> usize {
self.size
}
}
impl const BaseDriverOps for RamDisk {
fn device_type(&self) -> DeviceType {
DeviceType::Block
}
fn device_name(&self) -> &str {
"ramdisk"
}
}
impl BlockDriverOps for RamDisk {
#[inline]
fn num_blocks(&self) -> u64 {
(self.size / BLOCK_SIZE) as u64
}
#[inline]
fn block_size(&self) -> usize {
BLOCK_SIZE
}
fn read_block(&mut self, block_id: u64, buf: &mut [u8]) -> DevResult {
let offset = block_id as usize * BLOCK_SIZE;
if offset + buf.len() > self.size {
return Err(DevError::Io);
}
if buf.len() % BLOCK_SIZE != 0 {
return Err(DevError::InvalidParam);
}
buf.copy_from_slice(&self.data[offset..offset + buf.len()]);
Ok(())
}
fn write_block(&mut self, block_id: u64, buf: &[u8]) -> DevResult {
let offset = block_id as usize * BLOCK_SIZE;
if offset + buf.len() > self.size {
return Err(DevError::Io);
}
if buf.len() % BLOCK_SIZE != 0 {
return Err(DevError::InvalidParam);
}
self.data[offset..offset + buf.len()].copy_from_slice(buf);
Ok(())
}
fn flush(&mut self) -> DevResult {
Ok(())
}
}
const fn align_up(val: usize) -> usize {
(val + BLOCK_SIZE - 1) & !(BLOCK_SIZE - 1)
}