entity_map.rs

  1use crate::{seal::Sealed, AppContext, Context, Entity, ModelContext};
  2use anyhow::{anyhow, Result};
  3use derive_more::{Deref, DerefMut};
  4use parking_lot::{RwLock, RwLockUpgradableReadGuard};
  5use slotmap::{KeyData, SecondaryMap, SlotMap};
  6use std::{
  7    any::{type_name, 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    thread::panicking,
 17};
 18
 19#[cfg(any(test, feature = "test-support"))]
 20use collections::HashMap;
 21
 22slotmap::new_key_type! { pub struct EntityId; }
 23
 24impl From<u64> for EntityId {
 25    fn from(value: u64) -> Self {
 26        Self(KeyData::from_ffi(value))
 27    }
 28}
 29
 30impl EntityId {
 31    pub fn as_u64(self) -> u64 {
 32        self.0.as_ffi()
 33    }
 34}
 35
 36impl Display for EntityId {
 37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 38        write!(f, "{}", self.as_u64())
 39    }
 40}
 41
 42pub(crate) struct EntityMap {
 43    entities: SecondaryMap<EntityId, Box<dyn Any>>,
 44    ref_counts: Arc<RwLock<EntityRefCounts>>,
 45}
 46
 47struct EntityRefCounts {
 48    counts: SlotMap<EntityId, AtomicUsize>,
 49    dropped_entity_ids: Vec<EntityId>,
 50    #[cfg(any(test, feature = "test-support"))]
 51    leak_detector: LeakDetector,
 52}
 53
 54impl EntityMap {
 55    pub fn new() -> Self {
 56        Self {
 57            entities: SecondaryMap::new(),
 58            ref_counts: Arc::new(RwLock::new(EntityRefCounts {
 59                counts: SlotMap::with_key(),
 60                dropped_entity_ids: Vec::new(),
 61                #[cfg(any(test, feature = "test-support"))]
 62                leak_detector: LeakDetector {
 63                    next_handle_id: 0,
 64                    entity_handles: HashMap::default(),
 65                },
 66            })),
 67        }
 68    }
 69
 70    /// Reserve a slot for an entity, which you can subsequently use with `insert`.
 71    pub fn reserve<T: 'static>(&self) -> Slot<T> {
 72        let id = self.ref_counts.write().counts.insert(1.into());
 73        Slot(Model::new(id, Arc::downgrade(&self.ref_counts)))
 74    }
 75
 76    /// Insert an entity into a slot obtained by calling `reserve`.
 77    pub fn insert<T>(&mut self, slot: Slot<T>, entity: T) -> Model<T>
 78    where
 79        T: 'static,
 80    {
 81        let model = slot.0;
 82        self.entities.insert(model.entity_id, Box::new(entity));
 83        model
 84    }
 85
 86    /// Move an entity to the stack.
 87    #[track_caller]
 88    pub fn lease<'a, T>(&mut self, model: &'a Model<T>) -> Lease<'a, T> {
 89        self.assert_valid_context(model);
 90        let entity = Some(self.entities.remove(model.entity_id).unwrap_or_else(|| {
 91            panic!(
 92                "Circular entity lease of {}. Is it already being updated?",
 93                std::any::type_name::<T>()
 94            )
 95        }));
 96        Lease {
 97            model,
 98            entity,
 99            entity_type: PhantomData,
100        }
101    }
102
103    /// Return an entity after moving it to the stack.
104    pub fn end_lease<T>(&mut self, mut lease: Lease<T>) {
105        self.entities
106            .insert(lease.model.entity_id, lease.entity.take().unwrap());
107    }
108
109    pub fn read<T: 'static>(&self, model: &Model<T>) -> &T {
110        self.assert_valid_context(model);
111        self.entities[model.entity_id].downcast_ref().unwrap()
112    }
113
114    fn assert_valid_context(&self, model: &AnyModel) {
115        debug_assert!(
116            Weak::ptr_eq(&model.entity_map, &Arc::downgrade(&self.ref_counts)),
117            "used a model with the wrong context"
118        );
119    }
120
121    pub fn take_dropped(&mut self) -> Vec<(EntityId, Box<dyn Any>)> {
122        let mut ref_counts = self.ref_counts.write();
123        let dropped_entity_ids = mem::take(&mut ref_counts.dropped_entity_ids);
124
125        dropped_entity_ids
126            .into_iter()
127            .map(|entity_id| {
128                let count = ref_counts.counts.remove(entity_id).unwrap();
129                debug_assert_eq!(
130                    count.load(SeqCst),
131                    0,
132                    "dropped an entity that was referenced"
133                );
134                (entity_id, self.entities.remove(entity_id).unwrap())
135            })
136            .collect()
137    }
138}
139
140pub struct Lease<'a, T> {
141    entity: Option<Box<dyn Any>>,
142    pub model: &'a Model<T>,
143    entity_type: PhantomData<T>,
144}
145
146impl<'a, T: 'static> core::ops::Deref for Lease<'a, T> {
147    type Target = T;
148
149    fn deref(&self) -> &Self::Target {
150        self.entity.as_ref().unwrap().downcast_ref().unwrap()
151    }
152}
153
154impl<'a, T: 'static> core::ops::DerefMut for Lease<'a, T> {
155    fn deref_mut(&mut self) -> &mut Self::Target {
156        self.entity.as_mut().unwrap().downcast_mut().unwrap()
157    }
158}
159
160impl<'a, T> Drop for Lease<'a, T> {
161    fn drop(&mut self) {
162        if self.entity.is_some() && !panicking() {
163            panic!("Leases must be ended with EntityMap::end_lease")
164        }
165    }
166}
167
168#[derive(Deref, DerefMut)]
169pub struct Slot<T>(Model<T>);
170
171pub struct AnyModel {
172    pub(crate) entity_id: EntityId,
173    pub(crate) entity_type: TypeId,
174    entity_map: Weak<RwLock<EntityRefCounts>>,
175    #[cfg(any(test, feature = "test-support"))]
176    handle_id: HandleId,
177}
178
179impl AnyModel {
180    fn new(id: EntityId, entity_type: TypeId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self {
181        Self {
182            entity_id: id,
183            entity_type,
184            entity_map: entity_map.clone(),
185            #[cfg(any(test, feature = "test-support"))]
186            handle_id: entity_map
187                .upgrade()
188                .unwrap()
189                .write()
190                .leak_detector
191                .handle_created(id),
192        }
193    }
194
195    pub fn entity_id(&self) -> EntityId {
196        self.entity_id
197    }
198
199    pub fn entity_type(&self) -> TypeId {
200        self.entity_type
201    }
202
203    pub fn downgrade(&self) -> AnyWeakModel {
204        AnyWeakModel {
205            entity_id: self.entity_id,
206            entity_type: self.entity_type,
207            entity_ref_counts: self.entity_map.clone(),
208        }
209    }
210
211    pub fn downcast<T: 'static>(self) -> Result<Model<T>, AnyModel> {
212        if TypeId::of::<T>() == self.entity_type {
213            Ok(Model {
214                any_model: self,
215                entity_type: PhantomData,
216            })
217        } else {
218            Err(self)
219        }
220    }
221}
222
223impl Clone for AnyModel {
224    fn clone(&self) -> Self {
225        if let Some(entity_map) = self.entity_map.upgrade() {
226            let entity_map = entity_map.read();
227            let count = entity_map
228                .counts
229                .get(self.entity_id)
230                .expect("detected over-release of a model");
231            let prev_count = count.fetch_add(1, SeqCst);
232            assert_ne!(prev_count, 0, "Detected over-release of a model.");
233        }
234
235        let this = Self {
236            entity_id: self.entity_id,
237            entity_type: self.entity_type,
238            entity_map: self.entity_map.clone(),
239            #[cfg(any(test, feature = "test-support"))]
240            handle_id: self
241                .entity_map
242                .upgrade()
243                .unwrap()
244                .write()
245                .leak_detector
246                .handle_created(self.entity_id),
247        };
248        this
249    }
250}
251
252impl Drop for AnyModel {
253    fn drop(&mut self) {
254        if let Some(entity_map) = self.entity_map.upgrade() {
255            let entity_map = entity_map.upgradable_read();
256            let count = entity_map
257                .counts
258                .get(self.entity_id)
259                .expect("detected over-release of a handle.");
260            let prev_count = count.fetch_sub(1, SeqCst);
261            assert_ne!(prev_count, 0, "Detected over-release of a model.");
262            if prev_count == 1 {
263                // We were the last reference to this entity, so we can remove it.
264                let mut entity_map = RwLockUpgradableReadGuard::upgrade(entity_map);
265                entity_map.dropped_entity_ids.push(self.entity_id);
266            }
267        }
268
269        #[cfg(any(test, feature = "test-support"))]
270        if let Some(entity_map) = self.entity_map.upgrade() {
271            entity_map
272                .write()
273                .leak_detector
274                .handle_dropped(self.entity_id, self.handle_id)
275        }
276    }
277}
278
279impl<T> From<Model<T>> for AnyModel {
280    fn from(model: Model<T>) -> Self {
281        model.any_model
282    }
283}
284
285impl Hash for AnyModel {
286    fn hash<H: Hasher>(&self, state: &mut H) {
287        self.entity_id.hash(state);
288    }
289}
290
291impl PartialEq for AnyModel {
292    fn eq(&self, other: &Self) -> bool {
293        self.entity_id == other.entity_id
294    }
295}
296
297impl Eq for AnyModel {}
298
299impl std::fmt::Debug for AnyModel {
300    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
301        f.debug_struct("AnyModel")
302            .field("entity_id", &self.entity_id.as_u64())
303            .finish()
304    }
305}
306
307#[derive(Deref, DerefMut)]
308pub struct Model<T> {
309    #[deref]
310    #[deref_mut]
311    pub(crate) any_model: AnyModel,
312    pub(crate) entity_type: PhantomData<T>,
313}
314
315unsafe impl<T> Send for Model<T> {}
316unsafe impl<T> Sync for Model<T> {}
317impl<T> Sealed for Model<T> {}
318
319impl<T: 'static> Entity<T> for Model<T> {
320    type Weak = WeakModel<T>;
321
322    fn entity_id(&self) -> EntityId {
323        self.any_model.entity_id
324    }
325
326    fn downgrade(&self) -> Self::Weak {
327        WeakModel {
328            any_model: self.any_model.downgrade(),
329            entity_type: self.entity_type,
330        }
331    }
332
333    fn upgrade_from(weak: &Self::Weak) -> Option<Self>
334    where
335        Self: Sized,
336    {
337        Some(Model {
338            any_model: weak.any_model.upgrade()?,
339            entity_type: weak.entity_type,
340        })
341    }
342}
343
344impl<T: 'static> Model<T> {
345    fn new(id: EntityId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self
346    where
347        T: 'static,
348    {
349        Self {
350            any_model: AnyModel::new(id, TypeId::of::<T>(), entity_map),
351            entity_type: PhantomData,
352        }
353    }
354
355    /// Downgrade the this to a weak model reference
356    pub fn downgrade(&self) -> WeakModel<T> {
357        // Delegate to the trait implementation to keep behavior in one place.
358        // This method was included to improve method resolution in the presence of
359        // the Model's deref
360        Entity::downgrade(self)
361    }
362
363    /// Convert this into a dynamically typed model.
364    pub fn into_any(self) -> AnyModel {
365        self.any_model
366    }
367
368    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
369        cx.entities.read(self)
370    }
371
372    pub fn read_with<R, C: Context>(
373        &self,
374        cx: &C,
375        f: impl FnOnce(&T, &AppContext) -> R,
376    ) -> C::Result<R> {
377        cx.read_model(self, f)
378    }
379
380    /// Update the entity referenced by this model with the given function.
381    ///
382    /// The update function receives a context appropriate for its environment.
383    /// When updating in an `AppContext`, it receives a `ModelContext`.
384    /// When updating an a `WindowContext`, it receives a `ViewContext`.
385    pub fn update<C, R>(
386        &self,
387        cx: &mut C,
388        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
389    ) -> C::Result<R>
390    where
391        C: Context,
392    {
393        cx.update_model(self, update)
394    }
395}
396
397impl<T> Clone for Model<T> {
398    fn clone(&self) -> Self {
399        Self {
400            any_model: self.any_model.clone(),
401            entity_type: self.entity_type,
402        }
403    }
404}
405
406impl<T> std::fmt::Debug for Model<T> {
407    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
408        write!(
409            f,
410            "Model {{ entity_id: {:?}, entity_type: {:?} }}",
411            self.any_model.entity_id,
412            type_name::<T>()
413        )
414    }
415}
416
417impl<T> Hash for Model<T> {
418    fn hash<H: Hasher>(&self, state: &mut H) {
419        self.any_model.hash(state);
420    }
421}
422
423impl<T> PartialEq for Model<T> {
424    fn eq(&self, other: &Self) -> bool {
425        self.any_model == other.any_model
426    }
427}
428
429impl<T> Eq for Model<T> {}
430
431impl<T> PartialEq<WeakModel<T>> for Model<T> {
432    fn eq(&self, other: &WeakModel<T>) -> bool {
433        self.any_model.entity_id() == other.entity_id()
434    }
435}
436
437#[derive(Clone)]
438pub struct AnyWeakModel {
439    pub(crate) entity_id: EntityId,
440    entity_type: TypeId,
441    entity_ref_counts: Weak<RwLock<EntityRefCounts>>,
442}
443
444impl AnyWeakModel {
445    pub fn entity_id(&self) -> EntityId {
446        self.entity_id
447    }
448
449    pub fn is_upgradable(&self) -> bool {
450        let ref_count = self
451            .entity_ref_counts
452            .upgrade()
453            .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
454            .unwrap_or(0);
455        ref_count > 0
456    }
457
458    pub fn upgrade(&self) -> Option<AnyModel> {
459        let ref_counts = &self.entity_ref_counts.upgrade()?;
460        let ref_counts = ref_counts.read();
461        let ref_count = ref_counts.counts.get(self.entity_id)?;
462
463        // entity_id is in dropped_entity_ids
464        if ref_count.load(SeqCst) == 0 {
465            return None;
466        }
467        ref_count.fetch_add(1, SeqCst);
468        drop(ref_counts);
469
470        Some(AnyModel {
471            entity_id: self.entity_id,
472            entity_type: self.entity_type,
473            entity_map: self.entity_ref_counts.clone(),
474            #[cfg(any(test, feature = "test-support"))]
475            handle_id: self
476                .entity_ref_counts
477                .upgrade()
478                .unwrap()
479                .write()
480                .leak_detector
481                .handle_created(self.entity_id),
482        })
483    }
484
485    #[cfg(any(test, feature = "test-support"))]
486    pub fn assert_dropped(&self) {
487        self.entity_ref_counts
488            .upgrade()
489            .unwrap()
490            .write()
491            .leak_detector
492            .assert_dropped(self.entity_id);
493
494        if self
495            .entity_ref_counts
496            .upgrade()
497            .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
498            .is_some()
499        {
500            panic!(
501                "entity was recently dropped but resources are retained until the end of the effect cycle."
502            )
503        }
504    }
505}
506
507impl<T> From<WeakModel<T>> for AnyWeakModel {
508    fn from(model: WeakModel<T>) -> Self {
509        model.any_model
510    }
511}
512
513impl Hash for AnyWeakModel {
514    fn hash<H: Hasher>(&self, state: &mut H) {
515        self.entity_id.hash(state);
516    }
517}
518
519impl PartialEq for AnyWeakModel {
520    fn eq(&self, other: &Self) -> bool {
521        self.entity_id == other.entity_id
522    }
523}
524
525impl Eq for AnyWeakModel {}
526
527#[derive(Deref, DerefMut)]
528pub struct WeakModel<T> {
529    #[deref]
530    #[deref_mut]
531    any_model: AnyWeakModel,
532    entity_type: PhantomData<T>,
533}
534
535unsafe impl<T> Send for WeakModel<T> {}
536unsafe impl<T> Sync for WeakModel<T> {}
537
538impl<T> Clone for WeakModel<T> {
539    fn clone(&self) -> Self {
540        Self {
541            any_model: self.any_model.clone(),
542            entity_type: self.entity_type,
543        }
544    }
545}
546
547impl<T: 'static> WeakModel<T> {
548    /// Upgrade this weak model reference into a strong model reference
549    pub fn upgrade(&self) -> Option<Model<T>> {
550        // Delegate to the trait implementation to keep behavior in one place.
551        Model::upgrade_from(self)
552    }
553
554    /// Update the entity referenced by this model with the given function if
555    /// the referenced entity still exists. Returns an error if the entity has
556    /// been released.
557    pub fn update<C, R>(
558        &self,
559        cx: &mut C,
560        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
561    ) -> Result<R>
562    where
563        C: Context,
564        Result<C::Result<R>>: crate::Flatten<R>,
565    {
566        crate::Flatten::flatten(
567            self.upgrade()
568                .ok_or_else(|| anyhow!("entity release"))
569                .map(|this| cx.update_model(&this, update)),
570        )
571    }
572
573    /// Reads the entity referenced by this model with the given function if
574    /// the referenced entity still exists. Returns an error if the entity has
575    /// been released.
576    pub fn read_with<C, R>(&self, cx: &C, read: impl FnOnce(&T, &AppContext) -> R) -> Result<R>
577    where
578        C: Context,
579        Result<C::Result<R>>: crate::Flatten<R>,
580    {
581        crate::Flatten::flatten(
582            self.upgrade()
583                .ok_or_else(|| anyhow!("entity release"))
584                .map(|this| cx.read_model(&this, read)),
585        )
586    }
587}
588
589impl<T> Hash for WeakModel<T> {
590    fn hash<H: Hasher>(&self, state: &mut H) {
591        self.any_model.hash(state);
592    }
593}
594
595impl<T> PartialEq for WeakModel<T> {
596    fn eq(&self, other: &Self) -> bool {
597        self.any_model == other.any_model
598    }
599}
600
601impl<T> Eq for WeakModel<T> {}
602
603impl<T> PartialEq<Model<T>> for WeakModel<T> {
604    fn eq(&self, other: &Model<T>) -> bool {
605        self.entity_id() == other.any_model.entity_id()
606    }
607}
608
609#[cfg(any(test, feature = "test-support"))]
610lazy_static::lazy_static! {
611    static ref LEAK_BACKTRACE: bool =
612        std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty());
613}
614
615#[cfg(any(test, feature = "test-support"))]
616#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
617pub struct HandleId {
618    id: u64, // id of the handle itself, not the pointed at object
619}
620
621#[cfg(any(test, feature = "test-support"))]
622pub struct LeakDetector {
623    next_handle_id: u64,
624    entity_handles: HashMap<EntityId, HashMap<HandleId, Option<backtrace::Backtrace>>>,
625}
626
627#[cfg(any(test, feature = "test-support"))]
628impl LeakDetector {
629    #[track_caller]
630    pub fn handle_created(&mut self, entity_id: EntityId) -> HandleId {
631        let id = util::post_inc(&mut self.next_handle_id);
632        let handle_id = HandleId { id };
633        let handles = self.entity_handles.entry(entity_id).or_default();
634        handles.insert(
635            handle_id,
636            LEAK_BACKTRACE.then(|| backtrace::Backtrace::new_unresolved()),
637        );
638        handle_id
639    }
640
641    pub fn handle_dropped(&mut self, entity_id: EntityId, handle_id: HandleId) {
642        let handles = self.entity_handles.entry(entity_id).or_default();
643        handles.remove(&handle_id);
644    }
645
646    pub fn assert_dropped(&mut self, entity_id: EntityId) {
647        let handles = self.entity_handles.entry(entity_id).or_default();
648        if !handles.is_empty() {
649            for (_, backtrace) in handles {
650                if let Some(mut backtrace) = backtrace.take() {
651                    backtrace.resolve();
652                    eprintln!("Leaked handle: {:#?}", backtrace);
653                } else {
654                    eprintln!("Leaked handle: export LEAK_BACKTRACE to find allocation site");
655                }
656            }
657            panic!();
658        }
659    }
660}
661
662#[cfg(test)]
663mod test {
664    use crate::EntityMap;
665
666    struct TestEntity {
667        pub i: i32,
668    }
669
670    #[test]
671    fn test_entity_map_slot_assignment_before_cleanup() {
672        // Tests that slots are not re-used before take_dropped.
673        let mut entity_map = EntityMap::new();
674
675        let slot = entity_map.reserve::<TestEntity>();
676        entity_map.insert(slot, TestEntity { i: 1 });
677
678        let slot = entity_map.reserve::<TestEntity>();
679        entity_map.insert(slot, TestEntity { i: 2 });
680
681        let dropped = entity_map.take_dropped();
682        assert_eq!(dropped.len(), 2);
683
684        assert_eq!(
685            dropped
686                .into_iter()
687                .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
688                .collect::<Vec<i32>>(),
689            vec![1, 2],
690        );
691    }
692
693    #[test]
694    fn test_entity_map_weak_upgrade_before_cleanup() {
695        // Tests that weak handles are not upgraded before take_dropped
696        let mut entity_map = EntityMap::new();
697
698        let slot = entity_map.reserve::<TestEntity>();
699        let handle = entity_map.insert(slot, TestEntity { i: 1 });
700        let weak = handle.downgrade();
701        drop(handle);
702
703        let strong = weak.upgrade();
704        assert_eq!(strong, None);
705
706        let dropped = entity_map.take_dropped();
707        assert_eq!(dropped.len(), 1);
708
709        assert_eq!(
710            dropped
711                .into_iter()
712                .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
713                .collect::<Vec<i32>>(),
714            vec![1],
715        );
716    }
717}