Skip to content

Commit

Permalink
Make World::register* functions idempotent (amethyst#96)
Browse files Browse the repository at this point in the history
Previously repeated calls to `register` (and friends) would stomp over
the existing storage for the component type.

Now repeated calls will silently do nothing.
  • Loading branch information
jeffparsons committed Feb 8, 2017
1 parent a881c25 commit 041fcbd
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/world.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,9 +249,14 @@ impl<C> World<C>
}
}
/// Registers a new component type and id pair.
///
/// Does nothing if the type and id pair was already registered.
pub fn register_w_comp_id<T: Component>(&mut self, comp_id: C) {
let any = RwLock::new(MaskedStorage::<T>::new());
self.components.insert((comp_id, TypeId::of::<T>()), Box::new(any));
self.components.entry((comp_id, TypeId::of::<T>()))
.or_insert_with(|| {
let any = RwLock::new(MaskedStorage::<T>::new());
Box::new(any)
});
}
/// Unregisters a component type and id pair.
pub fn unregister_w_comp_id<T: Component>(&mut self, comp_id: C) -> Option<MaskedStorage<T>> {
Expand Down Expand Up @@ -382,6 +387,8 @@ impl World<()> {
}

/// Registers a new component type.
///
/// Does nothing if the component type was already registered.
pub fn register<T: Component>(&mut self) {
self.register_w_comp_id::<T>(())
}
Expand Down
20 changes: 20 additions & 0 deletions tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,3 +299,23 @@ fn dynamic_component() {
let c = w.read_w_comp_id::<CompBool>(2).get(e).unwrap().0;
assert_eq!(c, true);
}

#[test]
fn register_idempotency() {
// Test that repeated calls to `register` do not silently
// stomp over the existing storage, but instead silently do nothing.
let mut w = specs::World::new();
w.register::<CompInt>();

let e = w.create_now()
.with::<CompInt>(CompInt(10))
.build();

// At the time this test was written, a call to `register`
// would blindly plough ahead and stomp the existing storage, so...
w.register::<CompInt>();

// ...this would end up trying to unwrap a `None`.
let i = w.read::<CompInt>().get(e).unwrap().0;
assert_eq!(i, 10);
}

0 comments on commit 041fcbd

Please sign in to comment.