From 998c6ce03d1475e86e5068ff2c25734a1af67aaa Mon Sep 17 00:00:00 2001 From: dario Date: Sat, 18 May 2024 21:33:42 +0200 Subject: [PATCH] Fixed grow_to assuming that the last free range is always at the end (Issue: https://github.com/gfx-rs/range-alloc/issues/1) --- src/lib.rs | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 767d31e..a811f23 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -35,7 +35,12 @@ where } pub fn grow_to(&mut self, new_end: T) { - if let Some(last_range) = self.free_ranges.last_mut() { + let initial_range_end = self.initial_range.end; + if let Some(last_range) = self + .free_ranges + .last_mut() + .filter(|last_range| last_range.end == initial_range_end) + { last_range.end = new_end; } else { self.free_ranges.push(self.initial_range.end..new_end); @@ -222,6 +227,30 @@ mod tests { alloc.free_range(0..14); } + #[test] + fn test_grow_with_hole_at_start() { + let mut alloc = RangeAllocator::new(0..6); + + assert_eq!(alloc.allocate_range(3), Ok(0..3)); + assert_eq!(alloc.allocate_range(3), Ok(3..6)); + alloc.free_range(0..3); + + alloc.grow_to(9); + assert_eq!(alloc.allocated_ranges().collect::>(), [3..6]); + } + #[test] + fn test_grow_with_hole_in_middle() { + let mut alloc = RangeAllocator::new(0..6); + + assert_eq!(alloc.allocate_range(2), Ok(0..2)); + assert_eq!(alloc.allocate_range(2), Ok(2..4)); + assert_eq!(alloc.allocate_range(2), Ok(4..6)); + alloc.free_range(2..4); + + alloc.grow_to(9); + assert_eq!(alloc.allocated_ranges().collect::>(), [0..2, 4..6]); + } + #[test] fn test_dont_use_block_that_is_too_small() { let mut alloc = RangeAllocator::new(0..10);