Skip to content

Commit

Permalink
Make most Entity methods const (#5688)
Browse files Browse the repository at this point in the history
# Objective

Fixes #5687

## Solution

Update the methods on the `Entity` struct to be `const`, so we can
define compile-time constants and more generally use them in a const
context.

---

## Changelog

### Added

- Most `Entity` methods are now `const fn`.
  • Loading branch information
djeedai committed Aug 30, 2022
1 parent 24e5e10 commit fe6246d
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions crates/bevy_ecs/src/entity/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ impl Entity {
/// }
/// }
/// ```
pub fn from_raw(id: u32) -> Entity {
pub const fn from_raw(id: u32) -> Entity {
Entity { id, generation: 0 }
}

Expand All @@ -183,7 +183,7 @@ impl Entity {
/// Reconstruct an `Entity` previously destructured with [`Entity::to_bits`].
///
/// Only useful when applied to results from `to_bits` in the same instance of an application.
pub fn from_bits(bits: u64) -> Self {
pub const fn from_bits(bits: u64) -> Self {
Self {
generation: (bits >> 32) as u32,
id: bits as u32,
Expand All @@ -196,15 +196,15 @@ impl Entity {
/// with both live and dead entities. Useful for compactly representing entities within a
/// specific snapshot of the world, such as when serializing.
#[inline]
pub fn id(self) -> u32 {
pub const fn id(self) -> u32 {
self.id
}

/// Returns the generation of this Entity's id. The generation is incremented each time an
/// entity with a given id is despawned. This serves as a "count" of the number of times a
/// given id has been reused (id, generation) pairs uniquely identify a given Entity.
#[inline]
pub fn generation(self) -> u32 {
pub const fn generation(self) -> u32 {
self.generation
}
}
Expand Down Expand Up @@ -697,4 +697,21 @@ mod tests {
assert!(entities.contains(e));
assert!(entities.get(e).is_none());
}

#[test]
fn entity_const() {
const C1: Entity = Entity::from_raw(42);
assert_eq!(42, C1.id);
assert_eq!(0, C1.generation);

const C2: Entity = Entity::from_bits(0x0000_00ff_0000_00cc);
assert_eq!(0x0000_00cc, C2.id);
assert_eq!(0x0000_00ff, C2.generation);

const C3: u32 = Entity::from_raw(33).id();
assert_eq!(33, C3);

const C4: u32 = Entity::from_bits(0x00dd_00ff_0000_0000).generation();
assert_eq!(0x00dd_00ff, C4);
}
}

0 comments on commit fe6246d

Please sign in to comment.