entity_map.rs

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