diff --git a/crates/bevy_ecs/src/archetype.rs b/crates/bevy_ecs/src/archetype.rs index 9201f154ac..d6a67d8fff 100644 --- a/crates/bevy_ecs/src/archetype.rs +++ b/crates/bevy_ecs/src/archetype.rs @@ -588,13 +588,6 @@ struct ArchetypeComponents { #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] pub struct ArchetypeComponentId(usize); -impl ArchetypeComponentId { - #[inline] - pub(crate) const fn new(index: usize) -> Self { - Self(index) - } -} - impl SparseSetIndex for ArchetypeComponentId { #[inline] fn sparse_set_index(&self) -> usize { @@ -614,7 +607,7 @@ impl SparseSetIndex for ArchetypeComponentId { /// [module level documentation]: crate::archetype pub struct Archetypes { pub(crate) archetypes: Vec, - pub(crate) archetype_component_count: usize, + archetype_component_count: usize, by_components: bevy_utils::HashMap, } @@ -666,6 +659,22 @@ impl Archetypes { } } + /// Generate and store a new [`ArchetypeComponentId`]. + /// + /// This simply increment the counter and return the new value. + /// + /// # Panics + /// + /// On archetype component id overflow. + pub(crate) fn new_archetype_component_id(&mut self) -> ArchetypeComponentId { + let id = ArchetypeComponentId(self.archetype_component_count); + self.archetype_component_count = self + .archetype_component_count + .checked_add(1) + .expect("archetype_component_count overflow"); + id + } + /// Fetches an immutable reference to an [`Archetype`] using its /// ID. Returns `None` if no corresponding archetype exists. #[inline] diff --git a/crates/bevy_ecs/src/world/mod.rs b/crates/bevy_ecs/src/world/mod.rs index fb9a3f8924..f79d6abdeb 100644 --- a/crates/bevy_ecs/src/world/mod.rs +++ b/crates/bevy_ecs/src/world/mod.rs @@ -1780,13 +1780,11 @@ impl World { &mut self, component_id: ComponentId, ) -> &mut ResourceData { - let archetype_component_count = &mut self.archetypes.archetype_component_count; + let archetypes = &mut self.archetypes; self.storages .resources .initialize_with(component_id, &self.components, || { - let id = ArchetypeComponentId::new(*archetype_component_count); - *archetype_component_count += 1; - id + archetypes.new_archetype_component_id() }) } @@ -1797,13 +1795,11 @@ impl World { &mut self, component_id: ComponentId, ) -> &mut ResourceData { - let archetype_component_count = &mut self.archetypes.archetype_component_count; + let archetypes = &mut self.archetypes; self.storages .non_send_resources .initialize_with(component_id, &self.components, || { - let id = ArchetypeComponentId::new(*archetype_component_count); - *archetype_component_count += 1; - id + archetypes.new_archetype_component_id() }) }