Ensure unmodifiable view

This commit is contained in:
themode 2021-12-24 00:21:32 +01:00 committed by TheMode
parent 2c7aae6bec
commit 5d4dd1f9f4
2 changed files with 33 additions and 5 deletions

View File

@ -119,7 +119,8 @@ final class EntityTrackerImpl implements EntityTracker {
public @Unmodifiable <T extends Entity> Collection<T> chunkEntities(int chunkX, int chunkZ, @NotNull Target<T> target) {
final TargetEntry<Entity> entry = entries[target.ordinal()];
//noinspection unchecked
return (Collection<T>) entry.chunkEntities.computeIfAbsent(getChunkIndex(chunkX, chunkZ), i -> LIST_SUPPLIER.get());
var chunkEntities = (List<T>) entry.chunkEntities.computeIfAbsent(getChunkIndex(chunkX, chunkZ), i -> LIST_SUPPLIER.get());
return Collections.unmodifiableList(chunkEntities);
}
@Override

View File

@ -31,13 +31,9 @@ public class EntityTrackerTest {
assertTrue(chunkEntities.isEmpty());
tracker.register(ent1, Vec.ZERO, EntityTracker.Target.ENTITIES, updater);
assertTrue(chunkEntities.isEmpty());
chunkEntities = tracker.chunkEntities(Vec.ZERO, EntityTracker.Target.ENTITIES);
assertEquals(1, chunkEntities.size());
tracker.unregister(ent1, EntityTracker.Target.ENTITIES, updater);
chunkEntities = tracker.chunkEntities(Vec.ZERO, EntityTracker.Target.ENTITIES);
assertEquals(0, chunkEntities.size());
}
@ -124,4 +120,35 @@ public class EntityTrackerTest {
}
});
}
@Test
public void collectionView() {
var ent1 = new Entity(EntityType.ZOMBIE);
var updater = new EntityTracker.Update<>() {
@Override
public void add(@NotNull Entity entity) {
assertNotSame(ent1, entity);
fail("No other entity should be registered yet");
}
@Override
public void remove(@NotNull Entity entity) {
assertNotSame(ent1, entity);
fail("No other entity should be registered yet");
}
};
EntityTracker tracker = EntityTracker.newTracker();
var entities = tracker.entities();
var chunkEntities = tracker.chunkEntities(Vec.ZERO, EntityTracker.Target.ENTITIES);
assertTrue(entities.isEmpty());
assertTrue(chunkEntities.isEmpty());
tracker.register(ent1, Vec.ZERO, EntityTracker.Target.ENTITIES, updater);
assertEquals(1, entities.size());
assertEquals(1, chunkEntities.size());
assertThrows(Exception.class, () -> entities.add(new Entity(EntityType.ZOMBIE)));
assertThrows(Exception.class, () -> chunkEntities.add(new Entity(EntityType.ZOMBIE)));
}
}