From 698f8c2f01ea549d77d7dc3338a12e04c11057b9 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Wed, 17 Apr 2024 14:02:58 +0200 Subject: Adding upstream version 1.64.0+dfsg1. Signed-off-by: Daniel Baumann --- library/proc_macro/src/bridge/handle.rs | 75 +++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 library/proc_macro/src/bridge/handle.rs (limited to 'library/proc_macro/src/bridge/handle.rs') diff --git a/library/proc_macro/src/bridge/handle.rs b/library/proc_macro/src/bridge/handle.rs new file mode 100644 index 000000000..00954107b --- /dev/null +++ b/library/proc_macro/src/bridge/handle.rs @@ -0,0 +1,75 @@ +//! Server-side handles and storage for per-handle data. + +use std::collections::BTreeMap; +use std::hash::Hash; +use std::num::NonZeroU32; +use std::ops::{Index, IndexMut}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use super::fxhash::FxHashMap; + +pub(super) type Handle = NonZeroU32; + +/// A store that associates values of type `T` with numeric handles. A value can +/// be looked up using its handle. +pub(super) struct OwnedStore { + counter: &'static AtomicUsize, + data: BTreeMap, +} + +impl OwnedStore { + pub(super) fn new(counter: &'static AtomicUsize) -> Self { + // Ensure the handle counter isn't 0, which would panic later, + // when `NonZeroU32::new` (aka `Handle::new`) is called in `alloc`. + assert_ne!(counter.load(Ordering::SeqCst), 0); + + OwnedStore { counter, data: BTreeMap::new() } + } +} + +impl OwnedStore { + pub(super) fn alloc(&mut self, x: T) -> Handle { + let counter = self.counter.fetch_add(1, Ordering::SeqCst); + let handle = Handle::new(counter as u32).expect("`proc_macro` handle counter overflowed"); + assert!(self.data.insert(handle, x).is_none()); + handle + } + + pub(super) fn take(&mut self, h: Handle) -> T { + self.data.remove(&h).expect("use-after-free in `proc_macro` handle") + } +} + +impl Index for OwnedStore { + type Output = T; + fn index(&self, h: Handle) -> &T { + self.data.get(&h).expect("use-after-free in `proc_macro` handle") + } +} + +impl IndexMut for OwnedStore { + fn index_mut(&mut self, h: Handle) -> &mut T { + self.data.get_mut(&h).expect("use-after-free in `proc_macro` handle") + } +} + +/// Like `OwnedStore`, but avoids storing any value more than once. +pub(super) struct InternedStore { + owned: OwnedStore, + interner: FxHashMap, +} + +impl InternedStore { + pub(super) fn new(counter: &'static AtomicUsize) -> Self { + InternedStore { owned: OwnedStore::new(counter), interner: FxHashMap::default() } + } + + pub(super) fn alloc(&mut self, x: T) -> Handle { + let owned = &mut self.owned; + *self.interner.entry(x).or_insert_with(|| owned.alloc(x)) + } + + pub(super) fn copy(&mut self, h: Handle) -> T { + self.owned[h] + } +} -- cgit v1.2.3