1 //! Server-side handles and storage for per-handle data.
3 use std::collections::{BTreeMap, HashMap};
5 use std::num::NonZeroU32;
6 use std::ops::{Index, IndexMut};
7 use std::sync::atomic::{AtomicUsize, Ordering};
9 pub(super) type Handle = NonZeroU32;
11 pub(super) struct OwnedStore<T: 'static> {
12 counter: &'static AtomicUsize,
13 data: BTreeMap<Handle, T>,
16 impl<T> OwnedStore<T> {
17 pub(super) fn new(counter: &'static AtomicUsize) -> Self {
18 // Ensure the handle counter isn't 0, which would panic later,
19 // when `NonZeroU32::new` (aka `Handle::new`) is called in `alloc`.
20 assert_ne!(counter.load(Ordering::SeqCst), 0);
24 data: BTreeMap::new(),
29 impl<T> OwnedStore<T> {
30 pub(super) fn alloc(&mut self, x: T) -> Handle {
31 let counter = self.counter.fetch_add(1, Ordering::SeqCst);
32 let handle = Handle::new(counter as u32).expect("`proc_macro` handle counter overflowed");
33 assert!(self.data.insert(handle, x).is_none());
37 pub(super) fn take(&mut self, h: Handle) -> T {
40 .expect("use-after-free in `proc_macro` handle")
44 impl<T> Index<Handle> for OwnedStore<T> {
46 fn index(&self, h: Handle) -> &T {
49 .expect("use-after-free in `proc_macro` handle")
53 impl<T> IndexMut<Handle> for OwnedStore<T> {
54 fn index_mut(&mut self, h: Handle) -> &mut T {
57 .expect("use-after-free in `proc_macro` handle")
61 pub(super) struct InternedStore<T: 'static> {
63 interner: HashMap<T, Handle>,
66 impl<T: Copy + Eq + Hash> InternedStore<T> {
67 pub(super) fn new(counter: &'static AtomicUsize) -> Self {
69 owned: OwnedStore::new(counter),
70 interner: HashMap::new(),
74 pub(super) fn alloc(&mut self, x: T) -> Handle {
75 let owned = &mut self.owned;
76 *self.interner.entry(x).or_insert_with(|| owned.alloc(x))
79 pub(super) fn copy(&mut self, h: Handle) -> T {