|
| 1 | +use std::collections::hash_map::DefaultHasher; |
| 2 | +use std::env; |
| 3 | +use std::fmt; |
| 4 | +use std::hash::{Hash, Hasher}; |
1 | 5 | use std::iter::FromIterator;
|
| 6 | +use std::sync::atomic::Ordering::SeqCst; |
| 7 | +use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT}; |
| 8 | +use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT}; |
2 | 9 |
|
3 | 10 | use ast;
|
4 | 11 | use proc_macro2::{self, Ident};
|
@@ -88,3 +95,37 @@ pub fn wrap_import_function(function: ast::ImportFunction) -> ast::Import {
|
88 | 95 | kind: ast::ImportKind::Function(function),
|
89 | 96 | }
|
90 | 97 | }
|
| 98 | + |
| 99 | +/// Small utility used when generating symbol names. |
| 100 | +/// |
| 101 | +/// Hashes the public field here along with a few cargo-set env vars to |
| 102 | +/// distinguish between runs of the procedural macro. |
| 103 | +pub struct ShortHash<T>(pub T); |
| 104 | + |
| 105 | +impl<T: Hash> fmt::Display for ShortHash<T> { |
| 106 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 107 | + static HASHED: AtomicBool = ATOMIC_BOOL_INIT; |
| 108 | + static HASH: AtomicUsize = ATOMIC_USIZE_INIT; |
| 109 | + |
| 110 | + // Try to amortize the cost of loading env vars a lot as we're gonna be |
| 111 | + // hashing for a lot of symbols. |
| 112 | + if !HASHED.load(SeqCst) { |
| 113 | + let mut h = DefaultHasher::new(); |
| 114 | + env::var("CARGO_PKG_NAME") |
| 115 | + .expect("should have CARGO_PKG_NAME env var") |
| 116 | + .hash(&mut h); |
| 117 | + env::var("CARGO_PKG_VERSION") |
| 118 | + .expect("should have CARGO_PKG_VERSION env var") |
| 119 | + .hash(&mut h); |
| 120 | + // This may chop off 32 bits on 32-bit platforms, but that's ok, we |
| 121 | + // just want something to mix in below anyway. |
| 122 | + HASH.store(h.finish() as usize, SeqCst); |
| 123 | + HASHED.store(true, SeqCst); |
| 124 | + } |
| 125 | + |
| 126 | + let mut h = DefaultHasher::new(); |
| 127 | + HASH.load(SeqCst).hash(&mut h); |
| 128 | + self.0.hash(&mut h); |
| 129 | + write!(f, "{:016x}", h.finish()) |
| 130 | + } |
| 131 | +} |
0 commit comments