entity_map.rs

  1use crate::{App, AppContext, GpuiBorrow, VisualContext, Window, seal::Sealed};
  2use anyhow::{Context as _, Result};
  3use collections::FxHashSet;
  4use derive_more::{Deref, DerefMut};
  5use parking_lot::{RwLock, RwLockUpgradableReadGuard};
  6use slotmap::{KeyData, SecondaryMap, SlotMap};
  7use std::{
  8    any::{Any, TypeId, type_name},
  9    cell::RefCell,
 10    cmp::Ordering,
 11    fmt::{self, Display},
 12    hash::{Hash, Hasher},
 13    marker::PhantomData,
 14    mem,
 15    num::NonZeroU64,
 16    sync::{
 17        Arc, Weak,
 18        atomic::{AtomicU64, AtomicUsize, Ordering::SeqCst},
 19    },
 20    thread::panicking,
 21};
 22
 23use super::Context;
 24use crate::util::atomic_incr_if_not_zero;
 25#[cfg(any(test, feature = "leak-detection"))]
 26use collections::HashMap;
 27
 28slotmap::new_key_type! {
 29    /// A unique identifier for a entity across the application.
 30    pub struct EntityId;
 31}
 32
 33impl From<u64> for EntityId {
 34    fn from(value: u64) -> Self {
 35        Self(KeyData::from_ffi(value))
 36    }
 37}
 38
 39impl EntityId {
 40    /// Converts this entity id to a [NonZeroU64]
 41    pub fn as_non_zero_u64(self) -> NonZeroU64 {
 42        NonZeroU64::new(self.0.as_ffi()).unwrap()
 43    }
 44
 45    /// Converts this entity id to a [u64]
 46    pub fn as_u64(self) -> u64 {
 47        self.0.as_ffi()
 48    }
 49}
 50
 51impl Display for EntityId {
 52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 53        write!(f, "{}", self.as_u64())
 54    }
 55}
 56
 57pub(crate) struct EntityMap {
 58    entities: SecondaryMap<EntityId, Box<dyn Any>>,
 59    pub accessed_entities: RefCell<FxHashSet<EntityId>>,
 60    ref_counts: Arc<RwLock<EntityRefCounts>>,
 61}
 62
 63struct EntityRefCounts {
 64    counts: SlotMap<EntityId, AtomicUsize>,
 65    dropped_entity_ids: Vec<EntityId>,
 66    #[cfg(any(test, feature = "leak-detection"))]
 67    leak_detector: LeakDetector,
 68}
 69
 70impl EntityMap {
 71    pub fn new() -> Self {
 72        Self {
 73            entities: SecondaryMap::new(),
 74            accessed_entities: RefCell::new(FxHashSet::default()),
 75            ref_counts: Arc::new(RwLock::new(EntityRefCounts {
 76                counts: SlotMap::with_key(),
 77                dropped_entity_ids: Vec::new(),
 78                #[cfg(any(test, feature = "leak-detection"))]
 79                leak_detector: LeakDetector {
 80                    next_handle_id: 0,
 81                    entity_handles: HashMap::default(),
 82                },
 83            })),
 84        }
 85    }
 86
 87    /// Reserve a slot for an entity, which you can subsequently use with `insert`.
 88    pub fn reserve<T: 'static>(&self) -> Slot<T> {
 89        let id = self.ref_counts.write().counts.insert(1.into());
 90        Slot(Entity::new(id, Arc::downgrade(&self.ref_counts)))
 91    }
 92
 93    /// Insert an entity into a slot obtained by calling `reserve`.
 94    pub fn insert<T>(&mut self, slot: Slot<T>, entity: T) -> Entity<T>
 95    where
 96        T: 'static,
 97    {
 98        let mut accessed_entities = self.accessed_entities.borrow_mut();
 99        accessed_entities.insert(slot.entity_id);
100
101        let handle = slot.0;
102        self.entities.insert(handle.entity_id, Box::new(entity));
103        handle
104    }
105
106    /// Move an entity to the stack.
107    #[track_caller]
108    pub fn lease<T>(&mut self, pointer: &Entity<T>) -> Lease<T> {
109        self.assert_valid_context(pointer);
110        let mut accessed_entities = self.accessed_entities.borrow_mut();
111        accessed_entities.insert(pointer.entity_id);
112
113        let entity = Some(
114            self.entities
115                .remove(pointer.entity_id)
116                .unwrap_or_else(|| double_lease_panic::<T>("update")),
117        );
118        Lease {
119            entity,
120            id: pointer.entity_id,
121            entity_type: PhantomData,
122        }
123    }
124
125    /// Returns an entity after moving it to the stack.
126    pub fn end_lease<T>(&mut self, mut lease: Lease<T>) {
127        self.entities.insert(lease.id, lease.entity.take().unwrap());
128    }
129
130    pub fn read<T: 'static>(&self, entity: &Entity<T>) -> &T {
131        self.assert_valid_context(entity);
132        let mut accessed_entities = self.accessed_entities.borrow_mut();
133        accessed_entities.insert(entity.entity_id);
134
135        self.entities
136            .get(entity.entity_id)
137            .and_then(|entity| entity.downcast_ref())
138            .unwrap_or_else(|| double_lease_panic::<T>("read"))
139    }
140
141    fn assert_valid_context(&self, entity: &AnyEntity) {
142        debug_assert!(
143            Weak::ptr_eq(&entity.entity_map, &Arc::downgrade(&self.ref_counts)),
144            "used a entity with the wrong context"
145        );
146    }
147
148    pub fn extend_accessed(&mut self, entities: &FxHashSet<EntityId>) {
149        self.accessed_entities
150            .borrow_mut()
151            .extend(entities.iter().copied());
152    }
153
154    pub fn clear_accessed(&mut self) {
155        self.accessed_entities.borrow_mut().clear();
156    }
157
158    pub fn take_dropped(&mut self) -> Vec<(EntityId, Box<dyn Any>)> {
159        let mut ref_counts = self.ref_counts.write();
160        let dropped_entity_ids = mem::take(&mut ref_counts.dropped_entity_ids);
161        let mut accessed_entities = self.accessed_entities.borrow_mut();
162
163        dropped_entity_ids
164            .into_iter()
165            .filter_map(|entity_id| {
166                let count = ref_counts.counts.remove(entity_id).unwrap();
167                debug_assert_eq!(
168                    count.load(SeqCst),
169                    0,
170                    "dropped an entity that was referenced"
171                );
172                accessed_entities.remove(&entity_id);
173                // If the EntityId was allocated with `Context::reserve`,
174                // the entity may not have been inserted.
175                Some((entity_id, self.entities.remove(entity_id)?))
176            })
177            .collect()
178    }
179}
180
181#[track_caller]
182fn double_lease_panic<T>(operation: &str) -> ! {
183    panic!(
184        "cannot {operation} {} while it is already being updated",
185        std::any::type_name::<T>()
186    )
187}
188
189pub(crate) struct Lease<T> {
190    entity: Option<Box<dyn Any>>,
191    pub id: EntityId,
192    entity_type: PhantomData<T>,
193}
194
195impl<T: 'static> core::ops::Deref for Lease<T> {
196    type Target = T;
197
198    fn deref(&self) -> &Self::Target {
199        self.entity.as_ref().unwrap().downcast_ref().unwrap()
200    }
201}
202
203impl<T: 'static> core::ops::DerefMut for Lease<T> {
204    fn deref_mut(&mut self) -> &mut Self::Target {
205        self.entity.as_mut().unwrap().downcast_mut().unwrap()
206    }
207}
208
209impl<T> Drop for Lease<T> {
210    fn drop(&mut self) {
211        if self.entity.is_some() && !panicking() {
212            panic!("Leases must be ended with EntityMap::end_lease")
213        }
214    }
215}
216
217#[derive(Deref, DerefMut)]
218pub(crate) struct Slot<T>(Entity<T>);
219
220/// A dynamically typed reference to a entity, which can be downcast into a `Entity<T>`.
221pub struct AnyEntity {
222    pub(crate) entity_id: EntityId,
223    pub(crate) entity_type: TypeId,
224    entity_map: Weak<RwLock<EntityRefCounts>>,
225    #[cfg(any(test, feature = "leak-detection"))]
226    handle_id: HandleId,
227}
228
229impl AnyEntity {
230    fn new(id: EntityId, entity_type: TypeId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self {
231        Self {
232            entity_id: id,
233            entity_type,
234            #[cfg(any(test, feature = "leak-detection"))]
235            handle_id: entity_map
236                .clone()
237                .upgrade()
238                .unwrap()
239                .write()
240                .leak_detector
241                .handle_created(id),
242            entity_map,
243        }
244    }
245
246    /// Returns the id associated with this entity.
247    #[inline]
248    pub fn entity_id(&self) -> EntityId {
249        self.entity_id
250    }
251
252    /// Returns the [TypeId] associated with this entity.
253    #[inline]
254    pub fn entity_type(&self) -> TypeId {
255        self.entity_type
256    }
257
258    /// Converts this entity handle into a weak variant, which does not prevent it from being released.
259    pub fn downgrade(&self) -> AnyWeakEntity {
260        AnyWeakEntity {
261            entity_id: self.entity_id,
262            entity_type: self.entity_type,
263            entity_ref_counts: self.entity_map.clone(),
264        }
265    }
266
267    /// Converts this entity handle into a strongly-typed entity handle of the given type.
268    /// If this entity handle is not of the specified type, returns itself as an error variant.
269    pub fn downcast<T: 'static>(self) -> Result<Entity<T>, AnyEntity> {
270        if TypeId::of::<T>() == self.entity_type {
271            Ok(Entity {
272                any_entity: self,
273                entity_type: PhantomData,
274            })
275        } else {
276            Err(self)
277        }
278    }
279}
280
281impl Clone for AnyEntity {
282    fn clone(&self) -> Self {
283        if let Some(entity_map) = self.entity_map.upgrade() {
284            let entity_map = entity_map.read();
285            let count = entity_map
286                .counts
287                .get(self.entity_id)
288                .expect("detected over-release of a entity");
289            let prev_count = count.fetch_add(1, SeqCst);
290            assert_ne!(prev_count, 0, "Detected over-release of a entity.");
291        }
292
293        Self {
294            entity_id: self.entity_id,
295            entity_type: self.entity_type,
296            entity_map: self.entity_map.clone(),
297            #[cfg(any(test, feature = "leak-detection"))]
298            handle_id: self
299                .entity_map
300                .upgrade()
301                .unwrap()
302                .write()
303                .leak_detector
304                .handle_created(self.entity_id),
305        }
306    }
307}
308
309impl Drop for AnyEntity {
310    fn drop(&mut self) {
311        if let Some(entity_map) = self.entity_map.upgrade() {
312            let entity_map = entity_map.upgradable_read();
313            let count = entity_map
314                .counts
315                .get(self.entity_id)
316                .expect("detected over-release of a handle.");
317            let prev_count = count.fetch_sub(1, SeqCst);
318            assert_ne!(prev_count, 0, "Detected over-release of a entity.");
319            if prev_count == 1 {
320                // We were the last reference to this entity, so we can remove it.
321                let mut entity_map = RwLockUpgradableReadGuard::upgrade(entity_map);
322                entity_map.dropped_entity_ids.push(self.entity_id);
323            }
324        }
325
326        #[cfg(any(test, feature = "leak-detection"))]
327        if let Some(entity_map) = self.entity_map.upgrade() {
328            entity_map
329                .write()
330                .leak_detector
331                .handle_released(self.entity_id, self.handle_id)
332        }
333    }
334}
335
336impl<T> From<Entity<T>> for AnyEntity {
337    #[inline]
338    fn from(entity: Entity<T>) -> Self {
339        entity.any_entity
340    }
341}
342
343impl Hash for AnyEntity {
344    #[inline]
345    fn hash<H: Hasher>(&self, state: &mut H) {
346        self.entity_id.hash(state);
347    }
348}
349
350impl PartialEq for AnyEntity {
351    #[inline]
352    fn eq(&self, other: &Self) -> bool {
353        self.entity_id == other.entity_id
354    }
355}
356
357impl Eq for AnyEntity {}
358
359impl Ord for AnyEntity {
360    #[inline]
361    fn cmp(&self, other: &Self) -> Ordering {
362        self.entity_id.cmp(&other.entity_id)
363    }
364}
365
366impl PartialOrd for AnyEntity {
367    #[inline]
368    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
369        Some(self.cmp(other))
370    }
371}
372
373impl std::fmt::Debug for AnyEntity {
374    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
375        f.debug_struct("AnyEntity")
376            .field("entity_id", &self.entity_id.as_u64())
377            .finish()
378    }
379}
380
381/// A strong, well-typed reference to a struct which is managed
382/// by GPUI
383#[derive(Deref, DerefMut)]
384pub struct Entity<T> {
385    #[deref]
386    #[deref_mut]
387    pub(crate) any_entity: AnyEntity,
388    pub(crate) entity_type: PhantomData<fn(T) -> T>,
389}
390
391impl<T> Sealed for Entity<T> {}
392
393impl<T: 'static> Entity<T> {
394    #[inline]
395    fn new(id: EntityId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self
396    where
397        T: 'static,
398    {
399        Self {
400            any_entity: AnyEntity::new(id, TypeId::of::<T>(), entity_map),
401            entity_type: PhantomData,
402        }
403    }
404
405    /// Get the entity ID associated with this entity
406    #[inline]
407    pub fn entity_id(&self) -> EntityId {
408        self.any_entity.entity_id
409    }
410
411    /// Downgrade this entity pointer to a non-retaining weak pointer
412    #[inline]
413    pub fn downgrade(&self) -> WeakEntity<T> {
414        WeakEntity {
415            any_entity: self.any_entity.downgrade(),
416            entity_type: self.entity_type,
417        }
418    }
419
420    /// Convert this into a dynamically typed entity.
421    #[inline]
422    pub fn into_any(self) -> AnyEntity {
423        self.any_entity
424    }
425
426    /// Grab a reference to this entity from the context.
427    #[inline]
428    pub fn read<'a>(&self, cx: &'a App) -> &'a T {
429        cx.entities.read(self)
430    }
431
432    /// Read the entity referenced by this handle with the given function.
433    #[inline]
434    pub fn read_with<R, C: AppContext>(
435        &self,
436        cx: &C,
437        f: impl FnOnce(&T, &App) -> R,
438    ) -> C::Result<R> {
439        cx.read_entity(self, f)
440    }
441
442    /// Updates the entity referenced by this handle with the given function.
443    #[inline]
444    pub fn update<R, C: AppContext>(
445        &self,
446        cx: &mut C,
447        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
448    ) -> C::Result<R> {
449        cx.update_entity(self, update)
450    }
451
452    /// Updates the entity referenced by this handle with the given function.
453    #[inline]
454    pub fn as_mut<'a, C: AppContext>(&self, cx: &'a mut C) -> C::Result<GpuiBorrow<'a, T>> {
455        cx.as_mut(self)
456    }
457
458    /// Updates the entity referenced by this handle with the given function.
459    pub fn write<C: AppContext>(&self, cx: &mut C, value: T) -> C::Result<()> {
460        self.update(cx, |entity, cx| {
461            *entity = value;
462            cx.notify();
463        })
464    }
465
466    /// Updates the entity referenced by this handle with the given function if
467    /// the referenced entity still exists, within a visual context that has a window.
468    /// Returns an error if the entity has been released.
469    #[inline]
470    pub fn update_in<R, C: VisualContext>(
471        &self,
472        cx: &mut C,
473        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
474    ) -> C::Result<R> {
475        cx.update_window_entity(self, update)
476    }
477}
478
479impl<T> Clone for Entity<T> {
480    #[inline]
481    fn clone(&self) -> Self {
482        Self {
483            any_entity: self.any_entity.clone(),
484            entity_type: self.entity_type,
485        }
486    }
487}
488
489impl<T> std::fmt::Debug for Entity<T> {
490    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
491        f.debug_struct("Entity")
492            .field("entity_id", &self.any_entity.entity_id)
493            .field("entity_type", &type_name::<T>())
494            .finish()
495    }
496}
497
498impl<T> Hash for Entity<T> {
499    #[inline]
500    fn hash<H: Hasher>(&self, state: &mut H) {
501        self.any_entity.hash(state);
502    }
503}
504
505impl<T> PartialEq for Entity<T> {
506    #[inline]
507    fn eq(&self, other: &Self) -> bool {
508        self.any_entity == other.any_entity
509    }
510}
511
512impl<T> Eq for Entity<T> {}
513
514impl<T> PartialEq<WeakEntity<T>> for Entity<T> {
515    #[inline]
516    fn eq(&self, other: &WeakEntity<T>) -> bool {
517        self.any_entity.entity_id() == other.entity_id()
518    }
519}
520
521impl<T: 'static> Ord for Entity<T> {
522    #[inline]
523    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
524        self.entity_id().cmp(&other.entity_id())
525    }
526}
527
528impl<T: 'static> PartialOrd for Entity<T> {
529    #[inline]
530    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
531        Some(self.cmp(other))
532    }
533}
534
535/// A type erased, weak reference to a entity.
536#[derive(Clone)]
537pub struct AnyWeakEntity {
538    pub(crate) entity_id: EntityId,
539    entity_type: TypeId,
540    entity_ref_counts: Weak<RwLock<EntityRefCounts>>,
541}
542
543impl AnyWeakEntity {
544    /// Get the entity ID associated with this weak reference.
545    #[inline]
546    pub fn entity_id(&self) -> EntityId {
547        self.entity_id
548    }
549
550    /// Check if this weak handle can be upgraded, or if the entity has already been dropped
551    pub fn is_upgradable(&self) -> bool {
552        let ref_count = self
553            .entity_ref_counts
554            .upgrade()
555            .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
556            .unwrap_or(0);
557        ref_count > 0
558    }
559
560    /// Upgrade this weak entity reference to a strong reference.
561    pub fn upgrade(&self) -> Option<AnyEntity> {
562        let ref_counts = &self.entity_ref_counts.upgrade()?;
563        let ref_counts = ref_counts.read();
564        let ref_count = ref_counts.counts.get(self.entity_id)?;
565
566        if atomic_incr_if_not_zero(ref_count) == 0 {
567            // entity_id is in dropped_entity_ids
568            return None;
569        }
570        drop(ref_counts);
571
572        Some(AnyEntity {
573            entity_id: self.entity_id,
574            entity_type: self.entity_type,
575            entity_map: self.entity_ref_counts.clone(),
576            #[cfg(any(test, feature = "leak-detection"))]
577            handle_id: self
578                .entity_ref_counts
579                .upgrade()
580                .unwrap()
581                .write()
582                .leak_detector
583                .handle_created(self.entity_id),
584        })
585    }
586
587    /// Assert that entity referenced by this weak handle has been released.
588    #[cfg(any(test, feature = "leak-detection"))]
589    pub fn assert_released(&self) {
590        self.entity_ref_counts
591            .upgrade()
592            .unwrap()
593            .write()
594            .leak_detector
595            .assert_released(self.entity_id);
596
597        if self
598            .entity_ref_counts
599            .upgrade()
600            .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
601            .is_some()
602        {
603            panic!(
604                "entity was recently dropped but resources are retained until the end of the effect cycle."
605            )
606        }
607    }
608
609    /// Creates a weak entity that can never be upgraded.
610    pub fn new_invalid() -> Self {
611        /// To hold the invariant that all ids are unique, and considering that slotmap
612        /// increases their IDs from `0`, we can decrease ours from `u64::MAX` so these
613        /// two will never conflict (u64 is way too large).
614        static UNIQUE_NON_CONFLICTING_ID_GENERATOR: AtomicU64 = AtomicU64::new(u64::MAX);
615        let entity_id = UNIQUE_NON_CONFLICTING_ID_GENERATOR.fetch_sub(1, SeqCst);
616
617        Self {
618            // Safety:
619            //   Docs say this is safe but can be unspecified if slotmap changes the representation
620            //   after `1.0.7`, that said, providing a valid entity_id here is not necessary as long
621            //   as we guarantee that `entity_id` is never used if `entity_ref_counts` equals
622            //   to `Weak::new()` (that is, it's unable to upgrade), that is the invariant that
623            //   actually needs to be hold true.
624            //
625            //   And there is no sane reason to read an entity slot if `entity_ref_counts` can't be
626            //   read in the first place, so we're good!
627            entity_id: entity_id.into(),
628            entity_type: TypeId::of::<()>(),
629            entity_ref_counts: Weak::new(),
630        }
631    }
632}
633
634impl std::fmt::Debug for AnyWeakEntity {
635    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
636        f.debug_struct(type_name::<Self>())
637            .field("entity_id", &self.entity_id)
638            .field("entity_type", &self.entity_type)
639            .finish()
640    }
641}
642
643impl<T> From<WeakEntity<T>> for AnyWeakEntity {
644    #[inline]
645    fn from(entity: WeakEntity<T>) -> Self {
646        entity.any_entity
647    }
648}
649
650impl Hash for AnyWeakEntity {
651    #[inline]
652    fn hash<H: Hasher>(&self, state: &mut H) {
653        self.entity_id.hash(state);
654    }
655}
656
657impl PartialEq for AnyWeakEntity {
658    #[inline]
659    fn eq(&self, other: &Self) -> bool {
660        self.entity_id == other.entity_id
661    }
662}
663
664impl Eq for AnyWeakEntity {}
665
666impl Ord for AnyWeakEntity {
667    #[inline]
668    fn cmp(&self, other: &Self) -> Ordering {
669        self.entity_id.cmp(&other.entity_id)
670    }
671}
672
673impl PartialOrd for AnyWeakEntity {
674    #[inline]
675    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
676        Some(self.cmp(other))
677    }
678}
679
680/// A weak reference to a entity of the given type.
681#[derive(Deref, DerefMut)]
682pub struct WeakEntity<T> {
683    #[deref]
684    #[deref_mut]
685    any_entity: AnyWeakEntity,
686    entity_type: PhantomData<fn(T) -> T>,
687}
688
689impl<T> std::fmt::Debug for WeakEntity<T> {
690    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
691        f.debug_struct(type_name::<Self>())
692            .field("entity_id", &self.any_entity.entity_id)
693            .field("entity_type", &type_name::<T>())
694            .finish()
695    }
696}
697
698impl<T> Clone for WeakEntity<T> {
699    fn clone(&self) -> Self {
700        Self {
701            any_entity: self.any_entity.clone(),
702            entity_type: self.entity_type,
703        }
704    }
705}
706
707impl<T: 'static> WeakEntity<T> {
708    /// Upgrade this weak entity reference into a strong entity reference
709    pub fn upgrade(&self) -> Option<Entity<T>> {
710        Some(Entity {
711            any_entity: self.any_entity.upgrade()?,
712            entity_type: self.entity_type,
713        })
714    }
715
716    /// Updates the entity referenced by this handle with the given function if
717    /// the referenced entity still exists. Returns an error if the entity has
718    /// been released.
719    pub fn update<C, R>(
720        &self,
721        cx: &mut C,
722        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
723    ) -> Result<R>
724    where
725        C: AppContext,
726        Result<C::Result<R>>: crate::Flatten<R>,
727    {
728        crate::Flatten::flatten(
729            self.upgrade()
730                .context("entity released")
731                .map(|this| cx.update_entity(&this, update)),
732        )
733    }
734
735    /// Updates the entity referenced by this handle with the given function if
736    /// the referenced entity still exists, within a visual context that has a window.
737    /// Returns an error if the entity has been released.
738    pub fn update_in<C, R>(
739        &self,
740        cx: &mut C,
741        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
742    ) -> Result<R>
743    where
744        C: VisualContext,
745        Result<C::Result<R>>: crate::Flatten<R>,
746    {
747        let window = cx.window_handle();
748        let this = self.upgrade().context("entity released")?;
749
750        crate::Flatten::flatten(window.update(cx, |_, window, cx| {
751            this.update(cx, |entity, cx| update(entity, window, cx))
752        }))
753    }
754
755    /// Reads the entity referenced by this handle with the given function if
756    /// the referenced entity still exists. Returns an error if the entity has
757    /// been released.
758    pub fn read_with<C, R>(&self, cx: &C, read: impl FnOnce(&T, &App) -> R) -> Result<R>
759    where
760        C: AppContext,
761        Result<C::Result<R>>: crate::Flatten<R>,
762    {
763        crate::Flatten::flatten(
764            self.upgrade()
765                .context("entity released")
766                .map(|this| cx.read_entity(&this, read)),
767        )
768    }
769
770    /// Create a new weak entity that can never be upgraded.
771    #[inline]
772    pub fn new_invalid() -> Self {
773        Self {
774            any_entity: AnyWeakEntity::new_invalid(),
775            entity_type: PhantomData,
776        }
777    }
778}
779
780impl<T> Hash for WeakEntity<T> {
781    #[inline]
782    fn hash<H: Hasher>(&self, state: &mut H) {
783        self.any_entity.hash(state);
784    }
785}
786
787impl<T> PartialEq for WeakEntity<T> {
788    #[inline]
789    fn eq(&self, other: &Self) -> bool {
790        self.any_entity == other.any_entity
791    }
792}
793
794impl<T> Eq for WeakEntity<T> {}
795
796impl<T> PartialEq<Entity<T>> for WeakEntity<T> {
797    #[inline]
798    fn eq(&self, other: &Entity<T>) -> bool {
799        self.entity_id() == other.any_entity.entity_id()
800    }
801}
802
803impl<T: 'static> Ord for WeakEntity<T> {
804    #[inline]
805    fn cmp(&self, other: &Self) -> Ordering {
806        self.entity_id().cmp(&other.entity_id())
807    }
808}
809
810impl<T: 'static> PartialOrd for WeakEntity<T> {
811    #[inline]
812    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
813        Some(self.cmp(other))
814    }
815}
816
817#[cfg(any(test, feature = "leak-detection"))]
818static LEAK_BACKTRACE: std::sync::LazyLock<bool> =
819    std::sync::LazyLock::new(|| std::env::var("LEAK_BACKTRACE").is_ok_and(|b| !b.is_empty()));
820
821#[cfg(any(test, feature = "leak-detection"))]
822#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
823pub(crate) struct HandleId {
824    id: u64, // id of the handle itself, not the pointed at object
825}
826
827#[cfg(any(test, feature = "leak-detection"))]
828pub(crate) struct LeakDetector {
829    next_handle_id: u64,
830    entity_handles: HashMap<EntityId, HashMap<HandleId, Option<backtrace::Backtrace>>>,
831}
832
833#[cfg(any(test, feature = "leak-detection"))]
834impl LeakDetector {
835    #[track_caller]
836    pub fn handle_created(&mut self, entity_id: EntityId) -> HandleId {
837        let id = util::post_inc(&mut self.next_handle_id);
838        let handle_id = HandleId { id };
839        let handles = self.entity_handles.entry(entity_id).or_default();
840        handles.insert(
841            handle_id,
842            LEAK_BACKTRACE.then(backtrace::Backtrace::new_unresolved),
843        );
844        handle_id
845    }
846
847    pub fn handle_released(&mut self, entity_id: EntityId, handle_id: HandleId) {
848        let handles = self.entity_handles.entry(entity_id).or_default();
849        handles.remove(&handle_id);
850    }
851
852    pub fn assert_released(&mut self, entity_id: EntityId) {
853        let handles = self.entity_handles.entry(entity_id).or_default();
854        if !handles.is_empty() {
855            for backtrace in handles.values_mut() {
856                if let Some(mut backtrace) = backtrace.take() {
857                    backtrace.resolve();
858                    eprintln!("Leaked handle: {:#?}", backtrace);
859                } else {
860                    eprintln!("Leaked handle: export LEAK_BACKTRACE to find allocation site");
861                }
862            }
863            panic!();
864        }
865    }
866}
867
868#[cfg(test)]
869mod test {
870    use crate::EntityMap;
871
872    struct TestEntity {
873        pub i: i32,
874    }
875
876    #[test]
877    fn test_entity_map_slot_assignment_before_cleanup() {
878        // Tests that slots are not re-used before take_dropped.
879        let mut entity_map = EntityMap::new();
880
881        let slot = entity_map.reserve::<TestEntity>();
882        entity_map.insert(slot, TestEntity { i: 1 });
883
884        let slot = entity_map.reserve::<TestEntity>();
885        entity_map.insert(slot, TestEntity { i: 2 });
886
887        let dropped = entity_map.take_dropped();
888        assert_eq!(dropped.len(), 2);
889
890        assert_eq!(
891            dropped
892                .into_iter()
893                .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
894                .collect::<Vec<i32>>(),
895            vec![1, 2],
896        );
897    }
898
899    #[test]
900    fn test_entity_map_weak_upgrade_before_cleanup() {
901        // Tests that weak handles are not upgraded before take_dropped
902        let mut entity_map = EntityMap::new();
903
904        let slot = entity_map.reserve::<TestEntity>();
905        let handle = entity_map.insert(slot, TestEntity { i: 1 });
906        let weak = handle.downgrade();
907        drop(handle);
908
909        let strong = weak.upgrade();
910        assert_eq!(strong, None);
911
912        let dropped = entity_map.take_dropped();
913        assert_eq!(dropped.len(), 1);
914
915        assert_eq!(
916            dropped
917                .into_iter()
918                .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
919                .collect::<Vec<i32>>(),
920            vec![1],
921        );
922    }
923}