Skip to content

Replace assert with proper null checks for content in write method #110

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 37 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
ceb7261
Replace assert in the AdvancementsPacket class
Isurunwg Jan 26, 2025
0b33873
Replace assert in the AnvilLoader class
Isurunwg Jan 26, 2025
5fa97ce
Replace assert in the ArrayUtils class
Isurunwg Jan 26, 2025
4f61319
Replace assert in the BinaryBuffer class
Isurunwg Jan 26, 2025
f9a4592
Replace assert in the BlockImpl class
Isurunwg Jan 26, 2025
faeddc3
Replace assert in the BlockLight class
Isurunwg Jan 26, 2025
d80c26a
Replace assert in the BlockUtils class
Isurunwg Jan 26, 2025
cde4ff0
Replace assert in the ChunkData class
Isurunwg Jan 26, 2025
86474c9
Replace assert in the ClientAdvancementTabPacket class
Isurunwg Jan 26, 2025
f17ed6c
Replace assert in the CollisionUtils class
Isurunwg Jan 26, 2025
bd980e3
Replace assert in the CommandParserImpl class
Isurunwg Jan 26, 2025
5222dee
Replace assert in the DataComponentMapImpl class
Isurunwg Jan 26, 2025
ea62d90
Replace assert in the DynamicChunk class
Isurunwg Jan 26, 2025
9c36630
Replace assert in the Entity lass
Isurunwg Jan 26, 2025
fd5c2ad
Replace assert in the EntityInstanceEvent lass
Isurunwg Jan 26, 2025
c20692d
Replace assert in the EntityView lass
Isurunwg Jan 26, 2025
5238047
Replace assert in the EventNodeImpl lass
Isurunwg Jan 26, 2025
68fb20b
Replace assert in the FlexiblePalette lass
Isurunwg Jan 26, 2025
d058602
Replace assert in the GeneratorImpl lass
Isurunwg Jan 26, 2025
d6a2ab3
Replace assert in the InstanceContainer lass
Isurunwg Jan 26, 2025
dd5b691
Replace assert in the NamespaceID lass
Isurunwg Jan 26, 2025
d0d1549
Replace assert in the NetworkBufferTypeImpl lass
Isurunwg Jan 26, 2025
99f5a81
Replace assert in the PacketProcessor lass
Isurunwg Jan 26, 2025
bce8fe2
Replace assert in the PacketUtils lass
Isurunwg Jan 26, 2025
3e4e7e6
Replace assert in the Player lass
Isurunwg Jan 26, 2025
bc13974
Replace assert in the ScoreboardObjectivePacket class
Isurunwg Jan 26, 2025
780db6a
Replace assert in the ServerLinksPacket class
Isurunwg Jan 26, 2025
bc79a9d
Replace assert in the ShapeImpl class
Isurunwg Jan 26, 2025
bbc2ee0
Replace assert in the Sidebar class
Isurunwg Jan 26, 2025
2dfa592
Replace assert in the StopSoundPacket class
Isurunwg Jan 26, 2025
f87fc07
Replace assert in the Tag class
Isurunwg Jan 26, 2025
f4e40aa
Replace assert in the TagHandlerImpl class
Isurunwg Jan 26, 2025
50ab13d
Replace assert in the TagNbtSeparator class
Isurunwg Jan 26, 2025
10082b4
Replace assert in the TagRecord class
Isurunwg Jan 26, 2025
9e3adee
Replace assert in the ThreadDispatcher class
Isurunwg Jan 26, 2025
86eedde
Replace assert in the TickThread class
Isurunwg Jan 26, 2025
8b8d641
Replace assert in the Worker class
Isurunwg Jan 26, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ public final class CollisionUtils {
public static PhysicsResult handlePhysics(@NotNull Entity entity, @NotNull Vec entityVelocity,
@Nullable PhysicsResult lastPhysicsResult, boolean singleCollision) {
final Instance instance = entity.getInstance();
assert instance != null;
if (instance == null) {
throw new IllegalStateException("Instance cannot be null for entity: " + entity);
}
return handlePhysics(instance, entity.getChunk(),
entity.getBoundingBox(),
entity.getPosition(), entityVelocity,
Expand Down Expand Up @@ -83,7 +85,9 @@ public static PhysicsResult handlePhysics(@NotNull Entity entity, @NotNull Vec e
public static PhysicsResult handlePhysics(@NotNull Entity entity, @NotNull Vec entityVelocity,
@Nullable PhysicsResult lastPhysicsResult) {
final Instance instance = entity.getInstance();
assert instance != null;
if (instance == null) {
throw new IllegalStateException("Instance cannot be null for entity: " + entity);
}
return handlePhysics(instance, entity.getChunk(),
entity.getBoundingBox(),
entity.getPosition(), entityVelocity,
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/net/minestom/server/collision/ShapeImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -175,9 +175,9 @@ private static BoundingBox[] parseRegistryBoundingBoxString(String str) {
final Vec min = new Vec(minX, minY, minZ);
final Vec max = new Vec(minX + boundXSize, minY + boundYSize, minZ + boundZSize);
final BoundingBox bb = new BoundingBox(min, max);
assert bb.minX() == minX;
assert bb.minY() == minY;
assert bb.minZ() == minZ;
if (bb.minX() != minX || bb.minY() != minY || bb.minZ() != minZ) {
throw new IllegalStateException("BoundingBox min values do not match the parsed values.");
}
boundingBoxes[i] = bb;
}
return boundingBoxes;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,9 @@ int cursor() {
}

void cursor(int cursor) {
assert cursor >= 0 && cursor <= input.length();
if (cursor < 0 || cursor > input.length()) {
throw new IllegalArgumentException("Cursor value must be between 0 and the length of the input.");
}
this.cursor = cursor;
}
}
Expand All @@ -431,7 +433,9 @@ private static <T> ArgumentResult<T> parseArgument(@NotNull CommandSender sender
return new ArgumentResult.IncompatibleType<>();
}
// Bruteforce
assert argument.allowSpace() && !argument.useRemaining();
if (!(argument.allowSpace() && !argument.useRemaining())) {
throw new IllegalArgumentException("Argument must allow space and not use remaining.");
}
StringBuilder current = new StringBuilder(reader.readWord());
while (true) {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,9 @@ public void write(@NotNull NetworkBuffer buffer, DataComponentMap value) {
buffer.write(NetworkBuffer.VAR_INT, entry.getIntKey());
//noinspection unchecked
DataComponent<Object> type = (DataComponent<Object>) this.idToType.apply(entry.getIntKey());
assert type != null;
if (type == null) {
throw new IllegalStateException("DataComponent type cannot be null for key: " + entry.getIntKey());
}
type.write(buffer, entry.getValue());
}
}
Expand Down
13 changes: 9 additions & 4 deletions src/main/java/net/minestom/server/entity/Entity.java
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,9 @@ public void remove(@NotNull Entity entity) {
@Override
public void referenceUpdate(@NotNull Point point, @Nullable EntityTracker tracker) {
final Instance currentInstance = tracker != null ? instance : null;
assert currentInstance == null || currentInstance.getEntityTracker() == tracker :
"EntityTracker does not match current instance";
if (currentInstance != null && currentInstance.getEntityTracker() != tracker) {
throw new IllegalStateException("EntityTracker does not match current instance");
}
viewEngine.updateTracker(currentInstance, point);
}
};
Expand Down Expand Up @@ -1237,7 +1238,9 @@ public void refreshPosition(@NotNull final Pos newPosition, boolean ignoreView,
final boolean positionChange = (distanceX + distanceY + distanceZ) > 0;

final Chunk chunk = getChunk();
assert chunk != null;
if (chunk == null) {
throw new IllegalStateException("Chunk cannot be null");
}
if (distanceX > 8 || distanceY > 8 || distanceZ > 8) {
PacketUtils.prepareViewablePacket(chunk, new EntityTeleportPacket(getEntityId(), position, isOnGround()), this);
nextSynchronizationTick = synchronizationTicks + 1;
Expand Down Expand Up @@ -1306,7 +1309,9 @@ protected void refreshCoordinate(Point newPosition) {
}
// Handle chunk switch
final Instance instance = getInstance();
assert instance != null;
if (instance == null) {
throw new IllegalStateException("Instance cannot be null");
}
instance.getEntityTracker().move(this, newPosition, trackingTarget, trackingUpdate);
final int lastChunkX = currentChunk.getChunkX();
final int lastChunkZ = currentChunk.getChunkZ();
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/net/minestom/server/entity/EntityView.java
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,9 @@ public boolean isRegistered(T entity) {
}

public void register(T entity) {
assert entity.getInstance() != null : "Instance-less entity shouldn't be registered as viewer";
if (entity.getInstance() == null) {
throw new IllegalArgumentException("Instance-less entity shouldn't be registered as viewer");
}
this.bitSet.add(entity.getEntityId());
}

Expand Down
4 changes: 3 additions & 1 deletion src/main/java/net/minestom/server/entity/Player.java
Original file line number Diff line number Diff line change
Expand Up @@ -678,7 +678,9 @@ public Void join() {
throw new RuntimeException(e);
}
scheduler.process();
assert isDone();
if (!isDone()) {
throw new IllegalStateException("Future should be completed before processing.");
}
}
return super.join();
}
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/net/minestom/server/event/EventNodeImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,9 @@ record Graph(String name, String eventType, int priority,
}

void invalidateEventsFor(EventNodeImpl<? super T> node) {
assert Thread.holdsLock(GLOBAL_CHILD_LOCK);
if (!Thread.holdsLock(GLOBAL_CHILD_LOCK)) {
throw new IllegalStateException("Thread must hold the GLOBAL_CHILD_LOCK to call this method");
}
for (Class<? extends T> eventType : listenerMap.keySet()) {
node.invalidateEvent(eventType);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ public interface EntityInstanceEvent extends EntityEvent, InstanceEvent {
@Override
default @NotNull Instance getInstance() {
final Instance instance = getEntity().getInstance();
assert instance != null : "EntityInstanceEvent is only supported on events where the entity's instance is non-null!";
if (instance == null) {
throw new IllegalStateException("EntityInstanceEvent is only supported on events where the entity's instance is non-null!");
}
return instance;
}
}
4 changes: 3 additions & 1 deletion src/main/java/net/minestom/server/instance/DynamicChunk.java
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,8 @@ private void calculateFullHeightmap() {
}

private void assertLock() {
assert Thread.holdsLock(this) : "Chunk must be locked before access";
if (!Thread.holdsLock(this)) {
throw new IllegalStateException("Chunk must be locked before access");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,9 @@ public Chunk getChunk(int chunkX, int chunkZ) {

EventDispatcher.call(new InstanceChunkLoadEvent(this, chunk));
final CompletableFuture<Chunk> future = this.loadingChunks.remove(index);
assert future == completableFuture : "Invalid future: " + future;
if (future != completableFuture) {
throw new IllegalStateException("Invalid future: " + future);
}
completableFuture.complete(chunk);
})
.exceptionally(throwable -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,9 @@ public void loadInstance(@NotNull Instance instance) {
perRegionLoadedChunksLock.lock();
try {
Set<IntIntImmutablePair> previousVersion = perRegionLoadedChunks.put(new IntIntImmutablePair(regionX, regionZ), new HashSet<>());
assert previousVersion == null : "The AnvilLoader cache should not already have data for this region.";
if (previousVersion != null) {
throw new IllegalStateException("The AnvilLoader cache should not already have data for this region.");
}
return new RegionFile(regionPath);
} catch (IOException e) {
MinecraftServer.getExceptionManager().handleException(e);
Expand Down
24 changes: 18 additions & 6 deletions src/main/java/net/minestom/server/instance/block/BlockImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,9 @@ static Collection<Block> values() {
@Override
public @NotNull Block withProperty(@NotNull String property, @NotNull String value) {
final PropertyType[] propertyTypes = PROPERTIES_TYPE.get(id());
assert propertyTypes != null;
if (propertyTypes == null) {
throw new IllegalStateException("Property types cannot be null for id: " + id());
}
final byte keyIndex = findKeyIndex(propertyTypes, property, this);
final byte valueIndex = findValueIndex(propertyTypes[keyIndex], value, this);
final long updatedProperties = updateIndex(propertiesArray, keyIndex, valueIndex);
Expand All @@ -81,7 +83,9 @@ static Collection<Block> values() {
public @NotNull Block withProperties(@NotNull Map<@NotNull String, @NotNull String> properties) {
if (properties.isEmpty()) return this;
final PropertyType[] propertyTypes = PROPERTIES_TYPE.get(id());
assert propertyTypes != null;
if (propertyTypes == null) {
throw new IllegalStateException("Property types cannot be null for id: " + id());
}
long updatedProperties = this.propertiesArray;
for (Map.Entry<String, String> entry : properties.entrySet()) {
final byte keyIndex = findKeyIndex(propertyTypes, entry.getKey(), this);
Expand Down Expand Up @@ -114,7 +118,9 @@ static Collection<Block> values() {
@Override
public @Unmodifiable @NotNull Map<String, String> properties() {
final PropertyType[] propertyTypes = PROPERTIES_TYPE.get(id());
assert propertyTypes != null;
if (propertyTypes == null) {
throw new IllegalStateException("Property types cannot be null for id: " + id());
}
final int length = propertyTypes.length;
if (length == 0) return Map.of();
String[] keys = new String[length];
Expand Down Expand Up @@ -167,7 +173,9 @@ public int hashCode() {
private Block compute(long updatedProperties) {
if (updatedProperties == this.propertiesArray) return this;
final BlockImpl block = possibleProperties().get(updatedProperties);
assert block != null;
if (block == null) {
throw new IllegalStateException("Block cannot be null for updated properties: " + updatedProperties);
}
// Reuse the same block instance if possible
if (nbt == null && handler == null) return block;
// Otherwise copy with the nbt and handler
Expand All @@ -192,7 +200,9 @@ private static Block createImpl(String namespace, Registry.Properties properties
for (var entry : stateProperties) {
final var k = entry.getKey();
final var v = (List<String>) entry.getValue();
assert v.size() < MAX_VALUES;
if (v.size() >= MAX_VALUES) {
throw new IllegalStateException("Too many values for property " + k + " in block " + namespace);
}
propertyTypes[i++] = new PropertyType(k, v);
}
} else {
Expand All @@ -211,7 +221,9 @@ private static Block createImpl(String namespace, Registry.Properties properties
final String query = stateEntry.getKey();
final var stateOverride = (Map<String, Object>) stateEntry.getValue();
final var propertyMap = BlockUtils.parseProperties(query);
assert propertyTypes.length == propertyMap.size();
if (propertyTypes.length != propertyMap.size()) {
throw new IllegalStateException("Property types size mismatch for query " + query);
}
long propertiesValue = 0;
for (Map.Entry<String, String> entry : propertyMap.entrySet()) {
final byte keyIndex = findKeyIndex(propertyTypes, entry.getKey(), null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,12 @@ static final class DynamicFork implements Block.Setter {
public void setBlock(int x, int y, int z, @NotNull Block block) {
resize(x, y, z);
GenerationUnit section = findAbsolute(sections, minSection, width, height, depth, x, y, z);
assert section.absoluteStart().chunkX() == getChunkCoordinate(x) &&
boolean isValidSection = section.absoluteStart().chunkX() == getChunkCoordinate(x) &&
section.absoluteStart().section() == getChunkCoordinate(y) &&
section.absoluteStart().chunkZ() == getChunkCoordinate(z) :
"Invalid section " + section.absoluteStart() + " for " + x + ", " + y + ", " + z;
section.absoluteStart().chunkZ() == getChunkCoordinate(z);
if (!isValidSection) {
throw new IllegalStateException("Invalid section " + section.absoluteStart() + " for coordinates (" + x + ", " + y + ", " + z + ")");
}
section.modifier().setBlock(x, y, z, block);
}

Expand Down Expand Up @@ -528,7 +530,9 @@ private static GenerationUnit findAbsolute(List<GenerationUnit> units, Point sta

private static int findIndex(int width, int height, int depth,
int x, int y, int z) {
assert width > 0 && height > 0 && depth > 0;
if (width <= 0 || height <= 0 || depth <= 0) {
throw new IllegalArgumentException("Dimensions (width, height, depth) must be positive");
}
return (z * width * height) + (y * width) + x;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ static ShortArrayFIFOQueue buildInternalQueue(Palette blockPalette) {
// Apply section light
blockPalette.getAllPresent((x, y, z, stateId) -> {
final Block block = Block.fromStateId((short) stateId);
assert block != null;
if (block == null) {
throw new IllegalStateException("Block cannot be null for stateId: " + stateId);
}
final byte lightEmission = (byte) block.registry().lightEmission();

final int index = x | (z << 4) | (y << 8);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,9 @@ public void setAll(@NotNull EntrySupplier supplier) {
}
}
}
assert index == maxSize();
if (index != maxSize()) {
throw new IllegalStateException("Index does not match the expected max size");
}
// Update palette content
if (fillValue < 0) {
updateAll(cache);
Expand Down Expand Up @@ -167,7 +169,9 @@ public void replaceAll(@NotNull EntryFunction function) {
cache[index] = newValue != value ? getPaletteIndex(newValue) : value;
if (newValue != 0) count.setPlain(count.getPlain() + 1);
});
assert arrayIndex.getPlain() == maxSize();
if (arrayIndex.getPlain() != maxSize()) {
throw new IllegalStateException("Array index does not match the expected max size");
}
// Update palette content
updateAll(cache);
this.count = count.getPlain();
Expand Down Expand Up @@ -249,7 +253,9 @@ private void retrieveAll(@NotNull EntryConsumer consumer, boolean consumeEmpty)

private void updateAll(int[] paletteValues) {
final int size = maxSize();
assert paletteValues.length >= size;
if (paletteValues.length < size) {
throw new IllegalArgumentException("Palette values array length is smaller than the expected size");
}
final int bitsPerEntry = this.bitsPerEntry;
final int valuesPerLong = 64 / bitsPerEntry;
final long clear = (1L << bitsPerEntry) - 1L;
Expand All @@ -274,7 +280,9 @@ void resize(byte newBitsPerEntry) {
getAll(palette::set);
this.bitsPerEntry = palette.bitsPerEntry;
this.values = palette.values;
assert this.count == palette.count;
if (this.count != palette.count) {
throw new IllegalStateException("Palette count mismatch after resizing");
}
}

private int getPaletteIndex(int value) {
Expand All @@ -289,7 +297,9 @@ private int getPaletteIndex(int value) {
final int lookup = valueToPaletteMap.putIfAbsent(value, lastPaletteIndex);
if (lookup != -1) return lookup;
this.paletteToValueList.add(value);
assert lastPaletteIndex < maxPaletteSize(bpe);
if (lastPaletteIndex >= maxPaletteSize(bpe)) {
throw new IllegalStateException("Palette size exceeded after adding new value");
}
return lastPaletteIndex;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,9 @@ public void write(@NotNull NetworkBuffer buffer, byte[] value) {
public byte[] read(@NotNull NetworkBuffer buffer) {
final int limit = buffer.nioBuffer.limit();
final int length = limit - buffer.readIndex();
assert length >= 0 : "Invalid remaining: " + length;
if (length < 0) {
throw new IllegalStateException("Invalid remaining: " + length);
}
final byte[] bytes = new byte[length];
buffer.nioBuffer.get(buffer.readIndex(), bytes);
buffer.readIndex += length;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ public PacketProcessor(@NotNull PacketListenerManager packetListenerManager) {
NetworkBuffer buffer = new NetworkBuffer(body);
final ClientPacket clientPacket = switch (connectionState) {
case HANDSHAKE -> {
assert packetId == 0;
if (packetId != 0) {
throw new IllegalArgumentException("Invalid packetId for HANDSHAKE state. Expected packetId 0.");
}
yield new ClientHandshakePacket(buffer);
}
case STATUS -> statusHandler.create(packetId, buffer);
Expand All @@ -57,7 +59,9 @@ public ClientPacket process(@NotNull PlayerConnection connection, int packetId,
}

final Player player = connection.getPlayer();
assert player != null;
if (player == null) {
throw new IllegalStateException("Player should not be null");
}
player.addPacketToQueue(packet);
return packet;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ private static ClientAdvancementTabPacket read(@NotNull NetworkBuffer reader) {
public void write(@NotNull NetworkBuffer writer) {
writer.writeEnum(AdvancementAction.class, action);
if (action == AdvancementAction.OPENED_TAB) {
assert tabIdentifier != null;
if (tabIdentifier == null) {
throw new IllegalStateException("Tab identifier must not be null.");
}
if (tabIdentifier.length() > 256) {
throw new IllegalArgumentException("Tab identifier cannot be longer than 256 characters.");
}
Expand Down
Loading
Loading