diff --git a/src/queue.rs b/src/queue.rs index 9d7ea33..0fcd32d 100644 --- a/src/queue.rs +++ b/src/queue.rs @@ -421,35 +421,6 @@ pub fn find_max_fit( let current_page = find_youngest_page(flash, flash_range.clone())?; - // Find the max space available on each page until we wrap around. - let mut max_free: Option = None; - let page_data_start_address = - calculate_page_address::(flash_range.clone(), current_page) + S::WORD_SIZE as u32; - let page_data_end_address = - calculate_page_end_address::(flash_range.clone(), current_page) - S::WORD_SIZE as u32; - - let mut current_address = page_data_start_address; - let end_address = page_data_end_address; - - while current_address < end_address { - let result = ItemHeader::read_new(flash, current_address, end_address)?; - match result { - Some(header) => current_address = header.next_item_address::(current_address), - None => { - let data_address = - round_up_to_alignment_usize::(current_address as usize + ItemHeader::LENGTH); - if data_address <= end_address as usize { - let free = round_down_to_alignment_usize::( - end_address as usize - data_address as usize, - ); - max_free = max_free.map(|current| current.max(free)).or(Some(free)); - } - - break; - } - } - } - // Check if we have space on the next page let next_page = next_page::(flash_range.clone(), current_page); match get_page_state(flash, flash_range.clone(), next_page)? { @@ -471,11 +442,11 @@ pub fn find_max_fit( )? .is_none(); if next_page_empty { - max_free.replace(S::ERASE_SIZE - (2 * S::WORD_SIZE)); + return Ok(Some(S::ERASE_SIZE - (2 * S::WORD_SIZE))); } } PageState::Open => { - max_free.replace(S::ERASE_SIZE - (2 * S::WORD_SIZE)); + return Ok(Some(S::ERASE_SIZE - (2 * S::WORD_SIZE))); } PageState::PartialOpen => { // This should never happen @@ -483,6 +454,35 @@ pub fn find_max_fit( } }; + // See how much space we can ind in the current page. + let mut max_free: Option = None; + let page_data_start_address = + calculate_page_address::(flash_range.clone(), current_page) + S::WORD_SIZE as u32; + let page_data_end_address = + calculate_page_end_address::(flash_range.clone(), current_page) - S::WORD_SIZE as u32; + + let mut current_address = page_data_start_address; + let end_address = page_data_end_address; + + while current_address < end_address { + let result = ItemHeader::read_new(flash, current_address, end_address)?; + match result { + Some(header) => current_address = header.next_item_address::(current_address), + None => { + let data_address = + round_up_to_alignment_usize::(current_address as usize + ItemHeader::LENGTH); + if data_address <= end_address as usize { + let free = round_down_to_alignment_usize::( + end_address as usize - data_address as usize, + ); + max_free = max_free.map(|current| current.max(free)).or(Some(free)); + } + + break; + } + } + } + Ok(max_free) }