From 54988eb2399c889fb82926c1508bb0ec31bedba2 Mon Sep 17 00:00:00 2001 From: Taiki Endo Date: Sun, 15 Dec 2024 23:27:35 +0900 Subject: [PATCH] Calculate layout in const context --- crossbeam-channel/src/flavors/list.rs | 12 ++++++++---- crossbeam-deque/src/deque.rs | 12 ++++++++---- crossbeam-queue/src/seg_queue.rs | 12 ++++++++---- 3 files changed, 24 insertions(+), 12 deletions(-) diff --git a/crossbeam-channel/src/flavors/list.rs b/crossbeam-channel/src/flavors/list.rs index 9f2e55258..6c15991f9 100644 --- a/crossbeam-channel/src/flavors/list.rs +++ b/crossbeam-channel/src/flavors/list.rs @@ -72,18 +72,22 @@ struct Block { } impl Block { - /// Creates an empty block. - fn new() -> Box { + const LAYOUT: Layout = { let layout = Layout::new::(); assert!( layout.size() != 0, "Block should never be zero-sized, as it has an AtomicPtr field" ); + layout + }; + + /// Creates an empty block. + fn new() -> Box { // 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. diff --git a/crossbeam-deque/src/deque.rs b/crossbeam-deque/src/deque.rs index 27354e09e..84ba0b8c0 100644 --- a/crossbeam-deque/src/deque.rs +++ b/crossbeam-deque/src/deque.rs @@ -1225,18 +1225,22 @@ struct Block { } impl Block { - /// Creates an empty block. - fn new() -> Box { + const LAYOUT: Layout = { let layout = Layout::new::(); assert!( layout.size() != 0, "Block should never be zero-sized, as it has an AtomicPtr field" ); + layout + }; + + /// Creates an empty block. + fn new() -> Box { // 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. diff --git a/crossbeam-queue/src/seg_queue.rs b/crossbeam-queue/src/seg_queue.rs index 68197e896..ad8f9c1ab 100644 --- a/crossbeam-queue/src/seg_queue.rs +++ b/crossbeam-queue/src/seg_queue.rs @@ -58,18 +58,22 @@ struct Block { } impl Block { - /// Creates an empty block. - fn new() -> Box { + const LAYOUT: Layout = { let layout = Layout::new::(); assert!( layout.size() != 0, "Block should never be zero-sized, as it has an AtomicPtr field" ); + layout + }; + + /// Creates an empty block. + fn new() -> Box { // 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.