1 //! lib-proc-macro Server-side handles and storage for per-handle data.
3 //! Copy from https://github.com/rust-lang/rust/blob/6050e523bae6de61de4e060facc43dc512adaccd/src/libproc_macro/bridge/handle.rs
4 //! augmented with removing unstable features
6 use std::collections::{BTreeMap, HashMap};
8 use std::num::NonZeroU32;
9 use std::ops::{Index, IndexMut};
10 use std::sync::atomic::{AtomicUsize, Ordering};
12 pub(super) type Handle = NonZeroU32;
14 pub(super) struct OwnedStore<T: 'static> {
15 counter: &'static AtomicUsize,
16 data: BTreeMap<Handle, T>,
19 impl<T> OwnedStore<T> {
20 pub(super) fn new(counter: &'static AtomicUsize) -> Self {
21 // Ensure the handle counter isn't 0, which would panic later,
22 // when `NonZeroU32::new` (aka `Handle::new`) is called in `alloc`.
23 assert_ne!(counter.load(Ordering::SeqCst), 0);
25 OwnedStore { counter, 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 {
38 self.data.remove(&h).expect("use-after-free in `proc_macro` handle")
42 impl<T> Index<Handle> for OwnedStore<T> {
44 fn index(&self, h: Handle) -> &T {
45 self.data.get(&h).expect("use-after-free in `proc_macro` handle")
49 impl<T> IndexMut<Handle> for OwnedStore<T> {
50 fn index_mut(&mut self, h: Handle) -> &mut T {
51 self.data.get_mut(&h).expect("use-after-free in `proc_macro` handle")
55 pub(super) struct InternedStore<T: 'static> {
57 interner: HashMap<T, Handle>,
60 impl<T: Copy + Eq + Hash> InternedStore<T> {
61 pub(super) fn new(counter: &'static AtomicUsize) -> Self {
62 InternedStore { owned: OwnedStore::new(counter), interner: HashMap::new() }
65 pub(super) fn alloc(&mut self, x: T) -> Handle {
66 let owned = &mut self.owned;
67 *self.interner.entry(x).or_insert_with(|| owned.alloc(x))
70 pub(super) fn copy(&mut self, h: Handle) -> T {