Skip to content

Commit

Permalink
[bevy_ecs] Cleanup SparseSetIndex impls (#2099)
Browse files Browse the repository at this point in the history
Problem:
- SparseSetIndex trait implementations had a lot of duplicated code.

Solution:
- Utilize a macro to implement the trait for a generic type.
  • Loading branch information
NathanSWard committed May 7, 2021
1 parent bfd15d2 commit 883abbb
Showing 1 changed file with 12 additions and 46 deletions.
58 changes: 12 additions & 46 deletions crates/bevy_ecs/src/storage/sparse_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,55 +368,21 @@ pub trait SparseSetIndex: Clone {
fn get_sparse_set_index(value: usize) -> Self;
}

impl SparseSetIndex for u8 {
fn sparse_set_index(&self) -> usize {
*self as usize
}

fn get_sparse_set_index(value: usize) -> Self {
value as u8
}
}

impl SparseSetIndex for u16 {
fn sparse_set_index(&self) -> usize {
*self as usize
}

fn get_sparse_set_index(value: usize) -> Self {
value as u16
}
}

impl SparseSetIndex for u32 {
fn sparse_set_index(&self) -> usize {
*self as usize
}

fn get_sparse_set_index(value: usize) -> Self {
value as u32
}
}

impl SparseSetIndex for u64 {
fn sparse_set_index(&self) -> usize {
*self as usize
}
macro_rules! impl_sparse_set_index {
($($ty:ty),+) => {
$(impl SparseSetIndex for $ty {
fn sparse_set_index(&self) -> usize {
*self as usize
}

fn get_sparse_set_index(value: usize) -> Self {
value as u64
}
fn get_sparse_set_index(value: usize) -> Self {
value as $ty
}
})*
};
}

impl SparseSetIndex for usize {
fn sparse_set_index(&self) -> usize {
*self
}

fn get_sparse_set_index(value: usize) -> Self {
value
}
}
impl_sparse_set_index!(u8, u16, u32, u64, usize);

#[derive(Default)]
pub struct SparseSets {
Expand Down

0 comments on commit 883abbb

Please sign in to comment.