@@ -6,9 +6,7 @@ use std::env;
6
6
use std:: fmt;
7
7
use std:: hash:: { Hash , Hasher } ;
8
8
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 ;
12
10
13
11
use crate :: ast;
14
12
use proc_macro2:: { self , Ident } ;
@@ -133,13 +131,12 @@ pub fn wrap_import_function(function: ast::ImportFunction) -> ast::Import {
133
131
pub struct ShortHash < T > ( pub T ) ;
134
132
135
133
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 ( ) ;
139
136
140
137
// Try to amortize the cost of loading env vars a lot as we're gonna be
141
138
// hashing for a lot of symbols.
142
- if ! HASHED . load ( SeqCst ) {
139
+ let seed = * HASH_SEED . get_or_init ( || {
143
140
let mut h = DefaultHasher :: new ( ) ;
144
141
env:: var ( "CARGO_PKG_NAME" )
145
142
. expect ( "should have CARGO_PKG_NAME env var" )
@@ -149,13 +146,24 @@ impl<T: Hash> fmt::Display for ShortHash<T> {
149
146
. hash ( & mut h) ;
150
147
// This may chop off 32 bits on 32-bit platforms, but that's ok, we
151
148
// 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
+ } ) ;
155
151
156
152
let mut h = DefaultHasher :: new ( ) ;
157
- HASH . load ( SeqCst ) . hash ( & mut h) ;
153
+ seed . hash ( & mut h) ;
158
154
self . 0 . hash ( & mut h) ;
159
155
write ! ( f, "{:016x}" , h. finish( ) )
160
156
}
161
157
}
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