summaryrefslogtreecommitdiff
path: root/src/disk/bitmap.rs
blob: 64389c2c9dd3a9adcd6561a3ba98e8fc4af37d50 (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
53
54
use crate::block_device::{BlockDevice, BLOCK_SIZE};
use std::cell::RefCell;
use std::sync::Arc;

pub struct Bitmap {
    pub starting_block: usize,
    pub length: usize,
    pub device: Arc<dyn BlockDevice>,
    pub data: Vec<u8>,
}

impl Bitmap {
    pub fn new(starting_block: usize, length: usize, device: Arc<dyn BlockDevice>) -> Self {
        Self {
            starting_block,
            length,
            device,
            data: vec![0u8; length * BLOCK_SIZE],
        }
    }
    pub fn allocate(&mut self) -> Option<usize> {
        // let mut data = self.data.borrow_mut();
        for (i, byte) in self.data.iter_mut().enumerate() {
            let leading_ones = byte.leading_ones();
            if leading_ones != 8 {
                *byte |= (1 << (7 - leading_ones)) as u8;
                return Some(i * 8 + leading_ones as usize);
            }
        }
        None
        // panic!("No more space for allocation!")
    }

    pub fn query(&self, index: usize) -> bool {
        // let data = self.data.borrow();
        if index == 0 {
            false
        } else {
            self.data[index / 8] & ((1 << (7 - index % 8)) as u8) != 0
        }
    }

    // fn write_back(&mut self) {
    //     for block_index_offset in self.dirty_blocks.iter() {
    //         let buffer_front_index = BLOCK_SIZE * block_index_offset;
    //         let buffer_back_index = BLOCK_SIZE * (block_index_offset + 1);
    //         self.device.write(
    //             self.starting_block + block_index_offset,
    //             &self.data[buffer_front_index..buffer_back_index],
    //         );
    //     }
    //     self.dirty_blocks = Vec::new();
    // }
}