Skip to main content

ghast_protocol/
intern.rs

1//! Process-wide sharing of immutable data that every connection to the same server receives
2//! identically (registry names, tags, recipes, the command tree). Many clients in one process
3//! then hold one copy instead of one each. Values are matched by content when they are stored
4//! (once per join, under a lock); reads go through the `Arc` / [`Bytes`] taken then and never
5//! touch the pool. An entry lives as long as something holds it.
6
7use std::any::{Any, TypeId};
8use std::collections::HashMap;
9use std::hash::{BuildHasher, Hash, RandomState};
10use std::sync::{Arc, Mutex, OnceLock, PoisonError, Weak};
11
12use bytes::Bytes;
13
14type Key = (TypeId, u64);
15
16struct Pool {
17    hasher: RandomState,
18    entries: HashMap<Key, Weak<dyn Any + Send + Sync>>,
19    /// Dead entries are dropped when the map reaches this size.
20    prune_at: usize,
21}
22
23fn pool() -> &'static Mutex<Pool> {
24    static POOL: OnceLock<Mutex<Pool>> = OnceLock::new();
25    POOL.get_or_init(|| {
26        Mutex::new(Pool {
27            hasher: RandomState::new(),
28            entries: HashMap::new(),
29            prune_at: 64,
30        })
31    })
32}
33
34/// The process's shared copy of `value` (an equal value stored earlier and still alive), or
35/// `value` itself, which later equal values then share. Costs a hash of `value` and a lock:
36/// meant for data stored once per connection, not per packet.
37pub fn shared<T: Hash + Eq + Send + Sync + 'static>(value: T) -> Arc<T> {
38    let mut pool = pool().lock().unwrap_or_else(PoisonError::into_inner);
39    let key = (TypeId::of::<T>(), pool.hasher.hash_one(&value));
40    if let Some(old) = pool.entries.get(&key).and_then(Weak::upgrade)
41        && let Ok(old) = old.downcast::<T>()
42        && *old == value
43    {
44        return old;
45    }
46    // New, dead or a hash collision (then the newer value is the one shared from now on).
47    let new = Arc::new(value);
48    let weak: Weak<dyn Any + Send + Sync> = Arc::downgrade(&new) as _;
49    pool.entries.insert(key, weak);
50    if pool.entries.len() >= pool.prune_at {
51        pool.entries.retain(|_, w| w.strong_count() > 0);
52        pool.prune_at = (pool.entries.len() * 2).max(64);
53    }
54    new
55}
56
57/// Bytes owned by a shared allocation.
58struct Owner(Arc<Box<[u8]>>);
59
60impl AsRef<[u8]> for Owner {
61    fn as_ref(&self) -> &[u8] {
62        &self.0
63    }
64}
65
66/// `data` as [`Bytes`] backed by the process's shared copy of these bytes.
67pub fn bytes(data: &[u8]) -> Bytes {
68    if data.is_empty() {
69        return Bytes::new();
70    }
71    Bytes::from_owner(Owner(shared(Box::<[u8]>::from(data))))
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77
78    #[test]
79    fn equal_values_share_one_allocation() {
80        let a = shared(vec!["minecraft:a".to_string(), "minecraft:b".to_string()]);
81        let b = shared(vec!["minecraft:a".to_string(), "minecraft:b".to_string()]);
82        assert!(Arc::ptr_eq(&a, &b));
83        let c = shared(vec!["minecraft:a".to_string()]);
84        assert!(!Arc::ptr_eq(&a, &c));
85        // Same content, other type: not shared.
86        let d = shared(vec![String::from("minecraft:a")].into_boxed_slice());
87        assert_eq!(d.len(), 1);
88
89        let x = bytes(b"tags of one server");
90        let y = bytes(b"tags of one server");
91        assert_eq!(x.as_ptr(), y.as_ptr());
92        assert_eq!(&x[..], b"tags of one server");
93        assert_ne!(bytes(b"other tags").as_ptr(), x.as_ptr());
94    }
95
96    #[test]
97    fn an_entry_ends_with_its_last_holder() {
98        let v = vec![7u64, 8, 9];
99        let a = shared(v.clone());
100        let weak = Arc::downgrade(&a);
101        drop(a);
102        assert!(weak.upgrade().is_none());
103        // Built again from scratch.
104        let b = shared(v);
105        assert_eq!(*b, [7, 8, 9]);
106    }
107}