entity_map.rs

  1use crate::{AppContext, Context};
  2use anyhow::{anyhow, Result};
  3use derive_more::{Deref, DerefMut};
  4use parking_lot::{RwLock, RwLockUpgradableReadGuard};
  5use slotmap::{SecondaryMap, SlotMap};
  6use std::{
  7    any::{Any, TypeId},
  8    fmt::{self, Display},
  9    hash::{Hash, Hasher},
 10    marker::PhantomData,
 11    mem,
 12    sync::{
 13        atomic::{AtomicUsize, Ordering::SeqCst},
 14        Arc, Weak,
 15    },
 16};
 17
 18slotmap::new_key_type! { pub struct EntityId; }
 19
 20impl Display for EntityId {
 21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 22        write!(f, "{}", self)
 23    }
 24}
 25
 26pub(crate) struct EntityMap {
 27    entities: SecondaryMap<EntityId, Box<dyn Any + Send + Sync>>,
 28    ref_counts: Arc<RwLock<EntityRefCounts>>,
 29}
 30
 31struct EntityRefCounts {
 32    counts: SlotMap<EntityId, AtomicUsize>,
 33    dropped_entity_ids: Vec<EntityId>,
 34}
 35
 36impl EntityMap {
 37    pub fn new() -> Self {
 38        Self {
 39            entities: SecondaryMap::new(),
 40            ref_counts: Arc::new(RwLock::new(EntityRefCounts {
 41                counts: SlotMap::with_key(),
 42                dropped_entity_ids: Vec::new(),
 43            })),
 44        }
 45    }
 46
 47    /// Reserve a slot for an entity, which you can subsequently use with `insert`.
 48    pub fn reserve<T: 'static + Send + Sync>(&self) -> Slot<T> {
 49        let id = self.ref_counts.write().counts.insert(1.into());
 50        Slot(Handle::new(id, Arc::downgrade(&self.ref_counts)))
 51    }
 52
 53    /// Insert an entity into a slot obtained by calling `reserve`.
 54    pub fn insert<T: 'static + Any + Send + Sync>(
 55        &mut self,
 56        slot: Slot<T>,
 57        entity: T,
 58    ) -> Handle<T> {
 59        let handle = slot.0;
 60        self.entities.insert(handle.entity_id, Box::new(entity));
 61        handle
 62    }
 63
 64    /// Move an entity to the stack.
 65    pub fn lease<'a, T: 'static + Send + Sync>(&mut self, handle: &'a Handle<T>) -> Lease<'a, T> {
 66        let entity = Some(
 67            self.entities
 68                .remove(handle.entity_id)
 69                .expect("Circular entity lease. Is the entity already being updated?")
 70                .downcast::<T>()
 71                .unwrap(),
 72        );
 73        Lease { handle, entity }
 74    }
 75
 76    /// Return an entity after moving it to the stack.
 77    pub fn end_lease<T: 'static + Send + Sync>(&mut self, mut lease: Lease<T>) {
 78        self.entities
 79            .insert(lease.handle.entity_id, lease.entity.take().unwrap());
 80    }
 81
 82    pub fn read<T: 'static + Send + Sync>(&self, handle: &Handle<T>) -> &T {
 83        self.entities[handle.entity_id].downcast_ref().unwrap()
 84    }
 85
 86    pub fn weak_handle<T: 'static + Send + Sync>(&self, id: EntityId) -> WeakHandle<T> {
 87        WeakHandle {
 88            any_handle: AnyWeakHandle {
 89                entity_id: id,
 90                entity_type: TypeId::of::<T>(),
 91                entity_ref_counts: Arc::downgrade(&self.ref_counts),
 92            },
 93            entity_type: PhantomData,
 94        }
 95    }
 96
 97    pub fn take_dropped(&mut self) -> Vec<(EntityId, Box<dyn Any + Send + Sync>)> {
 98        let dropped_entity_ids = mem::take(&mut self.ref_counts.write().dropped_entity_ids);
 99        dropped_entity_ids
100            .into_iter()
101            .map(|entity_id| (entity_id, self.entities.remove(entity_id).unwrap()))
102            .collect()
103    }
104}
105
106pub struct Lease<'a, T: Send + Sync> {
107    entity: Option<Box<T>>,
108    pub handle: &'a Handle<T>,
109}
110
111impl<'a, T> core::ops::Deref for Lease<'a, T>
112where
113    T: Send + Sync,
114{
115    type Target = T;
116
117    fn deref(&self) -> &Self::Target {
118        self.entity.as_ref().unwrap()
119    }
120}
121
122impl<'a, T> core::ops::DerefMut for Lease<'a, T>
123where
124    T: Send + Sync,
125{
126    fn deref_mut(&mut self) -> &mut Self::Target {
127        self.entity.as_mut().unwrap()
128    }
129}
130
131impl<'a, T> Drop for Lease<'a, T>
132where
133    T: Send + Sync,
134{
135    fn drop(&mut self) {
136        if self.entity.is_some() {
137            // We don't panic here, because other panics can cause us to drop the lease without ending it cleanly.
138            log::error!("Leases must be ended with EntityMap::end_lease")
139        }
140    }
141}
142
143#[derive(Deref, DerefMut)]
144pub struct Slot<T: Send + Sync + 'static>(Handle<T>);
145
146pub struct AnyHandle {
147    pub(crate) entity_id: EntityId,
148    entity_type: TypeId,
149    entity_map: Weak<RwLock<EntityRefCounts>>,
150}
151
152impl AnyHandle {
153    fn new(id: EntityId, entity_type: TypeId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self {
154        Self {
155            entity_id: id,
156            entity_type,
157            entity_map,
158        }
159    }
160
161    pub fn entity_id(&self) -> EntityId {
162        self.entity_id
163    }
164
165    pub fn downgrade(&self) -> AnyWeakHandle {
166        AnyWeakHandle {
167            entity_id: self.entity_id,
168            entity_type: self.entity_type,
169            entity_ref_counts: self.entity_map.clone(),
170        }
171    }
172
173    pub fn downcast<T>(&self) -> Option<Handle<T>>
174    where
175        T: 'static + Send + Sync,
176    {
177        if TypeId::of::<T>() == self.entity_type {
178            Some(Handle {
179                any_handle: self.clone(),
180                entity_type: PhantomData,
181            })
182        } else {
183            None
184        }
185    }
186}
187
188impl Clone for AnyHandle {
189    fn clone(&self) -> Self {
190        if let Some(entity_map) = self.entity_map.upgrade() {
191            let entity_map = entity_map.read();
192            let count = entity_map
193                .counts
194                .get(self.entity_id)
195                .expect("detected over-release of a handle");
196            let prev_count = count.fetch_add(1, SeqCst);
197            assert_ne!(prev_count, 0, "Detected over-release of a handle.");
198        }
199
200        Self {
201            entity_id: self.entity_id,
202            entity_type: self.entity_type,
203            entity_map: self.entity_map.clone(),
204        }
205    }
206}
207
208impl Drop for AnyHandle {
209    fn drop(&mut self) {
210        if let Some(entity_map) = self.entity_map.upgrade() {
211            let entity_map = entity_map.upgradable_read();
212            let count = entity_map
213                .counts
214                .get(self.entity_id)
215                .expect("Detected over-release of a handle.");
216            let prev_count = count.fetch_sub(1, SeqCst);
217            assert_ne!(prev_count, 0, "Detected over-release of a handle.");
218            if prev_count == 1 {
219                // We were the last reference to this entity, so we can remove it.
220                let mut entity_map = RwLockUpgradableReadGuard::upgrade(entity_map);
221                entity_map.counts.remove(self.entity_id);
222                entity_map.dropped_entity_ids.push(self.entity_id);
223            }
224        }
225    }
226}
227
228impl<T> From<Handle<T>> for AnyHandle
229where
230    T: 'static + Send + Sync,
231{
232    fn from(handle: Handle<T>) -> Self {
233        handle.any_handle
234    }
235}
236
237#[derive(Deref, DerefMut)]
238pub struct Handle<T: Send + Sync> {
239    #[deref]
240    #[deref_mut]
241    any_handle: AnyHandle,
242    entity_type: PhantomData<T>,
243}
244
245impl<T: 'static + Send + Sync> Handle<T> {
246    fn new(id: EntityId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self {
247        Self {
248            any_handle: AnyHandle::new(id, TypeId::of::<T>(), entity_map),
249            entity_type: PhantomData,
250        }
251    }
252
253    pub fn downgrade(&self) -> WeakHandle<T> {
254        WeakHandle {
255            any_handle: self.any_handle.downgrade(),
256            entity_type: self.entity_type,
257        }
258    }
259
260    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
261        cx.entities.read(self)
262    }
263
264    /// Update the entity referenced by this handle with the given function.
265    ///
266    /// The update function receives a context appropriate for its environment.
267    /// When updating in an `AppContext`, it receives a `ModelContext`.
268    /// When updating an a `WindowContext`, it receives a `ViewContext`.
269    pub fn update<C: Context, R>(
270        &self,
271        cx: &mut C,
272        update: impl FnOnce(&mut T, &mut C::EntityContext<'_, '_, T>) -> R,
273    ) -> C::Result<R> {
274        cx.update_entity(self, update)
275    }
276}
277
278impl<T: Send + Sync> Clone for Handle<T> {
279    fn clone(&self) -> Self {
280        Self {
281            any_handle: self.any_handle.clone(),
282            entity_type: self.entity_type,
283        }
284    }
285}
286
287#[derive(Clone)]
288pub struct AnyWeakHandle {
289    pub(crate) entity_id: EntityId,
290    entity_type: TypeId,
291    entity_ref_counts: Weak<RwLock<EntityRefCounts>>,
292}
293
294impl AnyWeakHandle {
295    pub fn entity_id(&self) -> EntityId {
296        self.entity_id
297    }
298
299    pub fn is_upgradable(&self) -> bool {
300        let ref_count = self
301            .entity_ref_counts
302            .upgrade()
303            .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
304            .unwrap_or(0);
305        ref_count > 0
306    }
307
308    pub fn upgrade(&self) -> Option<AnyHandle> {
309        let entity_map = self.entity_ref_counts.upgrade()?;
310        entity_map
311            .read()
312            .counts
313            .get(self.entity_id)?
314            .fetch_add(1, SeqCst);
315        Some(AnyHandle {
316            entity_id: self.entity_id,
317            entity_type: self.entity_type,
318            entity_map: self.entity_ref_counts.clone(),
319        })
320    }
321}
322
323impl<T> From<WeakHandle<T>> for AnyWeakHandle
324where
325    T: 'static + Send + Sync,
326{
327    fn from(handle: WeakHandle<T>) -> Self {
328        handle.any_handle
329    }
330}
331
332impl Hash for AnyWeakHandle {
333    fn hash<H: Hasher>(&self, state: &mut H) {
334        self.entity_id.hash(state);
335    }
336}
337
338impl PartialEq for AnyWeakHandle {
339    fn eq(&self, other: &Self) -> bool {
340        self.entity_id == other.entity_id
341    }
342}
343
344impl Eq for AnyWeakHandle {}
345
346#[derive(Deref, DerefMut)]
347pub struct WeakHandle<T> {
348    #[deref]
349    #[deref_mut]
350    any_handle: AnyWeakHandle,
351    entity_type: PhantomData<T>,
352}
353
354impl<T: 'static + Send + Sync> Clone for WeakHandle<T> {
355    fn clone(&self) -> Self {
356        Self {
357            any_handle: self.any_handle.clone(),
358            entity_type: self.entity_type,
359        }
360    }
361}
362
363impl<T: Send + Sync + 'static> WeakHandle<T> {
364    pub fn upgrade(&self) -> Option<Handle<T>> {
365        Some(Handle {
366            any_handle: self.any_handle.upgrade()?,
367            entity_type: self.entity_type,
368        })
369    }
370
371    /// Update the entity referenced by this handle with the given function if
372    /// the referenced entity still exists. Returns an error if the entity has
373    /// been released.
374    ///
375    /// The update function receives a context appropriate for its environment.
376    /// When updating in an `AppContext`, it receives a `ModelContext`.
377    /// When updating an a `WindowContext`, it receives a `ViewContext`.
378    pub fn update<C: Context, R>(
379        &self,
380        cx: &mut C,
381        update: impl FnOnce(&mut T, &mut C::EntityContext<'_, '_, T>) -> R,
382    ) -> Result<R>
383    where
384        Result<C::Result<R>>: crate::Flatten<R>,
385    {
386        crate::Flatten::flatten(
387            self.upgrade()
388                .ok_or_else(|| anyhow!("entity release"))
389                .map(|this| cx.update_entity(&this, update)),
390        )
391    }
392}
393
394impl<T: Send + Sync + 'static> Hash for WeakHandle<T> {
395    fn hash<H: Hasher>(&self, state: &mut H) {
396        self.any_handle.hash(state);
397    }
398}
399
400impl<T: Send + Sync + 'static> PartialEq for WeakHandle<T> {
401    fn eq(&self, other: &Self) -> bool {
402        self.any_handle == other.any_handle
403    }
404}
405
406impl<T: Send + Sync + 'static> Eq for WeakHandle<T> {}