1use 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 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
34pub 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 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
57struct Owner(Arc<Box<[u8]>>);
59
60impl AsRef<[u8]> for Owner {
61 fn as_ref(&self) -> &[u8] {
62 &self.0
63 }
64}
65
66pub 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 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 let b = shared(v);
105 assert_eq!(*b, [7, 8, 9]);
106 }
107}