entity_map.rs

  1use crate::{App, AppContext, VisualContext, Window, seal::Sealed};
  2use anyhow::{Result, anyhow};
  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::{AtomicUsize, Ordering::SeqCst},
 19    },
 20    thread::panicking,
 21};
 22
 23#[cfg(any(test, feature = "leak-detection"))]
 24use collections::HashMap;
 25
 26use super::Context;
 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<'a, T>(&mut self, pointer: &'a Entity<T>) -> Lease<'a, 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            pointer,
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
128            .insert(lease.pointer.entity_id, lease.entity.take().unwrap());
129    }
130
131    pub fn read<T: 'static>(&self, entity: &Entity<T>) -> &T {
132        self.assert_valid_context(entity);
133        let mut accessed_entities = self.accessed_entities.borrow_mut();
134        accessed_entities.insert(entity.entity_id);
135
136        self.entities
137            .get(entity.entity_id)
138            .and_then(|entity| entity.downcast_ref())
139            .unwrap_or_else(|| double_lease_panic::<T>("read"))
140    }
141
142    fn assert_valid_context(&self, entity: &AnyEntity) {
143        debug_assert!(
144            Weak::ptr_eq(&entity.entity_map, &Arc::downgrade(&self.ref_counts)),
145            "used a entity with the wrong context"
146        );
147    }
148
149    pub fn extend_accessed(&mut self, entities: &FxHashSet<EntityId>) {
150        self.accessed_entities
151            .borrow_mut()
152            .extend(entities.iter().copied());
153    }
154
155    pub fn clear_accessed(&mut self) {
156        self.accessed_entities.borrow_mut().clear();
157    }
158
159    pub fn take_dropped(&mut self) -> Vec<(EntityId, Box<dyn Any>)> {
160        let mut ref_counts = self.ref_counts.write();
161        let dropped_entity_ids = mem::take(&mut ref_counts.dropped_entity_ids);
162        let mut accessed_entities = self.accessed_entities.borrow_mut();
163
164        dropped_entity_ids
165            .into_iter()
166            .filter_map(|entity_id| {
167                let count = ref_counts.counts.remove(entity_id).unwrap();
168                debug_assert_eq!(
169                    count.load(SeqCst),
170                    0,
171                    "dropped an entity that was referenced"
172                );
173                accessed_entities.remove(&entity_id);
174                // If the EntityId was allocated with `Context::reserve`,
175                // the entity may not have been inserted.
176                Some((entity_id, self.entities.remove(entity_id)?))
177            })
178            .collect()
179    }
180}
181
182#[track_caller]
183fn double_lease_panic<T>(operation: &str) -> ! {
184    panic!(
185        "cannot {operation} {} while it is already being updated",
186        std::any::type_name::<T>()
187    )
188}
189
190pub(crate) struct Lease<'a, T> {
191    entity: Option<Box<dyn Any>>,
192    pub pointer: &'a Entity<T>,
193    entity_type: PhantomData<T>,
194}
195
196impl<T: 'static> core::ops::Deref for Lease<'_, T> {
197    type Target = T;
198
199    fn deref(&self) -> &Self::Target {
200        self.entity.as_ref().unwrap().downcast_ref().unwrap()
201    }
202}
203
204impl<T: 'static> core::ops::DerefMut for Lease<'_, T> {
205    fn deref_mut(&mut self) -> &mut Self::Target {
206        self.entity.as_mut().unwrap().downcast_mut().unwrap()
207    }
208}
209
210impl<T> Drop for Lease<'_, T> {
211    fn drop(&mut self) {
212        if self.entity.is_some() && !panicking() {
213            panic!("Leases must be ended with EntityMap::end_lease")
214        }
215    }
216}
217
218#[derive(Deref, DerefMut)]
219pub(crate) struct Slot<T>(Entity<T>);
220
221/// A dynamically typed reference to a entity, which can be downcast into a `Entity<T>`.
222pub struct AnyEntity {
223    pub(crate) entity_id: EntityId,
224    pub(crate) entity_type: TypeId,
225    entity_map: Weak<RwLock<EntityRefCounts>>,
226    #[cfg(any(test, feature = "leak-detection"))]
227    handle_id: HandleId,
228}
229
230impl AnyEntity {
231    fn new(id: EntityId, entity_type: TypeId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self {
232        Self {
233            entity_id: id,
234            entity_type,
235            entity_map: entity_map.clone(),
236            #[cfg(any(test, feature = "leak-detection"))]
237            handle_id: entity_map
238                .upgrade()
239                .unwrap()
240                .write()
241                .leak_detector
242                .handle_created(id),
243        }
244    }
245
246    /// Returns the id associated with this entity.
247    pub fn entity_id(&self) -> EntityId {
248        self.entity_id
249    }
250
251    /// Returns the [TypeId] associated with this entity.
252    pub fn entity_type(&self) -> TypeId {
253        self.entity_type
254    }
255
256    /// Converts this entity handle into a weak variant, which does not prevent it from being released.
257    pub fn downgrade(&self) -> AnyWeakEntity {
258        AnyWeakEntity {
259            entity_id: self.entity_id,
260            entity_type: self.entity_type,
261            entity_ref_counts: self.entity_map.clone(),
262        }
263    }
264
265    /// Converts this entity handle into a strongly-typed entity handle of the given type.
266    /// If this entity handle is not of the specified type, returns itself as an error variant.
267    pub fn downcast<T: 'static>(self) -> Result<Entity<T>, AnyEntity> {
268        if TypeId::of::<T>() == self.entity_type {
269            Ok(Entity {
270                any_entity: self,
271                entity_type: PhantomData,
272            })
273        } else {
274            Err(self)
275        }
276    }
277}
278
279impl Clone for AnyEntity {
280    fn clone(&self) -> Self {
281        if let Some(entity_map) = self.entity_map.upgrade() {
282            let entity_map = entity_map.read();
283            let count = entity_map
284                .counts
285                .get(self.entity_id)
286                .expect("detected over-release of a entity");
287            let prev_count = count.fetch_add(1, SeqCst);
288            assert_ne!(prev_count, 0, "Detected over-release of a entity.");
289        }
290
291        Self {
292            entity_id: self.entity_id,
293            entity_type: self.entity_type,
294            entity_map: self.entity_map.clone(),
295            #[cfg(any(test, feature = "leak-detection"))]
296            handle_id: self
297                .entity_map
298                .upgrade()
299                .unwrap()
300                .write()
301                .leak_detector
302                .handle_created(self.entity_id),
303        }
304    }
305}
306
307impl Drop for AnyEntity {
308    fn drop(&mut self) {
309        if let Some(entity_map) = self.entity_map.upgrade() {
310            let entity_map = entity_map.upgradable_read();
311            let count = entity_map
312                .counts
313                .get(self.entity_id)
314                .expect("detected over-release of a handle.");
315            let prev_count = count.fetch_sub(1, SeqCst);
316            assert_ne!(prev_count, 0, "Detected over-release of a entity.");
317            if prev_count == 1 {
318                // We were the last reference to this entity, so we can remove it.
319                let mut entity_map = RwLockUpgradableReadGuard::upgrade(entity_map);
320                entity_map.dropped_entity_ids.push(self.entity_id);
321            }
322        }
323
324        #[cfg(any(test, feature = "leak-detection"))]
325        if let Some(entity_map) = self.entity_map.upgrade() {
326            entity_map
327                .write()
328                .leak_detector
329                .handle_released(self.entity_id, self.handle_id)
330        }
331    }
332}
333
334impl<T> From<Entity<T>> for AnyEntity {
335    fn from(entity: Entity<T>) -> Self {
336        entity.any_entity
337    }
338}
339
340impl Hash for AnyEntity {
341    fn hash<H: Hasher>(&self, state: &mut H) {
342        self.entity_id.hash(state);
343    }
344}
345
346impl PartialEq for AnyEntity {
347    fn eq(&self, other: &Self) -> bool {
348        self.entity_id == other.entity_id
349    }
350}
351
352impl Eq for AnyEntity {}
353
354impl Ord for AnyEntity {
355    fn cmp(&self, other: &Self) -> Ordering {
356        self.entity_id.cmp(&other.entity_id)
357    }
358}
359
360impl PartialOrd for AnyEntity {
361    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
362        Some(self.cmp(other))
363    }
364}
365
366impl std::fmt::Debug for AnyEntity {
367    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368        f.debug_struct("AnyEntity")
369            .field("entity_id", &self.entity_id.as_u64())
370            .finish()
371    }
372}
373
374/// A strong, well typed reference to a struct which is managed
375/// by GPUI
376#[derive(Deref, DerefMut)]
377pub struct Entity<T> {
378    #[deref]
379    #[deref_mut]
380    pub(crate) any_entity: AnyEntity,
381    pub(crate) entity_type: PhantomData<T>,
382}
383
384unsafe impl<T> Send for Entity<T> {}
385unsafe impl<T> Sync for Entity<T> {}
386impl<T> Sealed for Entity<T> {}
387
388impl<T: 'static> Entity<T> {
389    fn new(id: EntityId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self
390    where
391        T: 'static,
392    {
393        Self {
394            any_entity: AnyEntity::new(id, TypeId::of::<T>(), entity_map),
395            entity_type: PhantomData,
396        }
397    }
398
399    /// Get the entity ID associated with this entity
400    pub fn entity_id(&self) -> EntityId {
401        self.any_entity.entity_id
402    }
403
404    /// Downgrade this entity pointer to a non-retaining weak pointer
405    pub fn downgrade(&self) -> WeakEntity<T> {
406        WeakEntity {
407            any_entity: self.any_entity.downgrade(),
408            entity_type: self.entity_type,
409        }
410    }
411
412    /// Upgrade the given weak pointer to a retaining pointer, if it still exists
413    pub fn upgrade_from(weak: &WeakEntity<T>) -> Option<Self>
414    where
415        Self: Sized,
416    {
417        Some(Entity {
418            any_entity: weak.any_entity.upgrade()?,
419            entity_type: weak.entity_type,
420        })
421    }
422
423    /// Convert this into a dynamically typed entity.
424    pub fn into_any(self) -> AnyEntity {
425        self.any_entity
426    }
427
428    /// Grab a reference to this entity from the context.
429    pub fn read<'a>(&self, cx: &'a App) -> &'a T {
430        cx.entities.read(self)
431    }
432
433    /// Read the entity referenced by this handle with the given function.
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    ///
444    /// The update function receives a context appropriate for its environment.
445    /// When updating in an `App`, it receives a `Context`.
446    /// When updating in a `Window`, it receives a `Window` and a `Context`.
447    pub fn update<C, R>(
448        &self,
449        cx: &mut C,
450        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
451    ) -> C::Result<R>
452    where
453        C: AppContext,
454    {
455        cx.update_entity(self, update)
456    }
457
458    /// Updates the entity referenced by this handle with the given function if
459    /// the referenced entity still exists, within a visual context that has a window.
460    /// Returns an error if the entity has been released.
461    pub fn update_in<C, R>(
462        &self,
463        cx: &mut C,
464        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
465    ) -> C::Result<R>
466    where
467        C: VisualContext,
468    {
469        cx.update_window_entity(self, update)
470    }
471}
472
473impl<T> Clone for Entity<T> {
474    fn clone(&self) -> Self {
475        Self {
476            any_entity: self.any_entity.clone(),
477            entity_type: self.entity_type,
478        }
479    }
480}
481
482impl<T> std::fmt::Debug for Entity<T> {
483    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
484        f.debug_struct("Entity")
485            .field("entity_id", &self.any_entity.entity_id)
486            .field("entity_type", &type_name::<T>())
487            .finish()
488    }
489}
490
491impl<T> Hash for Entity<T> {
492    fn hash<H: Hasher>(&self, state: &mut H) {
493        self.any_entity.hash(state);
494    }
495}
496
497impl<T> PartialEq for Entity<T> {
498    fn eq(&self, other: &Self) -> bool {
499        self.any_entity == other.any_entity
500    }
501}
502
503impl<T> Eq for Entity<T> {}
504
505impl<T> PartialEq<WeakEntity<T>> for Entity<T> {
506    fn eq(&self, other: &WeakEntity<T>) -> bool {
507        self.any_entity.entity_id() == other.entity_id()
508    }
509}
510
511impl<T: 'static> Ord for Entity<T> {
512    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
513        self.entity_id().cmp(&other.entity_id())
514    }
515}
516
517impl<T: 'static> PartialOrd for Entity<T> {
518    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
519        Some(self.cmp(other))
520    }
521}
522
523/// A type erased, weak reference to a entity.
524#[derive(Clone)]
525pub struct AnyWeakEntity {
526    pub(crate) entity_id: EntityId,
527    entity_type: TypeId,
528    entity_ref_counts: Weak<RwLock<EntityRefCounts>>,
529}
530
531impl AnyWeakEntity {
532    /// Get the entity ID associated with this weak reference.
533    pub fn entity_id(&self) -> EntityId {
534        self.entity_id
535    }
536
537    /// Check if this weak handle can be upgraded, or if the entity has already been dropped
538    pub fn is_upgradable(&self) -> bool {
539        let ref_count = self
540            .entity_ref_counts
541            .upgrade()
542            .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
543            .unwrap_or(0);
544        ref_count > 0
545    }
546
547    /// Upgrade this weak entity reference to a strong reference.
548    pub fn upgrade(&self) -> Option<AnyEntity> {
549        let ref_counts = &self.entity_ref_counts.upgrade()?;
550        let ref_counts = ref_counts.read();
551        let ref_count = ref_counts.counts.get(self.entity_id)?;
552
553        // entity_id is in dropped_entity_ids
554        if ref_count.load(SeqCst) == 0 {
555            return None;
556        }
557        ref_count.fetch_add(1, SeqCst);
558        drop(ref_counts);
559
560        Some(AnyEntity {
561            entity_id: self.entity_id,
562            entity_type: self.entity_type,
563            entity_map: self.entity_ref_counts.clone(),
564            #[cfg(any(test, feature = "leak-detection"))]
565            handle_id: self
566                .entity_ref_counts
567                .upgrade()
568                .unwrap()
569                .write()
570                .leak_detector
571                .handle_created(self.entity_id),
572        })
573    }
574
575    /// Assert that entity referenced by this weak handle has been released.
576    #[cfg(any(test, feature = "leak-detection"))]
577    pub fn assert_released(&self) {
578        self.entity_ref_counts
579            .upgrade()
580            .unwrap()
581            .write()
582            .leak_detector
583            .assert_released(self.entity_id);
584
585        if self
586            .entity_ref_counts
587            .upgrade()
588            .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
589            .is_some()
590        {
591            panic!(
592                "entity was recently dropped but resources are retained until the end of the effect cycle."
593            )
594        }
595    }
596}
597
598impl std::fmt::Debug for AnyWeakEntity {
599    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
600        f.debug_struct(type_name::<Self>())
601            .field("entity_id", &self.entity_id)
602            .field("entity_type", &self.entity_type)
603            .finish()
604    }
605}
606
607impl<T> From<WeakEntity<T>> for AnyWeakEntity {
608    fn from(entity: WeakEntity<T>) -> Self {
609        entity.any_entity
610    }
611}
612
613impl Hash for AnyWeakEntity {
614    fn hash<H: Hasher>(&self, state: &mut H) {
615        self.entity_id.hash(state);
616    }
617}
618
619impl PartialEq for AnyWeakEntity {
620    fn eq(&self, other: &Self) -> bool {
621        self.entity_id == other.entity_id
622    }
623}
624
625impl Eq for AnyWeakEntity {}
626
627impl Ord for AnyWeakEntity {
628    fn cmp(&self, other: &Self) -> Ordering {
629        self.entity_id.cmp(&other.entity_id)
630    }
631}
632
633impl PartialOrd for AnyWeakEntity {
634    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
635        Some(self.cmp(other))
636    }
637}
638
639/// A weak reference to a entity of the given type.
640#[derive(Deref, DerefMut)]
641pub struct WeakEntity<T> {
642    #[deref]
643    #[deref_mut]
644    any_entity: AnyWeakEntity,
645    entity_type: PhantomData<T>,
646}
647
648impl<T> std::fmt::Debug for WeakEntity<T> {
649    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
650        f.debug_struct(&type_name::<Self>())
651            .field("entity_id", &self.any_entity.entity_id)
652            .field("entity_type", &type_name::<T>())
653            .finish()
654    }
655}
656
657unsafe impl<T> Send for WeakEntity<T> {}
658unsafe impl<T> Sync for WeakEntity<T> {}
659
660impl<T> Clone for WeakEntity<T> {
661    fn clone(&self) -> Self {
662        Self {
663            any_entity: self.any_entity.clone(),
664            entity_type: self.entity_type,
665        }
666    }
667}
668
669impl<T: 'static> WeakEntity<T> {
670    /// Upgrade this weak entity reference into a strong entity reference
671    pub fn upgrade(&self) -> Option<Entity<T>> {
672        // Delegate to the trait implementation to keep behavior in one place.
673        Entity::upgrade_from(self)
674    }
675
676    /// Updates the entity referenced by this handle with the given function if
677    /// the referenced entity still exists. Returns an error if the entity has
678    /// been released.
679    pub fn update<C, R>(
680        &self,
681        cx: &mut C,
682        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
683    ) -> Result<R>
684    where
685        C: AppContext,
686        Result<C::Result<R>>: crate::Flatten<R>,
687    {
688        crate::Flatten::flatten(
689            self.upgrade()
690                .ok_or_else(|| anyhow!("entity released"))
691                .map(|this| cx.update_entity(&this, update)),
692        )
693    }
694
695    /// Updates the entity referenced by this handle with the given function if
696    /// the referenced entity still exists, within a visual context that has a window.
697    /// Returns an error if the entity has been released.
698    pub fn update_in<C, R>(
699        &self,
700        cx: &mut C,
701        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
702    ) -> Result<R>
703    where
704        C: VisualContext,
705        Result<C::Result<R>>: crate::Flatten<R>,
706    {
707        let window = cx.window_handle();
708        let this = self.upgrade().ok_or_else(|| anyhow!("entity released"))?;
709
710        crate::Flatten::flatten(window.update(cx, |_, window, cx| {
711            this.update(cx, |entity, cx| update(entity, window, cx))
712        }))
713    }
714
715    /// Reads the entity referenced by this handle with the given function if
716    /// the referenced entity still exists. Returns an error if the entity has
717    /// been released.
718    pub fn read_with<C, R>(&self, cx: &C, read: impl FnOnce(&T, &App) -> R) -> Result<R>
719    where
720        C: AppContext,
721        Result<C::Result<R>>: crate::Flatten<R>,
722    {
723        crate::Flatten::flatten(
724            self.upgrade()
725                .ok_or_else(|| anyhow!("entity release"))
726                .map(|this| cx.read_entity(&this, read)),
727        )
728    }
729}
730
731impl<T> Hash for WeakEntity<T> {
732    fn hash<H: Hasher>(&self, state: &mut H) {
733        self.any_entity.hash(state);
734    }
735}
736
737impl<T> PartialEq for WeakEntity<T> {
738    fn eq(&self, other: &Self) -> bool {
739        self.any_entity == other.any_entity
740    }
741}
742
743impl<T> Eq for WeakEntity<T> {}
744
745impl<T> PartialEq<Entity<T>> for WeakEntity<T> {
746    fn eq(&self, other: &Entity<T>) -> bool {
747        self.entity_id() == other.any_entity.entity_id()
748    }
749}
750
751impl<T: 'static> Ord for WeakEntity<T> {
752    fn cmp(&self, other: &Self) -> Ordering {
753        self.entity_id().cmp(&other.entity_id())
754    }
755}
756
757impl<T: 'static> PartialOrd for WeakEntity<T> {
758    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
759        Some(self.cmp(other))
760    }
761}
762
763#[cfg(any(test, feature = "leak-detection"))]
764static LEAK_BACKTRACE: std::sync::LazyLock<bool> =
765    std::sync::LazyLock::new(|| std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty()));
766
767#[cfg(any(test, feature = "leak-detection"))]
768#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
769pub(crate) struct HandleId {
770    id: u64, // id of the handle itself, not the pointed at object
771}
772
773#[cfg(any(test, feature = "leak-detection"))]
774pub(crate) struct LeakDetector {
775    next_handle_id: u64,
776    entity_handles: HashMap<EntityId, HashMap<HandleId, Option<backtrace::Backtrace>>>,
777}
778
779#[cfg(any(test, feature = "leak-detection"))]
780impl LeakDetector {
781    #[track_caller]
782    pub fn handle_created(&mut self, entity_id: EntityId) -> HandleId {
783        let id = util::post_inc(&mut self.next_handle_id);
784        let handle_id = HandleId { id };
785        let handles = self.entity_handles.entry(entity_id).or_default();
786        handles.insert(
787            handle_id,
788            LEAK_BACKTRACE.then(backtrace::Backtrace::new_unresolved),
789        );
790        handle_id
791    }
792
793    pub fn handle_released(&mut self, entity_id: EntityId, handle_id: HandleId) {
794        let handles = self.entity_handles.entry(entity_id).or_default();
795        handles.remove(&handle_id);
796    }
797
798    pub fn assert_released(&mut self, entity_id: EntityId) {
799        let handles = self.entity_handles.entry(entity_id).or_default();
800        if !handles.is_empty() {
801            for backtrace in handles.values_mut() {
802                if let Some(mut backtrace) = backtrace.take() {
803                    backtrace.resolve();
804                    eprintln!("Leaked handle: {:#?}", backtrace);
805                } else {
806                    eprintln!("Leaked handle: export LEAK_BACKTRACE to find allocation site");
807                }
808            }
809            panic!();
810        }
811    }
812}
813
814#[cfg(test)]
815mod test {
816    use crate::EntityMap;
817
818    struct TestEntity {
819        pub i: i32,
820    }
821
822    #[test]
823    fn test_entity_map_slot_assignment_before_cleanup() {
824        // Tests that slots are not re-used before take_dropped.
825        let mut entity_map = EntityMap::new();
826
827        let slot = entity_map.reserve::<TestEntity>();
828        entity_map.insert(slot, TestEntity { i: 1 });
829
830        let slot = entity_map.reserve::<TestEntity>();
831        entity_map.insert(slot, TestEntity { i: 2 });
832
833        let dropped = entity_map.take_dropped();
834        assert_eq!(dropped.len(), 2);
835
836        assert_eq!(
837            dropped
838                .into_iter()
839                .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
840                .collect::<Vec<i32>>(),
841            vec![1, 2],
842        );
843    }
844
845    #[test]
846    fn test_entity_map_weak_upgrade_before_cleanup() {
847        // Tests that weak handles are not upgraded before take_dropped
848        let mut entity_map = EntityMap::new();
849
850        let slot = entity_map.reserve::<TestEntity>();
851        let handle = entity_map.insert(slot, TestEntity { i: 1 });
852        let weak = handle.downgrade();
853        drop(handle);
854
855        let strong = weak.upgrade();
856        assert_eq!(strong, None);
857
858        let dropped = entity_map.take_dropped();
859        assert_eq!(dropped.len(), 1);
860
861        assert_eq!(
862            dropped
863                .into_iter()
864                .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
865                .collect::<Vec<i32>>(),
866            vec![1],
867        );
868    }
869}