Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- pub(super) fn set_size(&mut self, size: usize, block_bitmap: &mut Bitmap) -> Result<()> {
- // ANCHOR_END: set_size
- let current_size = self.size;
- // debug!(msg = "SET_SIZE", old_size = self.size, new_size = size);
- if size == self.size {
- return Ok(());
- }
- if size > self.size {
- let block_index = self.block_entry(self.size / BLOCK_SIZE, Some(block_bitmap))?;
- Self::try_allocate_entry(block_index, Some(block_bitmap))?;
- // debug!(index = *block_index);
- unsafe { BlockCache::block(*block_index)?.try_into_mut_slice::<u8>() }?
- .split_at_mut(current_size % BLOCK_SIZE)
- .1
- .fill(0);
- BlockCache::flush_block(*block_index)?;
- for block in self.size.div_ceil(BLOCK_SIZE)..=size.div_ceil(BLOCK_SIZE) {
- // debug!(block);
- let block_index = self.block_entry(block, Some(block_bitmap))?;
- Self::try_allocate_entry(block_index, Some(block_bitmap))?;
- // debug!(index = *block_index);
- unsafe { BlockCache::block(*block_index)?.try_into_mut_slice::<u8>() }?.fill(0);
- BlockCache::flush_block(*block_index)?;
- }
- } else if size == 0 {
- for height in 0..MAX_HEIGHT {
- remove_tree(&mut self.root_blocks[height], height, block_bitmap)?;
- }
- } else {
- let mut cumulative_size: usize = 0;
- let mut height = 0;
- while height != MAX_HEIGHT {
- cumulative_size += leaf_count_in_tree(height);
- if cumulative_size >= size.div_ceil(BLOCK_SIZE) {
- break;
- }
- height += 1;
- }
- let mut last_height = height;
- if height != MAX_HEIGHT {
- height += 1;
- }
- while height != MAX_HEIGHT && self.root_blocks[height] != NO_BLOCK {
- remove_tree(&mut self.root_blocks[height], height, block_bitmap)?;
- height += 1;
- }
- let mut current_size = self.size.div_ceil(BLOCK_SIZE);
- for prev in 0..last_height {
- current_size -= leaf_count_in_tree(prev);
- }
- let mut current_block = self.root_blocks[last_height];
- let mut option_block_bitmap = Some(block_bitmap);
- while last_height != 0 {
- let current_child_size = leaf_count_in_tree(last_height - 1);
- let split_index = current_size.div_ceil(current_child_size);
- let next_layer = next_level(&mut current_block, &mut option_block_bitmap)?;
- for block in next_layer.split_at_mut(split_index).1 {
- remove_tree(
- block,
- last_height - 1,
- option_block_bitmap.as_mut().unwrap(),
- )?;
- }
- if split_index == 0 || current_size % current_child_size == 0 {
- break;
- }
- current_block = next_layer[split_index - 1];
- last_height -= 1;
- current_size -= current_child_size * split_index;
- }
- }
- self.size = size;
- Ok(())
- }
Advertisement
Add Comment
Please, Sign In to add comment