From bfdbf20a813bb4b5527a3d6ff4a5c1bac134b466 Mon Sep 17 00:00:00 2001 From: Mica White Date: Wed, 25 Dec 2024 17:11:12 -0500 Subject: Remove once_cell and thread_local dependencies --- Cargo.toml | 4 +--- src/key.rs | 21 ++++++++++----------- 2 files changed, 11 insertions(+), 14 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 4930fb4..b7d06ba 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ name = "happylock" version = "0.3.0" authors = ["Mica White "] edition = "2021" -rust-version = "1.65" +rust-version = "1.80" description = "Free deadlock prevention" documentation = "https://docs.rs/happylock" readme = "README.md" @@ -13,8 +13,6 @@ keywords = ["deadlock", "mutex", "rwlock"] categories = ["concurrency"] [dependencies] -thread_local = "1" -once_cell = "1" lock_api = "0.4" parking_lot = { version = "0.12", optional = true } spin = { version = "0.9", optional = true } diff --git a/src/key.rs b/src/key.rs index 654979d..589f411 100644 --- a/src/key.rs +++ b/src/key.rs @@ -1,9 +1,7 @@ use std::cell::Cell; use std::fmt::{self, Debug}; use std::marker::PhantomData; - -use once_cell::sync::Lazy; -use thread_local::ThreadLocal; +use std::sync::LazyLock; use sealed::Sealed; @@ -17,10 +15,9 @@ mod sealed { impl Sealed for &mut ThreadKey {} } -// I am concerned that having multiple crates linked together with different -// static variables could break my key system. Library code probably shouldn't -// be creating keys at all. -static KEY: Lazy> = Lazy::new(ThreadLocal::new); +thread_local! { + static KEY: LazyLock = LazyLock::new(KeyCell::default); +} /// The key for the current thread. /// @@ -53,7 +50,7 @@ impl Drop for ThreadKey { fn drop(&mut self) { // safety: a thread key cannot be acquired without creating the lock // safety: the key is lost, so it's safe to unlock the cell - unsafe { KEY.get().unwrap_unchecked().force_unlock() } + unsafe { KEY.with(|key| key.force_unlock()) } } } @@ -76,8 +73,10 @@ impl ThreadKey { // safety: we just acquired the lock // safety: if this code changes, check to ensure the requirement for // the Drop implementation is still true - KEY.get_or_default().try_lock().then_some(Self { - phantom: PhantomData, + KEY.with(|key| { + key.try_lock().then_some(Self { + phantom: PhantomData, + }) }) } } @@ -91,7 +90,7 @@ struct KeyCell { impl KeyCell { /// Attempt to lock the `KeyCell`. This is not a fair lock. #[must_use] - pub fn try_lock(&'static self) -> bool { + pub fn try_lock(&self) -> bool { !self.is_locked.replace(true) } -- cgit v1.2.3