From 3d70d06db993c7787dba01c35d8b32d284810df4 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Wed, 29 Jan 2025 10:47:17 +0100 Subject: [PATCH] Make Vec and BTreeMap constructors const fns --- src/map.rs | 4 ++-- src/sync.rs | 22 ++++++++++++---------- src/vec.rs | 4 ++-- 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/src/map.rs b/src/map.rs index 7afdcf4..7b7b31d 100644 --- a/src/map.rs +++ b/src/map.rs @@ -311,9 +311,9 @@ pub struct FrozenBTreeMap { // safety: UnsafeCell implies !Sync impl FrozenBTreeMap { - pub fn new() -> Self { + pub const fn new() -> Self { Self { - map: UnsafeCell::new(Default::default()), + map: UnsafeCell::new(BTreeMap::new()), in_use: Cell::new(false), } } diff --git a/src/sync.rs b/src/sync.rs index 351e8c0..f763ca3 100644 --- a/src/sync.rs +++ b/src/sync.rs @@ -473,8 +473,10 @@ impl FrozenVec { } impl FrozenVec { - pub fn new() -> Self { - Default::default() + pub const fn new() -> Self { + Self { + vec: RwLock::new(Vec::new()), + } } // these should never return &T @@ -703,11 +705,7 @@ impl Default for LockFreeFrozenVec { /// Creates an empty `LockFreeFrozenVec` that does not allocate /// any heap allocations until the first time data is pushed to it. fn default() -> Self { - Self { - data: Self::null(), - len: AtomicUsize::new(0), - locked: AtomicBool::new(false), - } + Self::new() } } @@ -716,8 +714,12 @@ impl LockFreeFrozenVec { [const { AtomicPtr::new(std::ptr::null_mut()) }; NUM_BUFFERS] } - pub fn new() -> Self { - Default::default() + pub const fn new() -> Self { + Self { + data: Self::null(), + len: AtomicUsize::new(0), + locked: AtomicBool::new(false), + } } /// Obtains a write lock that ensures other writing threads @@ -1007,7 +1009,7 @@ fn test_non_lockfree() { pub struct FrozenBTreeMap(RwLock>); impl FrozenBTreeMap { - pub fn new() -> Self { + pub const fn new() -> Self { Self(RwLock::new(BTreeMap::new())) } diff --git a/src/vec.rs b/src/vec.rs index f9d36d5..d6e4da3 100644 --- a/src/vec.rs +++ b/src/vec.rs @@ -17,9 +17,9 @@ pub struct FrozenVec { impl FrozenVec { /// Constructs a new, empty vector. - pub fn new() -> Self { + pub const fn new() -> Self { Self { - vec: UnsafeCell::new(Default::default()), + vec: UnsafeCell::new(Vec::new()), } } }