Skip to content

Commit f3ae0fd

Browse files
committed
Shrink buffer down to length to uphold safety invariant
1 parent f1fa4bb commit f3ae0fd

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

packages/std/src/memory.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,13 @@ pub fn alloc(size: usize) -> *mut Region {
3333
/// Similar to alloc, but instead of creating a new vector it consumes an existing one and returns
3434
/// a pointer to the Region (preventing the memory from being freed until explicitly called later).
3535
///
36-
/// The resulting Region has capacity = length, i.e. the buffer's capacity is ignored.
37-
pub fn release_buffer(buffer: Vec<u8>) -> *mut Region {
36+
/// The resulting Region has capacity = length, the buffer capacity is shrunk down to its length.
37+
pub fn release_buffer(mut buffer: Vec<u8>) -> *mut Region {
38+
// Shrinking the buffer down to the length is important to uphold a safety invariant by the `dealloc` method.
39+
// Passing in a differing size into the `dealloc` layout is considered undefined behaviour.
40+
//
41+
// See: <https://doc.rust-lang.org/stable/alloc/alloc/trait.GlobalAlloc.html#safety-2>
42+
buffer.shrink_to_fit();
3843
let region = build_region(&buffer);
3944
mem::forget(buffer);
4045
Box::into_raw(region)

0 commit comments

Comments
 (0)