Skip to main content

gpui/app/
entity_map.rs

1// Modified by Longbridge for gpui-fast.
2use crate::{App, AppContext, GpuiBorrow, VisualContext, Window, seal::Sealed};
3use anyhow::{Context as _, Result};
4use collections::FxHashSet;
5use derive_more::{Deref, DerefMut};
6use parking_lot::{RwLock, RwLockUpgradableReadGuard};
7use slotmap::{KeyData, SecondaryMap, SlotMap};
8use std::{
9    any::{Any, TypeId, type_name},
10    cell::RefCell,
11    cmp::Ordering,
12    fmt::{self, Display},
13    hash::{Hash, Hasher},
14    marker::PhantomData,
15    mem,
16    num::NonZeroU64,
17    sync::{
18        Arc, Weak,
19        atomic::{AtomicU64, AtomicUsize, Ordering::SeqCst},
20    },
21    thread::panicking,
22};
23
24use super::Context;
25use crate::util::atomic_incr_if_not_zero;
26#[cfg(any(test, gpui_leak_detection))]
27use collections::HashMap;
28
29slotmap::new_key_type! {
30    /// A unique identifier for a entity across the application.
31    pub struct EntityId;
32}
33
34impl From<u64> for EntityId {
35    fn from(value: u64) -> Self {
36        Self(KeyData::from_ffi(value))
37    }
38}
39
40impl EntityId {
41    /// Converts this entity id to a [NonZeroU64]
42    pub fn as_non_zero_u64(self) -> NonZeroU64 {
43        NonZeroU64::new(self.0.as_ffi()).unwrap()
44    }
45
46    /// Converts this entity id to a [u64]
47    pub fn as_u64(self) -> u64 {
48        self.0.as_ffi()
49    }
50}
51
52impl Display for EntityId {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        write!(f, "{}", self.as_u64())
55    }
56}
57
58pub(crate) struct EntityMap {
59    entities: SecondaryMap<EntityId, Box<dyn Any>>,
60    accessed_entities: RefCell<AccessedEntities>,
61    pub(crate) access_log: crate::fast::dependencies::EntityAccessLog,
62    pub(crate) ref_counts: Arc<RwLock<EntityRefCounts>>,
63}
64
65/// The entities accessed during the current draw. An access is recorded only
66/// in the innermost open scope, or in `frame` outside any scope, and a scope's
67/// accesses are added to the one around it when it ends. Each scope therefore
68/// collects exactly what was accessed inside it, without copying what the
69/// draw accessed before it began, and `frame` ends up with every access.
70struct AccessedEntities {
71    /// Every entity accessed during the draw: the window subscribes to
72    /// exactly this set when the draw ends. Accesses outside any scope land
73    /// here directly, and a scope's accesses reach it when the outermost open
74    /// scope ends. It is the innermost set only while no scope is open, and
75    /// unlike a scope it is never ended.
76    frame: FxHashSet<EntityId>,
77    /// The scopes currently recording, innermost last.
78    scopes: Vec<FxHashSet<EntityId>>,
79}
80
81impl AccessedEntities {
82    fn innermost(&mut self) -> &mut FxHashSet<EntityId> {
83        self.scopes.last_mut().unwrap_or(&mut self.frame)
84    }
85}
86
87#[doc(hidden)]
88pub(crate) struct EntityRefCounts {
89    pub(crate) counts: SlotMap<EntityId, AtomicUsize>,
90    dropped_entity_ids: Vec<EntityId>,
91    #[cfg(any(test, gpui_leak_detection))]
92    leak_detector: LeakDetector,
93}
94
95pub(super) struct LeaseInner {
96    pub(super) entity: Option<Box<dyn Any>>,
97}
98
99impl EntityMap {
100    pub fn new() -> Self {
101        Self {
102            entities: SecondaryMap::new(),
103            accessed_entities: RefCell::new(AccessedEntities {
104                frame: FxHashSet::default(),
105                scopes: Vec::new(),
106            }),
107            access_log: crate::fast::dependencies::EntityAccessLog::default(),
108            ref_counts: Arc::new(RwLock::new(EntityRefCounts {
109                counts: SlotMap::with_key(),
110                dropped_entity_ids: Vec::new(),
111                #[cfg(any(test, gpui_leak_detection))]
112                leak_detector: LeakDetector {
113                    next_handle_id: 0,
114                    entity_handles: HashMap::default(),
115                },
116            })),
117        }
118    }
119
120    #[doc(hidden)]
121    pub fn ref_counts_drop_handle(&self) -> Arc<RwLock<EntityRefCounts>> {
122        self.ref_counts.clone()
123    }
124
125    /// Captures a snapshot of all entities that currently have alive handles.
126    ///
127    /// The returned [`LeakDetectorSnapshot`] can later be passed to
128    /// [`assert_no_new_leaks`](Self::assert_no_new_leaks) to verify that no
129    /// entities created after the snapshot are still alive.
130    #[cfg(any(test, gpui_leak_detection))]
131    pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
132        self.ref_counts.read().leak_detector.snapshot()
133    }
134
135    /// Asserts that no entities created after `snapshot` still have alive handles.
136    ///
137    /// See [`LeakDetector::assert_no_new_leaks`] for details.
138    #[cfg(any(test, gpui_leak_detection))]
139    pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
140        self.ref_counts
141            .read()
142            .leak_detector
143            .assert_no_new_leaks(snapshot)
144    }
145
146    /// Reserve a slot for an entity, which you can subsequently use with `insert`.
147    pub fn reserve<T: 'static>(&self) -> Slot<T> {
148        let id = self.ref_counts.write().counts.insert(1.into());
149        Slot(Entity::new(id, Arc::downgrade(&self.ref_counts)))
150    }
151
152    /// Insert an entity into a slot obtained by calling `reserve`.
153    pub fn insert<T>(&mut self, slot: Slot<T>, entity: T) -> Entity<T>
154    where
155        T: 'static,
156    {
157        self.accessed_entities
158            .get_mut()
159            .innermost()
160            .insert(slot.entity_id);
161        crate::fast::dependencies::note_access(self, slot.entity_id);
162
163        let handle = slot.0;
164        self.entities.insert(handle.entity_id, Box::new(entity));
165        handle
166    }
167
168    /// Move an entity to the stack.
169    #[track_caller]
170    pub fn lease<T>(&mut self, pointer: &Entity<T>) -> Lease<T> {
171        Lease {
172            inner: self.lease_erased(pointer, type_name::<T>()),
173            id: pointer.entity_id,
174            entity_type: PhantomData,
175        }
176    }
177
178    /// Returns an entity after moving it to the stack.
179    pub fn end_lease<T>(&mut self, lease: Lease<T>) {
180        self.end_lease_erased(lease.id, lease.inner);
181    }
182
183    #[inline(always)]
184    pub fn read<T: 'static>(&self, entity: &Entity<T>) -> &T {
185        self.assert_valid_context(entity);
186        self.read_inner(entity.entity_id)
187            .and_then(|entity| entity.downcast_ref())
188            .unwrap_or_else(|| double_lease_panic("read", type_name::<T>()))
189    }
190
191    #[track_caller]
192    pub(super) fn lease_erased(&mut self, pointer: &AnyEntity, entity_type: &str) -> LeaseInner {
193        self.assert_valid_context(pointer);
194        crate::fast::dependencies::note_update(self, pointer.entity_id);
195        let entity = Some(
196            self.lease_inner(pointer.entity_id)
197                .unwrap_or_else(|| double_lease_panic("update", entity_type)),
198        );
199        LeaseInner { entity }
200    }
201
202    pub(super) fn end_lease_erased(&mut self, entity_id: EntityId, mut lease: LeaseInner) {
203        self.end_lease_inner(entity_id, lease.entity.take().unwrap());
204    }
205
206    fn assert_valid_context(&self, entity: &AnyEntity) {
207        debug_assert!(
208            Weak::ptr_eq(&entity.entity_map, &Arc::downgrade(&self.ref_counts)),
209            "used a entity with the wrong context"
210        );
211    }
212
213    /// Records entities accessed by a reused draw. Entities released since it
214    /// recorded them are skipped, because the window would otherwise subscribe
215    /// to them again after `App` has cleaned up their subscriptions, and
216    /// nothing would clean those up.
217    pub fn extend_accessed(&mut self, entities: impl IntoIterator<Item = EntityId>) {
218        let ref_counts = self.ref_counts.read();
219        self.accessed_entities.get_mut().innermost().extend(
220            entities
221                .into_iter()
222                .filter(|entity_id| ref_counts.counts.contains_key(*entity_id)),
223        );
224    }
225
226    /// Clears the accessed entities and ends any scope left open.
227    pub fn clear_accessed(&mut self) {
228        let accessed_entities = self.accessed_entities.get_mut();
229        accessed_entities.scopes.clear();
230        accessed_entities.frame.clear();
231    }
232
233    pub fn push_access_scope(&mut self) {
234        self.accessed_entities
235            .get_mut()
236            .scopes
237            .push(FxHashSet::default());
238    }
239
240    /// Ends the innermost scope, adds its accessed entities to the scope
241    /// around it, and returns them.
242    pub fn pop_access_scope(&mut self) -> FxHashSet<EntityId> {
243        let accessed_entities = self.accessed_entities.get_mut();
244        let Some(scope) = accessed_entities.scopes.pop() else {
245            debug_assert!(false, "popped an access scope that wasn't pushed");
246            return FxHashSet::default();
247        };
248        accessed_entities.innermost().extend(scope.iter().copied());
249        scope
250    }
251
252    /// Takes every entity accessed during the draw, to be handed back with
253    /// [`Self::restore_accessed`].
254    pub fn take_accessed(&mut self) -> FxHashSet<EntityId> {
255        let accessed_entities = self.accessed_entities.get_mut();
256        debug_assert!(
257            accessed_entities.scopes.is_empty(),
258            "access scope left open"
259        );
260        mem::take(&mut accessed_entities.frame)
261    }
262
263    pub fn restore_accessed(&mut self, entities: FxHashSet<EntityId>) {
264        self.accessed_entities.get_mut().frame = entities;
265    }
266
267    pub fn take_dropped(&mut self) -> Vec<(EntityId, Box<dyn Any>)> {
268        let ref_counts = &mut *self.ref_counts.write();
269        let dropped_entity_ids = ref_counts.dropped_entity_ids.drain(..);
270        let accessed_entities = self.accessed_entities.get_mut();
271
272        dropped_entity_ids
273            .filter_map(|entity_id| {
274                let count = ref_counts.counts.remove(entity_id).unwrap();
275                debug_assert_eq!(
276                    count.load(SeqCst),
277                    0,
278                    "dropped an entity that was referenced"
279                );
280                accessed_entities.frame.remove(&entity_id);
281                for scope in &mut accessed_entities.scopes {
282                    scope.remove(&entity_id);
283                }
284                crate::fast::dependencies::EntityAccessLog::forget(&mut self.access_log, entity_id);
285                // If the EntityId was allocated with `Context::reserve`,
286                // the entity may not have been inserted.
287                Some((entity_id, self.entities.remove(entity_id)?))
288            })
289            .collect()
290    }
291
292    #[inline(never)]
293    fn read_inner(&self, entity_id: EntityId) -> Option<&dyn Any> {
294        self.accessed_entities
295            .borrow_mut()
296            .innermost()
297            .insert(entity_id);
298        crate::fast::dependencies::note_access(self, entity_id);
299        self.entities.get(entity_id).map(Box::as_ref)
300    }
301
302    #[inline(never)]
303    fn lease_inner(&mut self, entity_id: EntityId) -> Option<Box<dyn Any>> {
304        self.accessed_entities
305            .get_mut()
306            .innermost()
307            .insert(entity_id);
308        self.entities.remove(entity_id)
309    }
310
311    #[inline(never)]
312    fn end_lease_inner(&mut self, entity_id: EntityId, entity: Box<dyn Any>) {
313        self.entities.insert(entity_id, entity);
314    }
315}
316
317#[track_caller]
318fn double_lease_panic(operation: &str, entity_type: &str) -> ! {
319    panic!("cannot {operation} {entity_type} while it is already being updated")
320}
321
322pub(crate) struct Lease<T> {
323    pub id: EntityId,
324    inner: LeaseInner,
325    entity_type: PhantomData<T>,
326}
327
328impl<T: 'static> core::ops::Deref for Lease<T> {
329    type Target = T;
330
331    fn deref(&self) -> &Self::Target {
332        self.inner.entity.as_ref().unwrap().downcast_ref().unwrap()
333    }
334}
335
336impl<T: 'static> core::ops::DerefMut for Lease<T> {
337    fn deref_mut(&mut self) -> &mut Self::Target {
338        self.inner.entity.as_mut().unwrap().downcast_mut().unwrap()
339    }
340}
341
342impl Drop for LeaseInner {
343    fn drop(&mut self) {
344        if self.entity.is_some() && !panicking() {
345            panic!("Leases must be ended with EntityMap::end_lease")
346        }
347    }
348}
349
350#[derive(Deref, DerefMut)]
351pub(crate) struct Slot<T>(Entity<T>);
352
353/// A dynamically typed reference to a entity, which can be downcast into a `Entity<T>`.
354pub struct AnyEntity {
355    pub(crate) entity_id: EntityId,
356    pub(crate) entity_type: TypeId,
357    entity_map: Weak<RwLock<EntityRefCounts>>,
358    #[cfg(any(test, gpui_leak_detection))]
359    handle_id: HandleId,
360}
361
362impl AnyEntity {
363    fn new(
364        id: EntityId,
365        entity_type: TypeId,
366        entity_map: Weak<RwLock<EntityRefCounts>>,
367        #[cfg(any(test, gpui_leak_detection))] type_name: &'static str,
368    ) -> Self {
369        Self {
370            entity_id: id,
371            entity_type,
372            #[cfg(any(test, gpui_leak_detection))]
373            handle_id: entity_map
374                .clone()
375                .upgrade()
376                .unwrap()
377                .write()
378                .leak_detector
379                .handle_created(id, Some(type_name)),
380            entity_map,
381        }
382    }
383
384    /// Returns the id associated with this entity.
385    #[inline]
386    pub fn entity_id(&self) -> EntityId {
387        self.entity_id
388    }
389
390    /// Returns the [TypeId] associated with this entity.
391    #[inline]
392    pub fn entity_type(&self) -> TypeId {
393        self.entity_type
394    }
395
396    /// Converts this entity handle into a weak variant, which does not prevent it from being released.
397    pub fn downgrade(&self) -> AnyWeakEntity {
398        AnyWeakEntity {
399            entity_id: self.entity_id,
400            entity_type: self.entity_type,
401            entity_ref_counts: self.entity_map.clone(),
402        }
403    }
404
405    /// Converts this entity handle into a strongly-typed entity handle of the given type.
406    /// If this entity handle is not of the specified type, returns itself as an error variant.
407    pub fn downcast<T: 'static>(self) -> Result<Entity<T>, AnyEntity> {
408        if TypeId::of::<T>() == self.entity_type {
409            Ok(Entity {
410                any_entity: self,
411                entity_type: PhantomData,
412            })
413        } else {
414            Err(self)
415        }
416    }
417}
418
419impl Clone for AnyEntity {
420    fn clone(&self) -> Self {
421        if let Some(entity_map) = self.entity_map.upgrade() {
422            let entity_map = entity_map.read();
423            let count = entity_map
424                .counts
425                .get(self.entity_id)
426                .expect("detected over-release of a entity");
427            let prev_count = count.fetch_add(1, SeqCst);
428            assert_ne!(prev_count, 0, "Detected over-release of a entity.");
429        }
430
431        Self {
432            entity_id: self.entity_id,
433            entity_type: self.entity_type,
434            entity_map: self.entity_map.clone(),
435            #[cfg(any(test, gpui_leak_detection))]
436            handle_id: self
437                .entity_map
438                .upgrade()
439                .unwrap()
440                .write()
441                .leak_detector
442                .handle_created(self.entity_id, None),
443        }
444    }
445}
446
447impl Drop for AnyEntity {
448    fn drop(&mut self) {
449        if let Some(entity_map) = self.entity_map.upgrade() {
450            let entity_map = entity_map.upgradable_read();
451            let count = entity_map
452                .counts
453                .get(self.entity_id)
454                .expect("detected over-release of a handle.");
455            let prev_count = count.fetch_sub(1, SeqCst);
456            assert_ne!(prev_count, 0, "Detected over-release of a entity.");
457            if prev_count == 1 {
458                // We were the last reference to this entity, so we can remove it.
459                let mut entity_map = RwLockUpgradableReadGuard::upgrade(entity_map);
460                entity_map.dropped_entity_ids.push(self.entity_id);
461            }
462        }
463
464        #[cfg(any(test, gpui_leak_detection))]
465        if let Some(entity_map) = self.entity_map.upgrade() {
466            entity_map
467                .write()
468                .leak_detector
469                .handle_released(self.entity_id, self.handle_id)
470        }
471    }
472}
473
474impl<T> From<Entity<T>> for AnyEntity {
475    #[inline]
476    fn from(entity: Entity<T>) -> Self {
477        entity.any_entity
478    }
479}
480
481impl Hash for AnyEntity {
482    #[inline]
483    fn hash<H: Hasher>(&self, state: &mut H) {
484        self.entity_id.hash(state);
485    }
486}
487
488impl PartialEq for AnyEntity {
489    #[inline]
490    fn eq(&self, other: &Self) -> bool {
491        self.entity_id == other.entity_id
492    }
493}
494
495impl Eq for AnyEntity {}
496
497impl Ord for AnyEntity {
498    #[inline]
499    fn cmp(&self, other: &Self) -> Ordering {
500        self.entity_id.cmp(&other.entity_id)
501    }
502}
503
504impl PartialOrd for AnyEntity {
505    #[inline]
506    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
507        Some(self.cmp(other))
508    }
509}
510
511impl std::fmt::Debug for AnyEntity {
512    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
513        f.debug_struct("AnyEntity")
514            .field("entity_id", &self.entity_id.as_u64())
515            .finish()
516    }
517}
518
519/// A strong, well-typed reference to a struct which is managed
520/// by GPUI
521#[derive(Deref, DerefMut)]
522pub struct Entity<T> {
523    #[deref]
524    #[deref_mut]
525    pub(crate) any_entity: AnyEntity,
526    pub(crate) entity_type: PhantomData<fn(T) -> T>,
527}
528
529impl<T> Sealed for Entity<T> {}
530
531impl<T: 'static> Entity<T> {
532    #[inline]
533    fn new(id: EntityId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self
534    where
535        T: 'static,
536    {
537        Self {
538            any_entity: AnyEntity::new(
539                id,
540                TypeId::of::<T>(),
541                entity_map,
542                #[cfg(any(test, gpui_leak_detection))]
543                std::any::type_name::<T>(),
544            ),
545            entity_type: PhantomData,
546        }
547    }
548
549    /// Get the entity ID associated with this entity
550    #[inline]
551    pub fn entity_id(&self) -> EntityId {
552        self.any_entity.entity_id
553    }
554
555    /// Downgrade this entity pointer to a non-retaining weak pointer
556    #[inline]
557    pub fn downgrade(&self) -> WeakEntity<T> {
558        WeakEntity {
559            any_entity: self.any_entity.downgrade(),
560            entity_type: self.entity_type,
561        }
562    }
563
564    /// Convert this into a dynamically typed entity.
565    #[inline]
566    pub fn into_any(self) -> AnyEntity {
567        self.any_entity
568    }
569
570    /// Grab a reference to this entity from the context.
571    #[inline]
572    pub fn read<'a>(&self, cx: &'a App) -> &'a T {
573        cx.entities.read(self)
574    }
575
576    /// Read the entity referenced by this handle with the given function.
577    #[inline]
578    pub fn read_with<R, C: AppContext>(&self, cx: &C, f: impl FnOnce(&T, &App) -> R) -> R {
579        cx.read_entity(self, f)
580    }
581
582    /// Updates the entity referenced by this handle with the given function.
583    #[inline]
584    pub fn update<R, C: AppContext>(
585        &self,
586        cx: &mut C,
587        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
588    ) -> R {
589        cx.update_entity(self, update)
590    }
591
592    /// Updates the entity referenced by this handle with the given function.
593    #[inline]
594    pub fn as_mut<'a, C: AppContext>(&self, cx: &'a mut C) -> GpuiBorrow<'a, T> {
595        cx.as_mut(self)
596    }
597
598    /// Updates the entity referenced by this handle with the given function.
599    pub fn write<C: AppContext>(&self, cx: &mut C, value: T) {
600        self.update(cx, |entity, cx| {
601            *entity = value;
602            cx.notify();
603        })
604    }
605
606    /// Updates the entity referenced by this handle with the given function if
607    /// the referenced entity still exists, within a visual context that has a window.
608    /// Returns an error if the window has been closed.
609    #[inline]
610    pub fn update_in<R, C: VisualContext>(
611        &self,
612        cx: &mut C,
613        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
614    ) -> C::Result<R> {
615        cx.update_window_entity(self, update)
616    }
617}
618
619impl<T> Clone for Entity<T> {
620    #[inline]
621    fn clone(&self) -> Self {
622        Self {
623            any_entity: self.any_entity.clone(),
624            entity_type: self.entity_type,
625        }
626    }
627}
628
629impl<T> std::fmt::Debug for Entity<T> {
630    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
631        f.debug_struct("Entity")
632            .field("entity_id", &self.any_entity.entity_id)
633            .field("entity_type", &type_name::<T>())
634            .finish()
635    }
636}
637
638impl<T> Hash for Entity<T> {
639    #[inline]
640    fn hash<H: Hasher>(&self, state: &mut H) {
641        self.any_entity.hash(state);
642    }
643}
644
645impl<T> PartialEq for Entity<T> {
646    #[inline]
647    fn eq(&self, other: &Self) -> bool {
648        self.any_entity == other.any_entity
649    }
650}
651
652impl<T> Eq for Entity<T> {}
653
654impl<T> PartialEq<WeakEntity<T>> for Entity<T> {
655    #[inline]
656    fn eq(&self, other: &WeakEntity<T>) -> bool {
657        self.any_entity.entity_id() == other.entity_id()
658    }
659}
660
661impl<T: 'static> Ord for Entity<T> {
662    #[inline]
663    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
664        self.entity_id().cmp(&other.entity_id())
665    }
666}
667
668impl<T: 'static> PartialOrd for Entity<T> {
669    #[inline]
670    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
671        Some(self.cmp(other))
672    }
673}
674
675/// A type erased, weak reference to a entity.
676#[derive(Clone)]
677pub struct AnyWeakEntity {
678    pub(crate) entity_id: EntityId,
679    entity_type: TypeId,
680    entity_ref_counts: Weak<RwLock<EntityRefCounts>>,
681}
682
683impl AnyWeakEntity {
684    /// Get the entity ID associated with this weak reference.
685    #[inline]
686    pub fn entity_id(&self) -> EntityId {
687        self.entity_id
688    }
689
690    /// Check if this weak handle can be upgraded, or if the entity has already been dropped
691    pub fn is_upgradable(&self) -> bool {
692        let ref_count = self
693            .entity_ref_counts
694            .upgrade()
695            .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
696            .unwrap_or(0);
697        ref_count > 0
698    }
699
700    /// Upgrade this weak entity reference to a strong reference.
701    pub fn upgrade(&self) -> Option<AnyEntity> {
702        let ref_counts = &self.entity_ref_counts.upgrade()?;
703        let ref_counts = ref_counts.read();
704        let ref_count = ref_counts.counts.get(self.entity_id)?;
705
706        if atomic_incr_if_not_zero(ref_count) == 0 {
707            // entity_id is in dropped_entity_ids
708            return None;
709        }
710        drop(ref_counts);
711
712        Some(AnyEntity {
713            entity_id: self.entity_id,
714            entity_type: self.entity_type,
715            entity_map: self.entity_ref_counts.clone(),
716            #[cfg(any(test, gpui_leak_detection))]
717            handle_id: self
718                .entity_ref_counts
719                .upgrade()
720                .unwrap()
721                .write()
722                .leak_detector
723                .handle_created(self.entity_id, None),
724        })
725    }
726
727    /// Asserts that the entity referenced by this weak handle has been fully released.
728    ///
729    /// # Example
730    ///
731    /// ```ignore
732    /// let entity = cx.new(|_| MyEntity::new());
733    /// let weak = entity.downgrade();
734    /// drop(entity);
735    ///
736    /// // Verify the entity was released
737    /// weak.assert_released();
738    /// ```
739    ///
740    /// # Debugging Leaks
741    ///
742    /// With leak detection enabled (build with `GPUI_LEAK_DETECTION=1`), a failure
743    /// lists each leaked handle. Also set the `LEAK_BACKTRACE` environment variable
744    /// to see where they were allocated:
745    ///
746    /// ```bash
747    /// GPUI_LEAK_DETECTION=1 LEAK_BACKTRACE=1 cargo test my_test
748    /// ```
749    ///
750    /// # Panics
751    ///
752    /// - Panics if any strong handles to the entity are still alive.
753    /// - Panics if the entity was recently dropped but cleanup hasn't completed yet
754    ///   (resources are retained until the end of the effect cycle).
755    #[cfg(any(test, feature = "test-support", gpui_leak_detection))]
756    pub fn assert_released(&self) {
757        #[cfg(any(test, gpui_leak_detection))]
758        self.entity_ref_counts
759            .upgrade()
760            .unwrap()
761            .write()
762            .leak_detector
763            .assert_released(self.entity_id);
764
765        if self
766            .entity_ref_counts
767            .upgrade()
768            .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
769            .is_some()
770        {
771            panic!(
772                "entity is still alive, or was recently dropped and its resources are retained \
773                 until the end of the effect cycle. Build with GPUI_LEAK_DETECTION=1 to list \
774                 its live handles."
775            )
776        }
777    }
778
779    /// Creates a weak entity that can never be upgraded.
780    pub fn new_invalid() -> Self {
781        /// To hold the invariant that all ids are unique, and considering that slotmap
782        /// increases their IDs from `0`, we can decrease ours from `u64::MAX` so these
783        /// two will never conflict (u64 is way too large).
784        static UNIQUE_NON_CONFLICTING_ID_GENERATOR: AtomicU64 = AtomicU64::new(u64::MAX);
785        let entity_id = UNIQUE_NON_CONFLICTING_ID_GENERATOR.fetch_sub(1, SeqCst);
786
787        Self {
788            // Safety:
789            //   Docs say this is safe but can be unspecified if slotmap changes the representation
790            //   after `1.0.7`, that said, providing a valid entity_id here is not necessary as long
791            //   as we guarantee that `entity_id` is never used if `entity_ref_counts` equals
792            //   to `Weak::new()` (that is, it's unable to upgrade), that is the invariant that
793            //   actually needs to be hold true.
794            //
795            //   And there is no sane reason to read an entity slot if `entity_ref_counts` can't be
796            //   read in the first place, so we're good!
797            entity_id: entity_id.into(),
798            entity_type: TypeId::of::<()>(),
799            entity_ref_counts: Weak::new(),
800        }
801    }
802}
803
804impl std::fmt::Debug for AnyWeakEntity {
805    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
806        f.debug_struct(type_name::<Self>())
807            .field("entity_id", &self.entity_id)
808            .field("entity_type", &self.entity_type)
809            .finish()
810    }
811}
812
813impl<T> From<WeakEntity<T>> for AnyWeakEntity {
814    #[inline]
815    fn from(entity: WeakEntity<T>) -> Self {
816        entity.any_entity
817    }
818}
819
820impl Hash for AnyWeakEntity {
821    #[inline]
822    fn hash<H: Hasher>(&self, state: &mut H) {
823        self.entity_id.hash(state);
824    }
825}
826
827impl PartialEq for AnyWeakEntity {
828    #[inline]
829    fn eq(&self, other: &Self) -> bool {
830        self.entity_id == other.entity_id
831    }
832}
833
834impl Eq for AnyWeakEntity {}
835
836impl Ord for AnyWeakEntity {
837    #[inline]
838    fn cmp(&self, other: &Self) -> Ordering {
839        self.entity_id.cmp(&other.entity_id)
840    }
841}
842
843impl PartialOrd for AnyWeakEntity {
844    #[inline]
845    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
846        Some(self.cmp(other))
847    }
848}
849
850/// A weak reference to a entity of the given type.
851#[derive(Deref, DerefMut)]
852pub struct WeakEntity<T> {
853    #[deref]
854    #[deref_mut]
855    any_entity: AnyWeakEntity,
856    entity_type: PhantomData<fn(T) -> T>,
857}
858
859impl<T> std::fmt::Debug for WeakEntity<T> {
860    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
861        f.debug_struct(type_name::<Self>())
862            .field("entity_id", &self.any_entity.entity_id)
863            .field("entity_type", &type_name::<T>())
864            .finish()
865    }
866}
867
868impl<T> Clone for WeakEntity<T> {
869    fn clone(&self) -> Self {
870        Self {
871            any_entity: self.any_entity.clone(),
872            entity_type: self.entity_type,
873        }
874    }
875}
876
877impl<T: 'static> WeakEntity<T> {
878    /// Upgrade this weak entity reference into a strong entity reference
879    pub fn upgrade(&self) -> Option<Entity<T>> {
880        Some(Entity {
881            any_entity: self.any_entity.upgrade()?,
882            entity_type: self.entity_type,
883        })
884    }
885
886    /// Updates the entity referenced by this handle with the given function if
887    /// the referenced entity still exists. Returns an error if the entity has
888    /// been released.
889    #[inline(always)]
890    pub fn update<C, R>(
891        &self,
892        cx: &mut C,
893        update: impl FnOnce(&mut T, &mut Context<T>) -> R,
894    ) -> Result<R>
895    where
896        C: AppContext,
897    {
898        let entity = self.upgrade().context("entity released")?;
899        Ok(cx.update_entity(&entity, update))
900    }
901
902    /// Updates the entity referenced by this handle with the given function if
903    /// the referenced entity still exists, within a visual context that has a window.
904    /// Returns an error if the entity has been released.
905    #[inline(always)]
906    pub fn update_in<C, R>(
907        &self,
908        cx: &mut C,
909        update: impl FnOnce(&mut T, &mut Window, &mut Context<T>) -> R,
910    ) -> Result<R>
911    where
912        C: AppContext,
913    {
914        let entity = self.upgrade().context("entity released")?;
915        cx.with_window(entity.entity_id(), |window, app| {
916            entity.update(app, |entity, cx| update(entity, window, cx))
917        })
918        .context("entity has no current window")
919    }
920
921    /// Reads the entity referenced by this handle with the given function if
922    /// the referenced entity still exists. Returns an error if the entity has
923    /// been released.
924    #[inline(always)]
925    pub fn read_with<C, R>(&self, cx: &C, read: impl FnOnce(&T, &App) -> R) -> Result<R>
926    where
927        C: AppContext,
928    {
929        let entity = self.upgrade().context("entity released")?;
930        Ok(cx.read_entity(&entity, read))
931    }
932
933    /// Create a new weak entity that can never be upgraded.
934    #[inline]
935    pub fn new_invalid() -> Self {
936        Self {
937            any_entity: AnyWeakEntity::new_invalid(),
938            entity_type: PhantomData,
939        }
940    }
941}
942
943impl<T> Hash for WeakEntity<T> {
944    #[inline]
945    fn hash<H: Hasher>(&self, state: &mut H) {
946        self.any_entity.hash(state);
947    }
948}
949
950impl<T> PartialEq for WeakEntity<T> {
951    #[inline]
952    fn eq(&self, other: &Self) -> bool {
953        self.any_entity == other.any_entity
954    }
955}
956
957impl<T> Eq for WeakEntity<T> {}
958
959impl<T> PartialEq<Entity<T>> for WeakEntity<T> {
960    #[inline]
961    fn eq(&self, other: &Entity<T>) -> bool {
962        self.entity_id() == other.any_entity.entity_id()
963    }
964}
965
966impl<T: 'static> Ord for WeakEntity<T> {
967    #[inline]
968    fn cmp(&self, other: &Self) -> Ordering {
969        self.entity_id().cmp(&other.entity_id())
970    }
971}
972
973impl<T: 'static> PartialOrd for WeakEntity<T> {
974    #[inline]
975    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
976        Some(self.cmp(other))
977    }
978}
979
980/// Controls whether backtraces are captured when entity handles are created.
981///
982/// Set the `LEAK_BACKTRACE` environment variable to any non-empty value to enable
983/// backtrace capture. This helps identify where leaked handles were allocated.
984#[cfg(any(test, gpui_leak_detection))]
985static LEAK_BACKTRACE: std::sync::LazyLock<bool> =
986    std::sync::LazyLock::new(|| std::env::var("LEAK_BACKTRACE").is_ok_and(|b| !b.is_empty()));
987
988/// Unique identifier for a specific entity handle instance.
989///
990/// This is distinct from `EntityId` - while multiple handles can point to the same
991/// entity (same `EntityId`), each handle has its own unique `HandleId`.
992#[cfg(any(test, gpui_leak_detection))]
993#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
994pub(crate) struct HandleId {
995    id: u64,
996}
997
998/// Tracks entity handle allocations to detect leaks.
999///
1000/// The leak detector is enabled in tests and when the `leak-detection` feature is active.
1001/// It tracks every `Entity<T>` and `AnyEntity` handle that is created and released,
1002/// allowing you to verify that all handles to an entity have been properly dropped.
1003///
1004/// # How do leaks happen?
1005///
1006/// Entities are reference-counted structures that can own other entities
1007/// allowing to form cycles. If such a strong-reference counted cycle is
1008/// created, all participating strong entities in this cycle will effectively
1009/// leak as they cannot be released anymore.
1010///
1011/// Cycles can also happen if an entity owns a task or subscription that it
1012/// itself owns a strong reference to the entity again.
1013///
1014/// # Usage
1015///
1016/// You can use `WeakEntity::assert_released` or `AnyWeakEntity::assert_released`
1017/// to verify that an entity has been fully released:
1018///
1019/// ```ignore
1020/// let entity = cx.new(|_| MyEntity::new());
1021/// let weak = entity.downgrade();
1022/// drop(entity);
1023///
1024/// // This will panic if any handles to the entity are still alive
1025/// weak.assert_released();
1026/// ```
1027///
1028/// # Debugging Leaks
1029///
1030/// When a leak is detected, the detector will panic with information about the leaked
1031/// handles. To see where the leaked handles were allocated, set the `LEAK_BACKTRACE`
1032/// environment variable:
1033///
1034/// ```bash
1035/// LEAK_BACKTRACE=1 cargo test my_test
1036/// ```
1037///
1038/// This will capture and display backtraces for each leaked handle, helping you
1039/// identify where leaked handles were created.
1040///
1041/// # How It Works
1042///
1043/// - When an entity handle is created (via `Entity::new`, `Entity::clone`, or
1044///   `WeakEntity::upgrade`), `handle_created` is called to register the handle.
1045/// - When a handle is dropped, `handle_released` removes it from tracking.
1046/// - `assert_released` verifies that no handles remain for a given entity.
1047#[cfg(any(test, gpui_leak_detection))]
1048pub(crate) struct LeakDetector {
1049    next_handle_id: u64,
1050    entity_handles: HashMap<EntityId, EntityLeakData>,
1051}
1052
1053/// A snapshot of the set of alive entities at a point in time.
1054///
1055/// Created by [`LeakDetector::snapshot`]. Can later be passed to
1056/// [`LeakDetector::assert_no_new_leaks`] to verify that no new entity
1057/// handles remain between the snapshot and the current state.
1058#[cfg(any(test, feature = "test-support", gpui_leak_detection))]
1059#[derive(Default)]
1060pub struct LeakDetectorSnapshot {
1061    #[cfg(any(test, gpui_leak_detection))]
1062    entity_ids: collections::HashSet<EntityId>,
1063}
1064
1065#[cfg(any(test, gpui_leak_detection))]
1066struct EntityLeakData {
1067    handles: HashMap<HandleId, Option<backtrace::Backtrace>>,
1068    type_name: &'static str,
1069}
1070
1071#[cfg(any(test, gpui_leak_detection))]
1072impl LeakDetector {
1073    /// Records that a new handle has been created for the given entity.
1074    ///
1075    /// Returns a unique `HandleId` that must be passed to `handle_released` when
1076    /// the handle is dropped. If `LEAK_BACKTRACE` is set, captures a backtrace
1077    /// at the allocation site.
1078    #[track_caller]
1079    pub fn handle_created(
1080        &mut self,
1081        entity_id: EntityId,
1082        type_name: Option<&'static str>,
1083    ) -> HandleId {
1084        let id = gpui_util::post_inc(&mut self.next_handle_id);
1085        let handle_id = HandleId { id };
1086        let handles = self
1087            .entity_handles
1088            .entry(entity_id)
1089            .or_insert_with(|| EntityLeakData {
1090                handles: HashMap::default(),
1091                type_name: type_name.unwrap_or("<unknown>"),
1092            });
1093        handles.handles.insert(
1094            handle_id,
1095            LEAK_BACKTRACE.then(backtrace::Backtrace::new_unresolved),
1096        );
1097        handle_id
1098    }
1099
1100    /// Records that a handle has been released (dropped).
1101    ///
1102    /// This removes the handle from tracking. The `handle_id` should be the same
1103    /// one returned by `handle_created` when the handle was allocated.
1104    pub fn handle_released(&mut self, entity_id: EntityId, handle_id: HandleId) {
1105        if let std::collections::hash_map::Entry::Occupied(mut data) =
1106            self.entity_handles.entry(entity_id)
1107        {
1108            data.get_mut().handles.remove(&handle_id);
1109            if data.get().handles.is_empty() {
1110                data.remove();
1111            }
1112        }
1113    }
1114
1115    /// Asserts that all handles to the given entity have been released.
1116    ///
1117    /// # Panics
1118    ///
1119    /// Panics if any handles to the entity are still alive. The panic message
1120    /// includes backtraces for each leaked handle if `LEAK_BACKTRACE` is set,
1121    /// otherwise it suggests setting the environment variable to get more info.
1122    pub fn assert_released(&mut self, entity_id: EntityId) {
1123        use std::fmt::Write as _;
1124
1125        if let Some(data) = self.entity_handles.remove(&entity_id) {
1126            let mut out = String::new();
1127            for (_, backtrace) in data.handles {
1128                if let Some(mut backtrace) = backtrace {
1129                    backtrace.resolve();
1130                    let backtrace = BacktraceFormatter(backtrace);
1131                    writeln!(out, "Leaked handle:\n{:?}", backtrace).unwrap();
1132                } else {
1133                    writeln!(
1134                        out,
1135                        "Leaked handle: (export LEAK_BACKTRACE to find allocation site)"
1136                    )
1137                    .unwrap();
1138                }
1139            }
1140            panic!("Handles for {} leaked:\n{out}", data.type_name);
1141        }
1142    }
1143
1144    /// Captures a snapshot of all entity IDs that currently have alive handles.
1145    ///
1146    /// The returned [`LeakDetectorSnapshot`] can later be passed to
1147    /// [`assert_no_new_leaks`](Self::assert_no_new_leaks) to verify that no
1148    /// entities created after the snapshot are still alive.
1149    pub fn snapshot(&self) -> LeakDetectorSnapshot {
1150        LeakDetectorSnapshot {
1151            entity_ids: self.entity_handles.keys().copied().collect(),
1152        }
1153    }
1154
1155    /// Asserts that no entities created after `snapshot` still have alive handles.
1156    ///
1157    /// Entities that were already tracked at the time of the snapshot are ignored,
1158    /// even if they still have handles. Only *new* entities (those whose
1159    /// `EntityId` was not present in the snapshot) are considered leaks.
1160    ///
1161    /// # Panics
1162    ///
1163    /// Panics if any new entity handles exist. The panic message lists every
1164    /// leaked entity with its type name, and includes allocation-site backtraces
1165    /// when `LEAK_BACKTRACE` is set.
1166    pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
1167        use std::fmt::Write as _;
1168
1169        let mut out = String::new();
1170        for (entity_id, data) in &self.entity_handles {
1171            if snapshot.entity_ids.contains(entity_id) {
1172                continue;
1173            }
1174            for (_, backtrace) in &data.handles {
1175                if let Some(backtrace) = backtrace {
1176                    let mut backtrace = backtrace.clone();
1177                    backtrace.resolve();
1178                    let backtrace = BacktraceFormatter(backtrace);
1179                    writeln!(
1180                        out,
1181                        "Leaked handle for entity {} ({entity_id:?}):\n{:?}",
1182                        data.type_name, backtrace
1183                    )
1184                    .unwrap();
1185                } else {
1186                    writeln!(
1187                        out,
1188                        "Leaked handle for entity {} ({entity_id:?}): (export LEAK_BACKTRACE to find allocation site)",
1189                        data.type_name
1190                    )
1191                    .unwrap();
1192                }
1193            }
1194        }
1195
1196        if !out.is_empty() {
1197            panic!("New entity leaks detected since snapshot:\n{out}");
1198        }
1199    }
1200}
1201
1202#[cfg(any(test, gpui_leak_detection))]
1203impl Drop for LeakDetector {
1204    fn drop(&mut self) {
1205        use std::fmt::Write;
1206
1207        if self.entity_handles.is_empty() || std::thread::panicking() {
1208            return;
1209        }
1210
1211        let mut out = String::new();
1212        for (entity_id, data) in self.entity_handles.drain() {
1213            for (_handle, backtrace) in data.handles {
1214                if let Some(mut backtrace) = backtrace {
1215                    backtrace.resolve();
1216                    let backtrace = BacktraceFormatter(backtrace);
1217                    writeln!(
1218                        out,
1219                        "Leaked handle for entity {} ({entity_id:?}):\n{:?}",
1220                        data.type_name, backtrace
1221                    )
1222                    .unwrap();
1223                } else {
1224                    writeln!(
1225                        out,
1226                        "Leaked handle for entity {} ({entity_id:?}): (export LEAK_BACKTRACE to find allocation site)",
1227                        data.type_name
1228                    )
1229                    .unwrap();
1230                }
1231            }
1232        }
1233        panic!("Exited with leaked handles:\n{out}");
1234    }
1235}
1236
1237#[cfg(any(test, gpui_leak_detection))]
1238struct BacktraceFormatter(backtrace::Backtrace);
1239
1240#[cfg(any(test, gpui_leak_detection))]
1241impl fmt::Debug for BacktraceFormatter {
1242    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1243        use backtrace::{BacktraceFmt, BytesOrWideString, PrintFmt};
1244
1245        let style = if fmt.alternate() {
1246            PrintFmt::Full
1247        } else {
1248            PrintFmt::Short
1249        };
1250
1251        // When printing paths we try to strip the cwd if it exists, otherwise
1252        // we just print the path as-is. Note that we also only do this for the
1253        // short format, because if it's full we presumably want to print
1254        // everything.
1255        let cwd = std::env::current_dir();
1256        let mut print_path = move |fmt: &mut fmt::Formatter<'_>, path: BytesOrWideString<'_>| {
1257            let path = path.into_path_buf();
1258            if style != PrintFmt::Full {
1259                if let Ok(cwd) = &cwd {
1260                    if let Ok(suffix) = path.strip_prefix(cwd) {
1261                        return fmt::Display::fmt(&suffix.display(), fmt);
1262                    }
1263                }
1264            }
1265            fmt::Display::fmt(&path.display(), fmt)
1266        };
1267
1268        let mut f = BacktraceFmt::new(fmt, style, &mut print_path);
1269        f.add_context()?;
1270        let mut strip = true;
1271        for frame in self.0.frames() {
1272            if let [symbol, ..] = frame.symbols()
1273                && let Some(name) = symbol.name()
1274                && let Some(filename) = name.as_str()
1275            {
1276                match filename {
1277                    "test::run_test_in_process"
1278                    | "scheduler::executor::spawn_local_with_source_location::impl$1::poll<core::pin::Pin<alloc::boxed::Box<dyn$<core::future::future::Future<assoc$<Output,enum2$<core::result::Result<workspace::OpenResult,anyhow::Error> > > > >,alloc::alloc::Global> > >" => {
1279                        strip = true
1280                    }
1281                    "gpui::app::entity_map::LeakDetector::handle_created" => {
1282                        strip = false;
1283                        continue;
1284                    }
1285                    "zed::main" => {
1286                        strip = true;
1287                        f.frame().backtrace_frame(frame)?;
1288                    }
1289                    _ => {}
1290                }
1291            }
1292            if strip {
1293                continue;
1294            }
1295            f.frame().backtrace_frame(frame)?;
1296        }
1297        f.finish()?;
1298        Ok(())
1299    }
1300}
1301
1302#[cfg(test)]
1303mod test {
1304    use crate::EntityMap;
1305    use collections::FxHashSet;
1306
1307    struct TestEntity {
1308        pub i: i32,
1309    }
1310
1311    #[test]
1312    fn test_accessed_entity_scopes() {
1313        let mut entity_map = EntityMap::new();
1314        let slot = entity_map.reserve::<TestEntity>();
1315        let first = entity_map.insert(slot, TestEntity { i: 1 });
1316        let slot = entity_map.reserve::<TestEntity>();
1317        let second = entity_map.insert(slot, TestEntity { i: 2 });
1318        entity_map.clear_accessed();
1319
1320        entity_map.read(&first);
1321        entity_map.push_access_scope();
1322        entity_map.read(&first);
1323        entity_map.push_access_scope();
1324        entity_map.read(&second);
1325        let inner = entity_map.pop_access_scope();
1326        let outer = entity_map.pop_access_scope();
1327
1328        assert_eq!(inner, FxHashSet::from_iter([second.entity_id()]));
1329        let both = FxHashSet::from_iter([first.entity_id(), second.entity_id()]);
1330        assert_eq!(outer, both);
1331        assert_eq!(entity_map.take_accessed(), both);
1332
1333        drop(second);
1334        entity_map.take_dropped();
1335        entity_map.extend_accessed(both);
1336        assert_eq!(
1337            entity_map.take_accessed(),
1338            FxHashSet::from_iter([first.entity_id()]),
1339            "a released entity shouldn't be recorded again"
1340        );
1341    }
1342
1343    #[test]
1344    fn test_entity_map_slot_assignment_before_cleanup() {
1345        // Tests that slots are not re-used before take_dropped.
1346        let mut entity_map = EntityMap::new();
1347
1348        let slot = entity_map.reserve::<TestEntity>();
1349        entity_map.insert(slot, TestEntity { i: 1 });
1350
1351        let slot = entity_map.reserve::<TestEntity>();
1352        entity_map.insert(slot, TestEntity { i: 2 });
1353
1354        let dropped = entity_map.take_dropped();
1355        assert_eq!(dropped.len(), 2);
1356
1357        assert_eq!(
1358            dropped
1359                .into_iter()
1360                .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
1361                .collect::<Vec<i32>>(),
1362            vec![1, 2],
1363        );
1364    }
1365
1366    #[test]
1367    fn test_entity_map_weak_upgrade_before_cleanup() {
1368        // Tests that weak handles are not upgraded before take_dropped
1369        let mut entity_map = EntityMap::new();
1370
1371        let slot = entity_map.reserve::<TestEntity>();
1372        let handle = entity_map.insert(slot, TestEntity { i: 1 });
1373        let weak = handle.downgrade();
1374        drop(handle);
1375
1376        let strong = weak.upgrade();
1377        assert_eq!(strong, None);
1378
1379        let dropped = entity_map.take_dropped();
1380        assert_eq!(dropped.len(), 1);
1381
1382        assert_eq!(
1383            dropped
1384                .into_iter()
1385                .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
1386                .collect::<Vec<i32>>(),
1387            vec![1],
1388        );
1389    }
1390
1391    #[test]
1392    fn test_leak_detector_snapshot_no_leaks() {
1393        let mut entity_map = EntityMap::new();
1394
1395        let slot = entity_map.reserve::<TestEntity>();
1396        let pre_existing = entity_map.insert(slot, TestEntity { i: 1 });
1397
1398        let snapshot = entity_map.leak_detector_snapshot();
1399
1400        let slot = entity_map.reserve::<TestEntity>();
1401        let temporary = entity_map.insert(slot, TestEntity { i: 2 });
1402        drop(temporary);
1403
1404        entity_map.assert_no_new_leaks(&snapshot);
1405
1406        drop(pre_existing);
1407    }
1408
1409    #[test]
1410    #[should_panic(expected = "New entity leaks detected since snapshot")]
1411    fn test_leak_detector_snapshot_detects_new_leak() {
1412        let mut entity_map = EntityMap::new();
1413
1414        let slot = entity_map.reserve::<TestEntity>();
1415        let pre_existing = entity_map.insert(slot, TestEntity { i: 1 });
1416
1417        let snapshot = entity_map.leak_detector_snapshot();
1418
1419        let slot = entity_map.reserve::<TestEntity>();
1420        let leaked = entity_map.insert(slot, TestEntity { i: 2 });
1421
1422        // `leaked` is still alive, so this should panic.
1423        entity_map.assert_no_new_leaks(&snapshot);
1424
1425        drop(pre_existing);
1426        drop(leaked);
1427    }
1428}