1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
use core::{borrow::Borrow, hash::Hash};
use crate::{Site, Symbol};
use hashbrown::{HashMap, hash_map};
#[cfg(feature = "alloc")]
use alloc::{borrow::ToOwned, boxed::Box};
#[cfg(not(any(feature = "std", feature = "critical-section")))]
compile_error!("Either the `std` or `critical-section` feature must be enabled");
#[cfg(not(any(feature = "std", feature = "spin")))]
compile_error!("Either the `std` or `spin` feature must be enabled");
#[cfg(feature = "spin")]
use spin::{RwLock, RwLockReadGuard, RwLockWriteGuard};
#[cfg(not(feature = "spin"))]
use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
#[cfg(feature = "critical-section")]
use once_cell::sync::OnceCell as OnceLock;
#[cfg(not(feature = "critical-section"))]
use std::sync::OnceLock;
/// Helper to control the behavior of symbol strings in the registry's hash map.
#[derive(Clone, Copy, PartialEq, Eq)]
struct SymbolStr(&'static &'static str);
impl SymbolStr {
#[inline]
fn address(&self) -> usize {
core::ptr::from_ref::<&'static str>(self.0) as usize
}
}
impl Borrow<str> for SymbolStr {
#[inline]
fn borrow(&self) -> &str {
self.0
}
}
impl Hash for SymbolStr {
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
(*self.0).hash(state);
}
}
#[cfg(feature = "alloc")]
impl From<&str> for SymbolStr {
#[inline]
fn from(value: &str) -> Self {
let value = &*Box::leak(Box::new(&*value.to_owned().leak()));
Self(value)
}
}
/// The global symbol registry.
///
/// This is available for advanced use cases, such as bulk-insertion of many
/// symbols.
pub struct Registry {
#[cfg(not(feature = "spin"))]
store: std::sync::RwLock<Store>,
#[cfg(feature = "spin")]
store: spin::RwLock<Store>,
}
#[derive(Default)]
pub(crate) struct Store {
by_string: HashMap<SymbolStr, ()>,
by_pointer: HashMap<usize, SymbolStr>,
}
/// Symbol registry read lock guard
pub struct RegistryReadGuard {
// Note: Either `std` or `spin`.
guard: RwLockReadGuard<'static, Store>,
}
/// Symbol registry write lock guard
pub struct RegistryWriteGuard {
// Note: Either `std` or `spin`.
guard: RwLockWriteGuard<'static, Store>,
}
impl Registry {
#[inline]
fn new() -> Self {
Self {
store: RwLock::default(),
}
}
/// Get the global registry.
pub fn global() -> &'static Registry {
static REGISTRY: OnceLock<Registry> = OnceLock::new();
REGISTRY.get_or_init(Registry::new)
}
/// Acquire a global read lock of the registry's data.
///
/// New symbols cannot be created while the read lock is held, but acquiring
/// the lock does not prevent other threads from accessing the string
/// representation of a [`Symbol`].
#[inline]
pub fn read(&'static self) -> RegistryReadGuard {
RegistryReadGuard {
#[cfg(not(feature = "spin"))]
guard: self
.store
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner),
#[cfg(feature = "spin")]
guard: self.store.read(),
}
}
/// Acquire a global write lock of the registry's data.
///
/// Note that acquiring this lock does not prevent other threads from
/// reading the string representation of a [`Symbol`].
#[inline]
pub fn write(&'static self) -> RegistryWriteGuard {
RegistryWriteGuard {
#[cfg(not(feature = "spin"))]
guard: self
.store
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner),
#[cfg(feature = "spin")]
guard: self.store.write(),
}
}
/// Resolve and register symbols from a table.
///
/// You should never need to call this function manually.
///
/// Using the [`stringleton::enable!()`](../stringleton/macro.enable.html)
/// causes this to be called with the symbols from the current crate in a
/// static initializer function.
///
/// # Safety
///
/// `table` must not be accessed from any other thread. This is ensured when
/// this function is called as part of a static initializer function.
pub unsafe fn register_sites(table: &[Site]) {
unsafe {
Registry::global().write().register_sites(table);
}
}
/// Check if the registry contains a symbol matching `string` and return it
/// if so.
#[must_use]
#[inline]
pub fn get(&'static self, string: &str) -> Option<Symbol> {
self.read().guard.get(string)
}
/// Get the existing symbol for `string`, or insert a new one.
///
/// This opportunistically takes a read lock to check if the symbol exists,
/// and only takes a write lock if it doesn't.
///
/// If you are inserting many new symbols, prefer acquiring the write lock
/// by calling [`write()`](Self::write) and then repeatedly call
/// [`RegistryWriteGuard::get_or_insert()`].
#[cfg(any(feature = "std", feature = "alloc"))]
#[must_use]
pub fn get_or_insert(&'static self, string: &str) -> Symbol {
let read = self.read();
if let Some(previously_interned) = read.get(string) {
return previously_interned;
}
core::mem::drop(read);
let mut write = self.write();
write.get_or_insert(string)
}
/// Get the existing symbol for `string`, or insert a new one.
///
/// This variant is slightly more efficient than
/// [`get_or_insert()`](Self::get_or_insert), because it can reuse the
/// storage of `string` directly for this symbol. In other words, if this
/// call inserted the symbol, the returned [`Symbol`] will be backed by
/// `string`, and no additional allocations will have happened.
///
/// This opportunistically takes a read lock to check if the symbol exists,
/// and only takes a write lock if it doesn't.
///
/// If you are inserting many new symbols, prefer acquiring the write lock
/// by calling [`write()`](Self::write) and then repeatedly call
/// [`RegistryWriteGuard::get_or_insert_static()`].
#[inline]
#[must_use]
pub fn get_or_insert_static(&'static self, string: &'static &'static str) -> Symbol {
let read = self.read();
if let Some(previously_interned) = read.get(string) {
return previously_interned;
}
core::mem::drop(read);
let mut write = self.write();
write.get_or_insert_static(string)
}
/// Check if a symbol has been registered at `address` (i.e., it has been
/// produced by [`Symbol::to_ffi()`]), and return the symbol if so.
///
/// This can be used to verify symbols that have made a round-trip over an
/// FFI boundary.
#[inline]
#[must_use]
pub fn get_by_address(&'static self, address: u64) -> Option<Symbol> {
self.read().get_by_address(address)
}
}
impl Store {
#[cfg(any(feature = "std", feature = "alloc"))]
pub fn get_or_insert(&mut self, string: &str) -> Symbol {
let entry;
match self.by_string.entry_ref(string) {
hash_map::EntryRef::Occupied(e) => entry = e,
hash_map::EntryRef::Vacant(e) => {
// This calls `SymbolStr::from(string)`, which does the leaking.
entry = e.insert_entry(());
let interned = entry.key();
self.by_pointer.insert(interned.address(), *interned);
}
}
unsafe {
// SAFETY: We are the registry.
Symbol::new_unchecked(entry.key().0)
}
}
/// Fast-path for `&'static &'static str` without needing to allocate and
/// leak some boxes. This is what gets called by the `sym!()` macro.
pub fn get_or_insert_static(&mut self, string: &'static &'static str) -> Symbol {
// Caution: Creating a non-interned `SymbolStr` for the purpose of hash
// table lookup.
let symstr = SymbolStr(string);
let interned = match self.by_string.entry(symstr) {
hash_map::Entry::Occupied(entry) => *entry.key(), // Getting the original key.
hash_map::Entry::Vacant(entry) => {
let key = *entry.insert_entry(()).key();
self.by_pointer.insert(key.address(), key);
key
}
};
unsafe {
// SAFETY: We are the registry.
Symbol::new_unchecked(interned.0)
}
}
pub fn get(&self, string: &str) -> Option<Symbol> {
self.by_string
.get_key_value(string)
.map(|(symstr, ())| unsafe {
// SAFETY: We are the registry.
Symbol::new_unchecked(symstr.0)
})
}
#[allow(clippy::cast_possible_truncation)] // We don't have 128-bit pointers
pub fn get_by_address(&self, address: u64) -> Option<Symbol> {
self.by_pointer
.get(&(address as usize))
.map(|symstr| unsafe {
// SAFETY: We are the registry.
Symbol::new_unchecked(symstr.0)
})
}
}
impl RegistryReadGuard {
/// Get the number of registered symbols.
#[inline]
#[must_use]
pub fn len(&self) -> usize {
self.guard.by_string.len()
}
/// Whether or not any symbols are present in the registry.
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.guard.by_string.is_empty()
}
/// Check if the registry contains a symbol matching `string` and return it
/// if so.
///
/// This is a simple hash table lookup.
#[inline]
#[must_use]
pub fn get(&self, string: &str) -> Option<Symbol> {
self.guard.get(string)
}
/// Check if a symbol has been registered at `address` (i.e., it has been
/// produced by [`Symbol::to_ffi()`]), and return the symbol if so.
///
/// This can be used to verify symbols that have made a round-trip over an
/// FFI boundary.
#[inline]
#[must_use]
pub fn get_by_address(&self, address: u64) -> Option<Symbol> {
self.guard.get_by_address(address)
}
}
impl RegistryWriteGuard {
unsafe fn register_sites(&mut self, sites: &[Site]) {
unsafe {
for registration in sites {
let string = registration.get_string();
let interned = self.guard.get_or_insert_static(string);
// Place the interned string pointer at the site and mark it as
// initialized.
registration.initialize(interned);
}
}
}
/// Get the number of registered symbols.
#[inline]
#[must_use]
pub fn len(&self) -> usize {
self.guard.by_string.len()
}
/// Whether or not any symbols are present in the registry.
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.guard.by_string.is_empty()
}
#[inline]
#[must_use]
pub fn get(&self, string: &str) -> Option<Symbol> {
self.guard.get(string)
}
/// Check if a symbol has been registered at `address` (i.e., it has been
/// produced by [`Symbol::to_ffi()`]), and return the symbol if so.
///
/// This can be used to verify symbols that have made a round-trip over an
/// FFI boundary.
#[inline]
#[must_use]
pub fn get_by_address(&self, address: u64) -> Option<Symbol> {
self.guard.get_by_address(address)
}
/// Get the existing symbol for `string`, or insert a new one.
#[inline]
#[must_use]
#[cfg(feature = "alloc")]
pub fn get_or_insert(&mut self, string: &str) -> Symbol {
self.guard.get_or_insert(string)
}
/// Get the existing symbol for `string`, or insert a new one.
///
/// This variant is slightly more efficient than
/// [`get_or_insert()`](Self::get_or_insert), because it can reuse the
/// storage of `string` directly for this symbol. In other words, if this
/// call inserted the symbol, the returned [`Symbol`] will be backed by
/// `string`, and no additional allocations will have happened.
#[inline]
#[must_use]
pub fn get_or_insert_static(&mut self, string: &'static &'static str) -> Symbol {
self.guard.get_or_insert_static(string)
}
}