From 7a748cadbb2e2ce8c0e045cb8fbd77ccbd47459f Mon Sep 17 00:00:00 2001 From: Chuyan Zhang Date: Tue, 17 Oct 2023 23:07:21 -0700 Subject: initial commit --- src/disk/bitmap.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/disk/bitmap.rs (limited to 'src/disk/bitmap.rs') diff --git a/src/disk/bitmap.rs b/src/disk/bitmap.rs new file mode 100644 index 0000000..a5a9cc4 --- /dev/null +++ b/src/disk/bitmap.rs @@ -0,0 +1,49 @@ +use crate::block_device::{BlockDevice, BLOCK_SIZE}; +use std::sync::Arc; + +pub struct Bitmap { + pub starting_block: usize, + pub length: usize, + pub device: Arc, + pub data: Vec, + pub dirty_blocks: Vec, +} + +impl Bitmap { + pub fn new(starting_block: usize, length: usize, device: Arc) -> Self { + Self { + starting_block, + length, + device, + data: vec![0u8; length * BLOCK_SIZE], + dirty_blocks: Vec::new(), + } + } + pub fn allocate(&mut self) -> usize { + 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; + self.dirty_blocks.push(i / BLOCK_SIZE); + return i * 8 + leading_ones as usize; + } + } + panic!("No more space for allocation!") + } + + pub fn query(&self, index: usize) -> bool { + 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(); + } +} -- cgit v1.2.3-70-g09d2