diff --git a/src/allocator.rs b/src/allocator.rs index 0400970..a019b3a 100644 --- a/src/allocator.rs +++ b/src/allocator.rs @@ -1105,7 +1105,11 @@ impl Allocator { } let new_pointer = self.alloc(align, new_size)?; - core::ptr::copy_nonoverlapping(pointer.as_ptr(), new_pointer.as_ptr(), current_size.bytes() as usize); + core::ptr::copy_nonoverlapping( + pointer.as_ptr(), + new_pointer.as_ptr(), + core::cmp::min(current_size, new_size).bytes() as usize, + ); self.free(pointer); Some(new_pointer) diff --git a/src/lib.rs b/src/lib.rs index d35bc1f..12380d0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -230,6 +230,45 @@ fn test_shrink() { unsafe { alloc.free(b) }; } +#[test] +fn test_realloc() { + let one = Size::from_bytes_usize(1).unwrap(); + let big = Size::from_bytes_usize(128).unwrap(); + let small = Size::from_bytes_usize(32).unwrap(); + + let mut buffer = Array([0_u8; 512]); + let mut alloc = Allocator::new(unsafe { ArrayPointer::new(&mut buffer) }); + + let a = alloc.alloc(one, big).unwrap(); + unsafe { + for i in 0..128 { + *a.as_ptr().add(i) = i as u8; + } + } + + let a = unsafe { alloc.realloc(a, one, small) }.unwrap(); + unsafe { + for i in 0..32 { + assert_eq!(*a.as_ptr().add(i), i as u8); + } + alloc.free(a); + } + + let b = alloc.alloc(one, small).unwrap(); + unsafe { + for i in 0..32 { + *b.as_ptr().add(i) = i as u8; + } + } + let b = unsafe { alloc.realloc(b, one, big) }.unwrap(); + unsafe { + for i in 0..32 { + assert_eq!(*b.as_ptr().add(i), i as u8); + } + alloc.free(b); + } +} + #[test] fn test_grow() { let one = Size::from_bytes_usize(32).unwrap();