Skip to content

Commit

Permalink
flipped entities repr for ordering
Browse files Browse the repository at this point in the history
  • Loading branch information
sanbox-irl committed Dec 6, 2023
1 parent 428885e commit b6573d7
Showing 1 changed file with 11 additions and 9 deletions.
20 changes: 11 additions & 9 deletions src/entities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ use std::error::Error;
/// able to save space by only serializing the output of `Entity::id`.
#[derive(Clone, Copy, Hash, Eq, Ord, PartialEq, PartialOrd)]
pub struct Entity {
pub(crate) generation: NonZeroU32,
pub(crate) id: u32,
pub(crate) generation: NonZeroU32,
}

impl Entity {
Expand All @@ -41,21 +41,23 @@ impl Entity {
/// Useful for storing entity IDs externally, or in conjunction with `Entity::from_bits` and
/// `World::spawn_at` for easy serialization. Alternatively, consider `id` for more compact
/// representation.
pub fn to_bits(self) -> NonZeroU64 {
unsafe {
NonZeroU64::new_unchecked(u64::from(self.generation.get()) << 32 | u64::from(self.id))
}
pub const fn to_bits(self) -> NonZeroU64 {
unsafe { NonZeroU64::new_unchecked((self.id as u64) << 32 | self.generation.get() as u64) }
}

/// Reconstruct an `Entity` previously destructured with `to_bits` if the bitpattern is valid,
/// else `None`
///
/// Useful for storing entity IDs externally, or in conjunction with `Entity::to_bits` and
/// `World::spawn_at` for easy serialization.
pub fn from_bits(bits: u64) -> Option<Self> {
pub const fn from_bits(bits: u64) -> Option<Self> {
Some(Self {
generation: NonZeroU32::new((bits >> 32) as u32)?,
id: bits as u32,
id: (bits >> 32) as u32,
// `?` is not yet supported in const fns
generation: match NonZeroU32::new(bits as u32) {
Some(g) => g,
None => return None,
},
})
}

Expand All @@ -66,7 +68,7 @@ impl Entity {
/// specific snapshot of the world, such as when serializing.
///
/// See also `World::find_entity_from_id`.
pub fn id(self) -> u32 {
pub const fn id(self) -> u32 {
self.id
}
}
Expand Down

0 comments on commit b6573d7

Please sign in to comment.