Skip to content

Commit

Permalink
More correct buffer allocation
Browse files Browse the repository at this point in the history
The current one does not cause real problems at this time because the
size allocated is large enough, but it's better to use the more correct
one.
  • Loading branch information
taiki-e committed Jan 8, 2024
1 parent 7389cdf commit 5a15fc2
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
16 changes: 12 additions & 4 deletions crossbeam-deque/src/deque.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ use std::cell::{Cell, UnsafeCell};
use std::cmp;
use std::fmt;
use std::marker::PhantomData;
use std::mem::{self, ManuallyDrop, MaybeUninit};
use std::mem::{self, MaybeUninit};
use std::ptr;
use std::slice;
use std::sync::atomic::{self, AtomicIsize, AtomicPtr, AtomicUsize, Ordering};
use std::sync::Arc;

Expand Down Expand Up @@ -37,15 +38,22 @@ impl<T> Buffer<T> {
fn alloc(cap: usize) -> Buffer<T> {
debug_assert_eq!(cap, cap.next_power_of_two());

let mut v = ManuallyDrop::new(Vec::with_capacity(cap));
let ptr = v.as_mut_ptr();
let ptr = Box::into_raw(
(0..cap)
.map(|_| MaybeUninit::<T>::uninit())
.collect::<Box<[_]>>(),
)
.cast::<T>();

Buffer { ptr, cap }
}

/// Deallocates the buffer.
unsafe fn dealloc(self) {
drop(Vec::from_raw_parts(self.ptr, 0, self.cap));
drop(Box::from_raw(slice::from_raw_parts_mut(
self.ptr.cast::<MaybeUninit<T>>(),
self.cap,
)));
}

/// Returns a pointer to the task at the specified `index`.
Expand Down
5 changes: 3 additions & 2 deletions crossbeam-epoch/src/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -403,9 +403,10 @@ mod tests {
}

let len = v.len();
let ptr = ManuallyDrop::new(v).as_mut_ptr() as usize;
let cap = v.capacity();
let ptr = ManuallyDrop::new(v).as_mut_ptr();
guard.defer_unchecked(move || {
drop(Vec::from_raw_parts(ptr as *const i32 as *mut i32, len, len));
drop(Vec::from_raw_parts(ptr, len, cap));
DESTROYS.fetch_add(len, Ordering::Relaxed);
});
guard.flush();
Expand Down

0 comments on commit 5a15fc2

Please sign in to comment.