Skip to content

Commit

Permalink
Calculate layout in const context
Browse files Browse the repository at this point in the history
  • Loading branch information
taiki-e committed Dec 15, 2024
1 parent 761d0b6 commit 54988eb
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 12 deletions.
12 changes: 8 additions & 4 deletions crossbeam-channel/src/flavors/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,18 +72,22 @@ struct Block<T> {
}

impl<T> Block<T> {
/// Creates an empty block.
fn new() -> Box<Self> {
const LAYOUT: Layout = {
let layout = Layout::new::<Self>();
assert!(
layout.size() != 0,
"Block should never be zero-sized, as it has an AtomicPtr field"
);
layout
};

/// Creates an empty block.
fn new() -> Box<Self> {
// SAFETY: layout is not zero-sized
let ptr = unsafe { alloc_zeroed(layout) };
let ptr = unsafe { alloc_zeroed(Self::LAYOUT) };
// Handle allocation failure
if ptr.is_null() {
handle_alloc_error(layout)
handle_alloc_error(Self::LAYOUT)
}
// SAFETY: This is safe because:
// [1] `Block::next` (AtomicPtr) may be safely zero initialized.
Expand Down
12 changes: 8 additions & 4 deletions crossbeam-deque/src/deque.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1225,18 +1225,22 @@ struct Block<T> {
}

impl<T> Block<T> {
/// Creates an empty block.
fn new() -> Box<Self> {
const LAYOUT: Layout = {
let layout = Layout::new::<Self>();
assert!(
layout.size() != 0,
"Block should never be zero-sized, as it has an AtomicPtr field"
);
layout
};

/// Creates an empty block.
fn new() -> Box<Self> {
// SAFETY: layout is not zero-sized
let ptr = unsafe { alloc_zeroed(layout) };
let ptr = unsafe { alloc_zeroed(Self::LAYOUT) };
// Handle allocation failure
if ptr.is_null() {
handle_alloc_error(layout)
handle_alloc_error(Self::LAYOUT)
}
// SAFETY: This is safe because:
// [1] `Block::next` (AtomicPtr) may be safely zero initialized.
Expand Down
12 changes: 8 additions & 4 deletions crossbeam-queue/src/seg_queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,18 +58,22 @@ struct Block<T> {
}

impl<T> Block<T> {
/// Creates an empty block.
fn new() -> Box<Self> {
const LAYOUT: Layout = {
let layout = Layout::new::<Self>();
assert!(
layout.size() != 0,
"Block should never be zero-sized, as it has an AtomicPtr field"
);
layout
};

/// Creates an empty block.
fn new() -> Box<Self> {
// SAFETY: layout is not zero-sized
let ptr = unsafe { alloc_zeroed(layout) };
let ptr = unsafe { alloc_zeroed(Self::LAYOUT) };
// Handle allocation failure
if ptr.is_null() {
handle_alloc_error(layout)
handle_alloc_error(Self::LAYOUT)
}
// SAFETY: This is safe because:
// [1] `Block::next` (AtomicPtr) may be safely zero initialized.
Expand Down

0 comments on commit 54988eb

Please sign in to comment.