Skip to content

Commit 841f8e1

Browse files
committed
Replace atomic operations with OnceLock in backend/util
1 parent c35cc93 commit 841f8e1

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

crates/backend/src/util.rs

+19-11
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,7 @@ use std::env;
66
use std::fmt;
77
use std::hash::{Hash, Hasher};
88
use std::iter::FromIterator;
9-
use std::sync::atomic::AtomicBool;
10-
use std::sync::atomic::AtomicUsize;
11-
use std::sync::atomic::Ordering::SeqCst;
9+
use std::sync::OnceLock;
1210

1311
use crate::ast;
1412
use proc_macro2::{self, Ident};
@@ -133,13 +131,12 @@ pub fn wrap_import_function(function: ast::ImportFunction) -> ast::Import {
133131
pub struct ShortHash<T>(pub T);
134132

135133
impl<T: Hash> fmt::Display for ShortHash<T> {
136-
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
137-
static HASHED: AtomicBool = AtomicBool::new(false);
138-
static HASH: AtomicUsize = AtomicUsize::new(0);
134+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135+
static HASH_SEED: OnceLock<usize> = OnceLock::new();
139136

140137
// Try to amortize the cost of loading env vars a lot as we're gonna be
141138
// hashing for a lot of symbols.
142-
if !HASHED.load(SeqCst) {
139+
let seed = *HASH_SEED.get_or_init(|| {
143140
let mut h = DefaultHasher::new();
144141
env::var("CARGO_PKG_NAME")
145142
.expect("should have CARGO_PKG_NAME env var")
@@ -149,13 +146,24 @@ impl<T: Hash> fmt::Display for ShortHash<T> {
149146
.hash(&mut h);
150147
// This may chop off 32 bits on 32-bit platforms, but that's ok, we
151148
// just want something to mix in below anyway.
152-
HASH.store(h.finish() as usize, SeqCst);
153-
HASHED.store(true, SeqCst);
154-
}
149+
h.finish() as usize
150+
});
155151

156152
let mut h = DefaultHasher::new();
157-
HASH.load(SeqCst).hash(&mut h);
153+
seed.hash(&mut h);
158154
self.0.hash(&mut h);
159155
write!(f, "{:016x}", h.finish())
160156
}
161157
}
158+
159+
#[cfg(test)]
160+
mod tests {
161+
use super::*;
162+
163+
#[test]
164+
fn test_short_hash_eq() {
165+
let hash = ShortHash("Hello World");
166+
let hash_str = format!("{}", hash);
167+
assert_eq!(&hash_str, "0711bda1e8c6f44a");
168+
}
169+
}

0 commit comments

Comments
 (0)