From 210c923359a11edc4e1a2c3fbd6fbfa6d1534796 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=A0=20/=20green?= Date: Fri, 13 Dec 2024 18:08:43 +0900 Subject: [PATCH] refactor: replace UnsafeCell with RefCell (#346) There's a slight cost of the runtime borrow check but I guess it's negligible. --- src/cache.rs | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/src/cache.rs b/src/cache.rs index dea09aed..20ddff71 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -1,6 +1,6 @@ use std::{ borrow::Cow, - cell::UnsafeCell, + cell::RefCell, convert::AsRef, hash::{BuildHasherDefault, Hash, Hasher}, io, @@ -27,7 +27,7 @@ static THREAD_COUNT: AtomicU64 = AtomicU64::new(1); thread_local! { /// Per-thread pre-allocated path that is used to perform operations on paths more quickly. /// Learned from parcel - pub static SCRATCH_PATH: UnsafeCell = UnsafeCell::new(PathBuf::with_capacity(256)); + pub static SCRATCH_PATH: RefCell = RefCell::new(PathBuf::with_capacity(256)); pub static THREAD_ID: u64 = THREAD_COUNT.fetch_add(1, Ordering::SeqCst); } @@ -382,9 +382,7 @@ impl CachedPath { } pub fn add_extension(&self, ext: &str, cache: &Cache) -> Self { - SCRATCH_PATH.with(|path| { - // SAFETY: ??? - let path = unsafe { &mut *path.get() }; + SCRATCH_PATH.with_borrow_mut(|path| { path.clear(); let s = path.as_mut_os_string(); s.push(self.path.as_os_str()); @@ -394,9 +392,7 @@ impl CachedPath { } pub fn replace_extension(&self, ext: &str, cache: &Cache) -> Self { - SCRATCH_PATH.with(|path| { - // SAFETY: ??? - let path = unsafe { &mut *path.get() }; + SCRATCH_PATH.with_borrow_mut(|path| { path.clear(); let s = path.as_mut_os_string(); let self_len = self.path.as_os_str().len(); @@ -423,9 +419,7 @@ impl CachedPath { if matches!(head, Component::Prefix(..) | Component::RootDir) { return cache.value(subpath); } - SCRATCH_PATH.with(|path| { - // SAFETY: ??? - let path = unsafe { &mut *path.get() }; + SCRATCH_PATH.with_borrow_mut(|path| { path.clear(); path.push(&self.path); for component in std::iter::once(head).chain(components) {