Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/allocator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1105,7 +1105,11 @@ impl<E: Env> Allocator<E> {
}

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)
Expand Down
39 changes: 39 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Loading