1use crate::{seal::Sealed, App, AppContext, VisualContext, Window};
2use anyhow::{anyhow, Result};
3use collections::FxHashSet;
4use derive_more::{Deref, DerefMut};
5use parking_lot::{RwLock, RwLockUpgradableReadGuard};
6use slotmap::{KeyData, SecondaryMap, SlotMap};
7use std::{
8 any::{type_name, Any, TypeId},
9 cell::RefCell,
10 fmt::{self, Display},
11 hash::{Hash, Hasher},
12 marker::PhantomData,
13 mem,
14 num::NonZeroU64,
15 sync::{
16 atomic::{AtomicUsize, Ordering::SeqCst},
17 Arc, Weak,
18 },
19 thread::panicking,
20};
21
22#[cfg(any(test, feature = "leak-detection"))]
23use collections::HashMap;
24
25use super::Context;
26
27slotmap::new_key_type! {
28 /// A unique identifier for a entity across the application.
29 pub struct EntityId;
30}
31
32impl From<u64> for EntityId {
33 fn from(value: u64) -> Self {
34 Self(KeyData::from_ffi(value))
35 }
36}
37
38impl EntityId {
39 /// Converts this entity id to a [NonZeroU64]
40 pub fn as_non_zero_u64(self) -> NonZeroU64 {
41 NonZeroU64::new(self.0.as_ffi()).unwrap()
42 }
43
44 /// Converts this entity id to a [u64]
45 pub fn as_u64(self) -> u64 {
46 self.0.as_ffi()
47 }
48}
49
50impl Display for EntityId {
51 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 write!(f, "{}", self.as_u64())
53 }
54}
55
56pub(crate) struct EntityMap {
57 entities: SecondaryMap<EntityId, Box<dyn Any>>,
58 pub accessed_entities: RefCell<FxHashSet<EntityId>>,
59 ref_counts: Arc<RwLock<EntityRefCounts>>,
60}
61
62struct EntityRefCounts {
63 counts: SlotMap<EntityId, AtomicUsize>,
64 dropped_entity_ids: Vec<EntityId>,
65 #[cfg(any(test, feature = "leak-detection"))]
66 leak_detector: LeakDetector,
67}
68
69impl EntityMap {
70 pub fn new() -> Self {
71 Self {
72 entities: SecondaryMap::new(),
73 accessed_entities: RefCell::new(FxHashSet::default()),
74 ref_counts: Arc::new(RwLock::new(EntityRefCounts {
75 counts: SlotMap::with_key(),
76 dropped_entity_ids: Vec::new(),
77 #[cfg(any(test, feature = "leak-detection"))]
78 leak_detector: LeakDetector {
79 next_handle_id: 0,
80 entity_handles: HashMap::default(),
81 },
82 })),
83 }
84 }
85
86 /// Reserve a slot for an entity, which you can subsequently use with `insert`.
87 pub fn reserve<T: 'static>(&self) -> Slot<T> {
88 let id = self.ref_counts.write().counts.insert(1.into());
89 Slot(Entity::new(id, Arc::downgrade(&self.ref_counts)))
90 }
91
92 /// Insert an entity into a slot obtained by calling `reserve`.
93 pub fn insert<T>(&mut self, slot: Slot<T>, entity: T) -> Entity<T>
94 where
95 T: 'static,
96 {
97 let mut accessed_entities = self.accessed_entities.borrow_mut();
98 accessed_entities.insert(slot.entity_id);
99
100 let handle = slot.0;
101 self.entities.insert(handle.entity_id, Box::new(entity));
102 handle
103 }
104
105 /// Move an entity to the stack.
106 #[track_caller]
107 pub fn lease<'a, T>(&mut self, pointer: &'a Entity<T>) -> Lease<'a, T> {
108 self.assert_valid_context(pointer);
109 let mut accessed_entities = self.accessed_entities.borrow_mut();
110 accessed_entities.insert(pointer.entity_id);
111
112 let entity = Some(
113 self.entities
114 .remove(pointer.entity_id)
115 .unwrap_or_else(|| double_lease_panic::<T>("update")),
116 );
117 Lease {
118 entity,
119 pointer,
120 entity_type: PhantomData,
121 }
122 }
123
124 /// Returns an entity after moving it to the stack.
125 pub fn end_lease<T>(&mut self, mut lease: Lease<T>) {
126 self.entities
127 .insert(lease.pointer.entity_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<'a, T> {
190 entity: Option<Box<dyn Any>>,
191 pub pointer: &'a Entity<T>,
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 entity_map: entity_map.clone(),
235 #[cfg(any(test, feature = "leak-detection"))]
236 handle_id: entity_map
237 .upgrade()
238 .unwrap()
239 .write()
240 .leak_detector
241 .handle_created(id),
242 }
243 }
244
245 /// Returns the id associated with this entity.
246 pub fn entity_id(&self) -> EntityId {
247 self.entity_id
248 }
249
250 /// Returns the [TypeId] associated with this entity.
251 pub fn entity_type(&self) -> TypeId {
252 self.entity_type
253 }
254
255 /// Converts this entity handle into a weak variant, which does not prevent it from being released.
256 pub fn downgrade(&self) -> AnyWeakEntity {
257 AnyWeakEntity {
258 entity_id: self.entity_id,
259 entity_type: self.entity_type,
260 entity_ref_counts: self.entity_map.clone(),
261 }
262 }
263
264 /// Converts this entity handle into a strongly-typed entity handle of the given type.
265 /// If this entity handle is not of the specified type, returns itself as an error variant.
266 pub fn downcast<T: 'static>(self) -> Result<Entity<T>, AnyEntity> {
267 if TypeId::of::<T>() == self.entity_type {
268 Ok(Entity {
269 any_entity: self,
270 entity_type: PhantomData,
271 })
272 } else {
273 Err(self)
274 }
275 }
276}
277
278impl Clone for AnyEntity {
279 fn clone(&self) -> Self {
280 if let Some(entity_map) = self.entity_map.upgrade() {
281 let entity_map = entity_map.read();
282 let count = entity_map
283 .counts
284 .get(self.entity_id)
285 .expect("detected over-release of a entity");
286 let prev_count = count.fetch_add(1, SeqCst);
287 assert_ne!(prev_count, 0, "Detected over-release of a entity.");
288 }
289
290 Self {
291 entity_id: self.entity_id,
292 entity_type: self.entity_type,
293 entity_map: self.entity_map.clone(),
294 #[cfg(any(test, feature = "leak-detection"))]
295 handle_id: self
296 .entity_map
297 .upgrade()
298 .unwrap()
299 .write()
300 .leak_detector
301 .handle_created(self.entity_id),
302 }
303 }
304}
305
306impl Drop for AnyEntity {
307 fn drop(&mut self) {
308 if let Some(entity_map) = self.entity_map.upgrade() {
309 let entity_map = entity_map.upgradable_read();
310 let count = entity_map
311 .counts
312 .get(self.entity_id)
313 .expect("detected over-release of a handle.");
314 let prev_count = count.fetch_sub(1, SeqCst);
315 assert_ne!(prev_count, 0, "Detected over-release of a entity.");
316 if prev_count == 1 {
317 // We were the last reference to this entity, so we can remove it.
318 let mut entity_map = RwLockUpgradableReadGuard::upgrade(entity_map);
319 entity_map.dropped_entity_ids.push(self.entity_id);
320 }
321 }
322
323 #[cfg(any(test, feature = "leak-detection"))]
324 if let Some(entity_map) = self.entity_map.upgrade() {
325 entity_map
326 .write()
327 .leak_detector
328 .handle_released(self.entity_id, self.handle_id)
329 }
330 }
331}
332
333impl<T> From<Entity<T>> for AnyEntity {
334 fn from(entity: Entity<T>) -> Self {
335 entity.any_entity
336 }
337}
338
339impl Hash for AnyEntity {
340 fn hash<H: Hasher>(&self, state: &mut H) {
341 self.entity_id.hash(state);
342 }
343}
344
345impl PartialEq for AnyEntity {
346 fn eq(&self, other: &Self) -> bool {
347 self.entity_id == other.entity_id
348 }
349}
350
351impl Eq for AnyEntity {}
352
353impl std::fmt::Debug for AnyEntity {
354 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
355 f.debug_struct("AnyEntity")
356 .field("entity_id", &self.entity_id.as_u64())
357 .finish()
358 }
359}
360
361/// A strong, well typed reference to a struct which is managed
362/// by GPUI
363#[derive(Deref, DerefMut)]
364pub struct Entity<T> {
365 #[deref]
366 #[deref_mut]
367 pub(crate) any_entity: AnyEntity,
368 pub(crate) entity_type: PhantomData<T>,
369}
370
371unsafe impl<T> Send for Entity<T> {}
372unsafe impl<T> Sync for Entity<T> {}
373impl<T> Sealed for Entity<T> {}
374
375impl<T: 'static> Entity<T> {
376 fn new(id: EntityId, entity_map: Weak<RwLock<EntityRefCounts>>) -> Self
377 where
378 T: 'static,
379 {
380 Self {
381 any_entity: AnyEntity::new(id, TypeId::of::<T>(), entity_map),
382 entity_type: PhantomData,
383 }
384 }
385
386 /// Get the entity ID associated with this entity
387 pub fn entity_id(&self) -> EntityId {
388 self.any_entity.entity_id
389 }
390
391 /// Downgrade this entity pointer to a non-retaining weak pointer
392 pub fn downgrade(&self) -> WeakEntity<T> {
393 WeakEntity {
394 any_entity: self.any_entity.downgrade(),
395 entity_type: self.entity_type,
396 }
397 }
398
399 /// Upgrade the given weak pointer to a retaining pointer, if it still exists
400 pub fn upgrade_from(weak: &WeakEntity<T>) -> Option<Self>
401 where
402 Self: Sized,
403 {
404 Some(Entity {
405 any_entity: weak.any_entity.upgrade()?,
406 entity_type: weak.entity_type,
407 })
408 }
409
410 /// Convert this into a dynamically typed entity.
411 pub fn into_any(self) -> AnyEntity {
412 self.any_entity
413 }
414
415 /// Grab a reference to this entity from the context.
416 pub fn read<'a>(&self, cx: &'a App) -> &'a T {
417 cx.entities.read(self)
418 }
419
420 /// Read the entity referenced by this handle with the given function.
421 pub fn read_with<R, C: AppContext>(
422 &self,
423 cx: &C,
424 f: impl FnOnce(&T, &App) -> R,
425 ) -> C::Result<R> {
426 cx.read_entity(self, f)
427 }
428
429 /// Updates the entity referenced by this handle with the given function.
430 ///
431 /// The update function receives a context appropriate for its environment.
432 /// When updating in an `App`, it receives a `Context`.
433 /// When updating in a `Window`, it receives a `Window` and a `Context`.
434 pub fn update<C, R>(
435 &self,
436 cx: &mut C,
437 update: impl FnOnce(&mut T, &mut Context<'_, T>) -> R,
438 ) -> C::Result<R>
439 where
440 C: AppContext,
441 {
442 cx.update_entity(self, update)
443 }
444
445 /// Updates the entity referenced by this handle with the given function if
446 /// the referenced entity still exists, within a visual context that has a window.
447 /// Returns an error if the entity has been released.
448 pub fn update_in<C, R>(
449 &self,
450 cx: &mut C,
451 update: impl FnOnce(&mut T, &mut Window, &mut Context<'_, T>) -> R,
452 ) -> C::Result<R>
453 where
454 C: VisualContext,
455 {
456 cx.update_window_entity(self, update)
457 }
458}
459
460impl<T> Clone for Entity<T> {
461 fn clone(&self) -> Self {
462 Self {
463 any_entity: self.any_entity.clone(),
464 entity_type: self.entity_type,
465 }
466 }
467}
468
469impl<T> std::fmt::Debug for Entity<T> {
470 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
471 f.debug_struct("Entity")
472 .field("entity_id", &self.any_entity.entity_id)
473 .field("entity_type", &type_name::<T>())
474 .finish()
475 }
476}
477
478impl<T> Hash for Entity<T> {
479 fn hash<H: Hasher>(&self, state: &mut H) {
480 self.any_entity.hash(state);
481 }
482}
483
484impl<T> PartialEq for Entity<T> {
485 fn eq(&self, other: &Self) -> bool {
486 self.any_entity == other.any_entity
487 }
488}
489
490impl<T> Eq for Entity<T> {}
491
492impl<T> PartialEq<WeakEntity<T>> for Entity<T> {
493 fn eq(&self, other: &WeakEntity<T>) -> bool {
494 self.any_entity.entity_id() == other.entity_id()
495 }
496}
497
498/// A type erased, weak reference to a entity.
499#[derive(Clone)]
500pub struct AnyWeakEntity {
501 pub(crate) entity_id: EntityId,
502 entity_type: TypeId,
503 entity_ref_counts: Weak<RwLock<EntityRefCounts>>,
504}
505
506impl AnyWeakEntity {
507 /// Get the entity ID associated with this weak reference.
508 pub fn entity_id(&self) -> EntityId {
509 self.entity_id
510 }
511
512 /// Check if this weak handle can be upgraded, or if the entity has already been dropped
513 pub fn is_upgradable(&self) -> bool {
514 let ref_count = self
515 .entity_ref_counts
516 .upgrade()
517 .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
518 .unwrap_or(0);
519 ref_count > 0
520 }
521
522 /// Upgrade this weak entity reference to a strong reference.
523 pub fn upgrade(&self) -> Option<AnyEntity> {
524 let ref_counts = &self.entity_ref_counts.upgrade()?;
525 let ref_counts = ref_counts.read();
526 let ref_count = ref_counts.counts.get(self.entity_id)?;
527
528 // entity_id is in dropped_entity_ids
529 if ref_count.load(SeqCst) == 0 {
530 return None;
531 }
532 ref_count.fetch_add(1, SeqCst);
533 drop(ref_counts);
534
535 Some(AnyEntity {
536 entity_id: self.entity_id,
537 entity_type: self.entity_type,
538 entity_map: self.entity_ref_counts.clone(),
539 #[cfg(any(test, feature = "leak-detection"))]
540 handle_id: self
541 .entity_ref_counts
542 .upgrade()
543 .unwrap()
544 .write()
545 .leak_detector
546 .handle_created(self.entity_id),
547 })
548 }
549
550 /// Assert that entity referenced by this weak handle has been released.
551 #[cfg(any(test, feature = "leak-detection"))]
552 pub fn assert_released(&self) {
553 self.entity_ref_counts
554 .upgrade()
555 .unwrap()
556 .write()
557 .leak_detector
558 .assert_released(self.entity_id);
559
560 if self
561 .entity_ref_counts
562 .upgrade()
563 .and_then(|ref_counts| Some(ref_counts.read().counts.get(self.entity_id)?.load(SeqCst)))
564 .is_some()
565 {
566 panic!(
567 "entity was recently dropped but resources are retained until the end of the effect cycle."
568 )
569 }
570 }
571}
572
573impl std::fmt::Debug for AnyWeakEntity {
574 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
575 f.debug_struct(type_name::<Self>())
576 .field("entity_id", &self.entity_id)
577 .field("entity_type", &self.entity_type)
578 .finish()
579 }
580}
581
582impl<T> From<WeakEntity<T>> for AnyWeakEntity {
583 fn from(entity: WeakEntity<T>) -> Self {
584 entity.any_entity
585 }
586}
587
588impl Hash for AnyWeakEntity {
589 fn hash<H: Hasher>(&self, state: &mut H) {
590 self.entity_id.hash(state);
591 }
592}
593
594impl PartialEq for AnyWeakEntity {
595 fn eq(&self, other: &Self) -> bool {
596 self.entity_id == other.entity_id
597 }
598}
599
600impl Eq for AnyWeakEntity {}
601
602/// A weak reference to a entity of the given type.
603#[derive(Deref, DerefMut)]
604pub struct WeakEntity<T> {
605 #[deref]
606 #[deref_mut]
607 any_entity: AnyWeakEntity,
608 entity_type: PhantomData<T>,
609}
610
611impl<T> std::fmt::Debug for WeakEntity<T> {
612 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
613 f.debug_struct(&type_name::<Self>())
614 .field("entity_id", &self.any_entity.entity_id)
615 .field("entity_type", &type_name::<T>())
616 .finish()
617 }
618}
619
620unsafe impl<T> Send for WeakEntity<T> {}
621unsafe impl<T> Sync for WeakEntity<T> {}
622
623impl<T> Clone for WeakEntity<T> {
624 fn clone(&self) -> Self {
625 Self {
626 any_entity: self.any_entity.clone(),
627 entity_type: self.entity_type,
628 }
629 }
630}
631
632impl<T: 'static> WeakEntity<T> {
633 /// Upgrade this weak entity reference into a strong entity reference
634 pub fn upgrade(&self) -> Option<Entity<T>> {
635 // Delegate to the trait implementation to keep behavior in one place.
636 Entity::upgrade_from(self)
637 }
638
639 /// Updates the entity referenced by this handle with the given function if
640 /// the referenced entity still exists. Returns an error if the entity has
641 /// been released.
642 pub fn update<C, R>(
643 &self,
644 cx: &mut C,
645 update: impl FnOnce(&mut T, &mut Context<'_, T>) -> R,
646 ) -> Result<R>
647 where
648 C: AppContext,
649 Result<C::Result<R>>: crate::Flatten<R>,
650 {
651 crate::Flatten::flatten(
652 self.upgrade()
653 .ok_or_else(|| anyhow!("entity released"))
654 .map(|this| cx.update_entity(&this, update)),
655 )
656 }
657
658 /// Updates the entity referenced by this handle with the given function if
659 /// the referenced entity still exists, within a visual context that has a window.
660 /// Returns an error if the entity has been released.
661 pub fn update_in<C, R>(
662 &self,
663 cx: &mut C,
664 update: impl FnOnce(&mut T, &mut Window, &mut Context<'_, T>) -> R,
665 ) -> Result<R>
666 where
667 C: VisualContext,
668 Result<C::Result<R>>: crate::Flatten<R>,
669 {
670 let window = cx.window_handle();
671 let this = self.upgrade().ok_or_else(|| anyhow!("entity released"))?;
672
673 crate::Flatten::flatten(window.update(cx, |_, window, cx| {
674 this.update(cx, |entity, cx| update(entity, window, cx))
675 }))
676 }
677
678 /// Reads the entity referenced by this handle with the given function if
679 /// the referenced entity still exists. Returns an error if the entity has
680 /// been released.
681 pub fn read_with<C, R>(&self, cx: &C, read: impl FnOnce(&T, &App) -> R) -> Result<R>
682 where
683 C: AppContext,
684 Result<C::Result<R>>: crate::Flatten<R>,
685 {
686 crate::Flatten::flatten(
687 self.upgrade()
688 .ok_or_else(|| anyhow!("entity release"))
689 .map(|this| cx.read_entity(&this, read)),
690 )
691 }
692}
693
694impl<T> Hash for WeakEntity<T> {
695 fn hash<H: Hasher>(&self, state: &mut H) {
696 self.any_entity.hash(state);
697 }
698}
699
700impl<T> PartialEq for WeakEntity<T> {
701 fn eq(&self, other: &Self) -> bool {
702 self.any_entity == other.any_entity
703 }
704}
705
706impl<T> Eq for WeakEntity<T> {}
707
708impl<T> PartialEq<Entity<T>> for WeakEntity<T> {
709 fn eq(&self, other: &Entity<T>) -> bool {
710 self.entity_id() == other.any_entity.entity_id()
711 }
712}
713
714#[cfg(any(test, feature = "leak-detection"))]
715static LEAK_BACKTRACE: std::sync::LazyLock<bool> =
716 std::sync::LazyLock::new(|| std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty()));
717
718#[cfg(any(test, feature = "leak-detection"))]
719#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
720pub(crate) struct HandleId {
721 id: u64, // id of the handle itself, not the pointed at object
722}
723
724#[cfg(any(test, feature = "leak-detection"))]
725pub(crate) struct LeakDetector {
726 next_handle_id: u64,
727 entity_handles: HashMap<EntityId, HashMap<HandleId, Option<backtrace::Backtrace>>>,
728}
729
730#[cfg(any(test, feature = "leak-detection"))]
731impl LeakDetector {
732 #[track_caller]
733 pub fn handle_created(&mut self, entity_id: EntityId) -> HandleId {
734 let id = util::post_inc(&mut self.next_handle_id);
735 let handle_id = HandleId { id };
736 let handles = self.entity_handles.entry(entity_id).or_default();
737 handles.insert(
738 handle_id,
739 LEAK_BACKTRACE.then(backtrace::Backtrace::new_unresolved),
740 );
741 handle_id
742 }
743
744 pub fn handle_released(&mut self, entity_id: EntityId, handle_id: HandleId) {
745 let handles = self.entity_handles.entry(entity_id).or_default();
746 handles.remove(&handle_id);
747 }
748
749 pub fn assert_released(&mut self, entity_id: EntityId) {
750 let handles = self.entity_handles.entry(entity_id).or_default();
751 if !handles.is_empty() {
752 for backtrace in handles.values_mut() {
753 if let Some(mut backtrace) = backtrace.take() {
754 backtrace.resolve();
755 eprintln!("Leaked handle: {:#?}", backtrace);
756 } else {
757 eprintln!("Leaked handle: export LEAK_BACKTRACE to find allocation site");
758 }
759 }
760 panic!();
761 }
762 }
763}
764
765#[cfg(test)]
766mod test {
767 use crate::EntityMap;
768
769 struct TestEntity {
770 pub i: i32,
771 }
772
773 #[test]
774 fn test_entity_map_slot_assignment_before_cleanup() {
775 // Tests that slots are not re-used before take_dropped.
776 let mut entity_map = EntityMap::new();
777
778 let slot = entity_map.reserve::<TestEntity>();
779 entity_map.insert(slot, TestEntity { i: 1 });
780
781 let slot = entity_map.reserve::<TestEntity>();
782 entity_map.insert(slot, TestEntity { i: 2 });
783
784 let dropped = entity_map.take_dropped();
785 assert_eq!(dropped.len(), 2);
786
787 assert_eq!(
788 dropped
789 .into_iter()
790 .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
791 .collect::<Vec<i32>>(),
792 vec![1, 2],
793 );
794 }
795
796 #[test]
797 fn test_entity_map_weak_upgrade_before_cleanup() {
798 // Tests that weak handles are not upgraded before take_dropped
799 let mut entity_map = EntityMap::new();
800
801 let slot = entity_map.reserve::<TestEntity>();
802 let handle = entity_map.insert(slot, TestEntity { i: 1 });
803 let weak = handle.downgrade();
804 drop(handle);
805
806 let strong = weak.upgrade();
807 assert_eq!(strong, None);
808
809 let dropped = entity_map.take_dropped();
810 assert_eq!(dropped.len(), 1);
811
812 assert_eq!(
813 dropped
814 .into_iter()
815 .map(|(_, entity)| entity.downcast::<TestEntity>().unwrap().i)
816 .collect::<Vec<i32>>(),
817 vec![1],
818 );
819 }
820}