summaryrefslogtreecommitdiff
path: root/ayafs-core/src/block_device/disk.rs
blob: 9e9b6bcdb553d6eb1ca3fcf01aac906633754576 (plain) (blame)
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
use crate::block_device::{BlockDevice, BLOCK_SIZE};
use std::cell::RefCell;
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::PathBuf;
use log::debug;

pub struct Disk {
    #[allow(unused)]
    disk_path: PathBuf,
    device: RefCell<File>,
}

impl Disk {
    pub fn new(disk_path: PathBuf) -> Self {
        let device = File::options()
            .read(true)
            .write(true)
            .open(disk_path.as_path())
            .unwrap();
        Self {
            disk_path,
            device: RefCell::new(device),
        }
    }
}

impl BlockDevice for Disk {
    fn read(&self, block_id: usize, buffer: &mut [u8]) {
        assert_eq!(buffer.len(), BLOCK_SIZE);
        let mut device = self.device.borrow_mut();
        device
            .seek(SeekFrom::Start((block_id * BLOCK_SIZE) as u64))
            .expect("Unable to seek!");
        device
            .read_exact(buffer)
            .expect("Failed to read 4096 bytes!");
        debug!("disk::read block {}", block_id);
    }

    fn write(&self, block_id: usize, buffer: &[u8]) {
        assert_eq!(buffer.len(), BLOCK_SIZE);
        let mut device = self.device.borrow_mut();
        device
            .seek(SeekFrom::Start((block_id * BLOCK_SIZE) as u64))
            .expect("Unable to seek!");
        device
            .write_all(buffer)
            .expect("Unable to write 4096 bytes!");
        debug!("disk::write block {}", block_id);
    }
}