1use super::*;
3use std::collections::hash_map::DefaultHasher;
4use std::hash::{BuildHasher, Hash, Hasher};
5
6#[derive(Default)]
7pub(super) struct EntryIndex {
8 next: Cell<u64>,
9 buckets: RefCell<BTreeMap<u64, Vec<(u64, Weak<EntryKey>)>>>,
10}
11pub(super) struct EntryKey {
12 id: u64,
13 hash: u64,
14 value: Rc<dyn Any>,
15 index: Weak<EntryIndex>,
16}
17impl Drop for EntryKey {
18 fn drop(&mut self) {
19 if let Some(index) = self.index.upgrade() {
20 let mut buckets = index.buckets.borrow_mut();
21 if let Some(bucket) = buckets.get_mut(&self.hash) {
22 bucket.retain(|(id, _)| *id != self.id);
23 if bucket.is_empty() {
24 buckets.remove(&self.hash);
25 }
26 }
27 }
28 }
30}
31impl EntryIndex {
32 pub fn stats(&self) -> (usize, usize) {
33 let buckets = self.buckets.borrow();
34 (buckets.values().map(Vec::len).sum(), buckets.len())
35 }
36 fn candidates(&self, hash: u64) -> (Option<Rc<EntryKey>>, Vec<Rc<EntryKey>>) {
37 let buckets = self.buckets.borrow();
38 let Some(bucket) = buckets.get(&hash) else {
39 return (None, Vec::new());
40 };
41 (
42 bucket.first().and_then(|(_, key)| key.upgrade()),
43 bucket
44 .iter()
45 .skip(1)
46 .filter_map(|(_, key)| key.upgrade())
47 .collect(),
48 )
49 }
50 pub(super) fn find<K: Eq + Hash + 'static>(&self, key: &K) -> Result<Option<u64>, AccessError> {
53 let hash = project(|| {
54 let mut hasher = DefaultHasher::new();
55 key.hash(&mut hasher);
56 Ok(hasher.finish())
57 })?;
58 let (first, rest) = self.candidates(hash);
59 for candidate in first.into_iter().chain(rest) {
60 if project(|| {
61 Ok(candidate
62 .value
63 .downcast_ref::<K>()
64 .is_some_and(|old| old == key))
65 })? {
66 return Ok(Some(candidate.id));
67 }
68 }
69 Ok(None)
70 }
71 fn intern<K: Eq + Hash + 'static>(
72 self: &Rc<Self>,
73 key: K,
74 ) -> Result<Rc<EntryKey>, AccessError> {
75 let hash = project(|| {
76 let mut hasher = DefaultHasher::new();
77 key.hash(&mut hasher);
78 Ok(hasher.finish())
79 })?;
80 let (first, rest) = self.candidates(hash);
81 for candidate in first.into_iter().chain(rest) {
84 if project(|| {
85 Ok(candidate
86 .value
87 .downcast_ref::<K>()
88 .is_some_and(|old| old == &key))
89 })? {
90 return Ok(candidate);
91 }
92 }
93 let id = self.next.get();
94 self.next.set(
95 id.checked_add(1)
96 .expect("collection path identity exhausted"),
97 );
98 let key = Rc::new(EntryKey {
99 id,
100 hash,
101 value: Rc::new(key),
102 index: Rc::downgrade(self),
103 });
104 self.buckets
105 .borrow_mut()
106 .entry(hash)
107 .or_default()
108 .push((id, Rc::downgrade(&key)));
109 Ok(key)
110 }
111}
112
113trait Collection: 'static {
114 type Key: 'static;
115 type Value: 'static;
116 fn read(&self, key: &Self::Key) -> Option<&Self::Value>;
117 fn write(&mut self, key: &Self::Key) -> Option<&mut Self::Value>;
118}
119impl<T: 'static> Collection for Vec<T> {
120 type Key = usize;
121 type Value = T;
122 fn read(&self, key: &usize) -> Option<&T> {
123 self.get(*key)
124 }
125 fn write(&mut self, key: &usize) -> Option<&mut T> {
126 self.get_mut(*key)
127 }
128}
129impl<K: Ord + 'static, V: 'static> Collection for BTreeMap<K, V> {
130 type Key = K;
131 type Value = V;
132 fn read(&self, key: &K) -> Option<&V> {
133 self.get(key)
134 }
135 fn write(&mut self, key: &K) -> Option<&mut V> {
136 self.get_mut(key)
137 }
138}
139impl<K: Eq + Hash + 'static, V: 'static, S: BuildHasher + 'static> Collection for HashMap<K, V, S> {
140 type Key = K;
141 type Value = V;
142 fn read(&self, key: &K) -> Option<&V> {
143 self.get(key)
144 }
145 fn write(&mut self, key: &K) -> Option<&mut V> {
146 self.get_mut(key)
147 }
148}
149struct Select<C: Collection> {
150 parent: Option<Rc<dyn Projection>>,
151 key: Rc<dyn Any>,
152 types: PhantomData<fn() -> C>,
153}
154impl<C: Collection> Projection for Select<C> {
155 fn read<'a>(&self, value: &'a dyn Any) -> Result<&'a dyn Any, AccessError> {
156 let value = if let Some(parent) = &self.parent {
157 parent.read(value)?
158 } else {
159 value
160 };
161 let value = value.downcast_ref::<C>().ok_or(AccessError::TypeMismatch)?;
162 let key = self.key.downcast_ref().ok_or(AccessError::TypeMismatch)?;
163 value
164 .read(key)
165 .map(|v| v as &dyn Any)
166 .ok_or(AccessError::MissingField)
167 }
168 fn write<'a>(&self, value: &'a mut dyn Any) -> Result<&'a mut dyn Any, AccessError> {
169 let value = if let Some(parent) = &self.parent {
170 parent.write(value)?
171 } else {
172 value
173 };
174 let value = value.downcast_mut::<C>().ok_or(AccessError::TypeMismatch)?;
175 let key = self.key.downcast_ref().ok_or(AccessError::TypeMismatch)?;
176 value
177 .write(key)
178 .map(|v| v as &mut dyn Any)
179 .ok_or(AccessError::MissingField)
180 }
181}
182fn keyed<C: Collection>(
183 runtime: RuntimeId,
184 source: Key,
185 key: C::Key,
186) -> Result<Cage<C::Value>, AccessError>
187where
188 C::Key: Eq + Hash,
189{
190 let context = Context::new(runtime, source)?;
191 let index = context
192 .state
193 .borrow()
194 .fields
195 .indices
196 .get(&context.parent)
197 .cloned()
198 .unwrap_or_default();
199 let key = index.intern(key)?;
200 let parent = context.path.projection.clone();
201 let value = key.value.clone();
202 context.register(
203 Segment::Entry(key.id),
204 None,
205 move || {
206 Rc::new(Select::<C> {
207 parent,
208 key: value,
209 types: PhantomData,
210 }) as Rc<dyn Projection>
211 },
212 Some((key, index)),
213 )
214}
215
216struct Member<T: 'static> {
219 key: Key,
220 types: PhantomData<fn() -> T>,
221}
222impl<T: 'static> Projection for Member<T> {
223 fn read<'a>(&self, value: &'a dyn Any) -> Result<&'a dyn Any, AccessError> {
224 value
225 .downcast_ref::<Arena<T>>()
226 .ok_or(AccessError::TypeMismatch)?
227 .get(self.key)
228 .map(|v| v as &dyn Any)
229 .ok_or(AccessError::MissingField)
230 }
231 fn write<'a>(&self, value: &'a mut dyn Any) -> Result<&'a mut dyn Any, AccessError> {
232 value
233 .downcast_mut::<Arena<T>>()
234 .ok_or(AccessError::TypeMismatch)?
235 .get_mut(self.key)
236 .map(|v| v as &mut dyn Any)
237 .ok_or(AccessError::MissingField)
238 }
239}
240pub(super) fn keyed_context<T: 'static>(
241 source: Cage<Arena<T>>,
242 key: u64,
243) -> Result<(Context, PathGuard), AccessError> {
244 let context = Context::new(source.handle.runtime, source.handle.key)?;
245 let id = context.canonical::<T>(
246 Segment::Entry(key),
247 None,
248 move || {
249 Rc::new(Member::<T> {
250 key: Key::unpack(key),
251 types: PhantomData,
252 }) as Rc<dyn Projection>
253 },
254 None,
255 )?;
256 let guard = PathGuard {
257 state: context.state.clone(),
258 id,
259 };
260 let path = context.state.borrow().field_path(id)?;
261 Ok((
262 Context {
263 parent: Parent::Field(id),
264 depth: context.depth + 1,
265 path,
266 ..context
267 },
268 guard,
269 ))
270}
271impl<T: 'static> Cage<Vec<T>> {
272 pub fn item(self, index: usize) -> Cage<T> {
277 self.try_item(index)
278 .expect("create a collection position on a live Cage")
279 }
280 pub fn try_item(self, index: usize) -> Result<Cage<T>, AccessError> {
281 let context = Context::new(self.handle.runtime, self.handle.key)?;
282 let parent = context.path.projection.clone();
283 context.register(
284 Segment::Item(index),
285 None,
286 move || {
287 Rc::new(Select::<Vec<T>> {
288 parent,
289 key: Rc::new(index),
290 types: PhantomData,
291 }) as Rc<dyn Projection>
292 },
293 None,
294 )
295 }
296}
297impl<K: Ord + Hash + 'static, V: 'static> Cage<BTreeMap<K, V>> {
298 pub fn entry(self, key: K) -> Cage<V> {
317 self.try_entry(key)
318 .expect("create a map key on a live Cage")
319 }
320 pub fn try_entry(self, key: K) -> Result<Cage<V>, AccessError> {
321 keyed::<BTreeMap<K, V>>(self.handle.runtime, self.handle.key, key)
322 }
323}
324impl<K: Eq + Hash + 'static, V: 'static, S: BuildHasher + 'static> Cage<HashMap<K, V, S>> {
325 pub fn entry(self, key: K) -> Cage<V> {
328 self.try_entry(key)
329 .expect("create a map key on a live Cage")
330 }
331 pub fn try_entry(self, key: K) -> Result<Cage<V>, AccessError> {
332 keyed::<HashMap<K, V, S>>(self.handle.runtime, self.handle.key, key)
333 }
334}