Avoid allocation when writing framed packets

Signed-off-by: TheMode <themode@outlook.fr>
This commit is contained in:
TheMode 2021-10-25 23:55:20 +02:00
parent 1b4e0519ee
commit 00401bed25
3 changed files with 12 additions and 7 deletions

View File

@ -9,9 +9,14 @@ import java.nio.ByteBuffer;
/**
* Represents a packet which is already framed. (packet id+payload) + optional compression
* Can be used if you want to send the exact same buffer to multiple clients without processing it more than once.
* <p>
* The {@link ByteBuffer} will ultimately become a MemorySegment once out of incubation.
*/
@ApiStatus.Internal
public record FramedPacket(int packetId,
@NotNull ByteBuffer body,
@NotNull ServerPacket packet) {
public record FramedPacket(@NotNull ServerPacket packet,
@NotNull ByteBuffer body) {
public FramedPacket {
body = body.position(0).asReadOnlyBuffer();
}
}

View File

@ -226,7 +226,7 @@ public class PlayerSocketConnection extends PlayerConnection {
@Override
public void sendPacket(@NotNull FramedPacket framedPacket) {
write(framedPacket.body().duplicate().position(0));
write(framedPacket.body());
}
@ApiStatus.Internal

View File

@ -120,7 +120,7 @@ public final class PacketUtils {
if (!PACKET_LISTENER_MANAGER.processServerPacket(packet, players))
return;
final ByteBuffer finalBuffer = createFramedPacket(packet).flip();
final FramedPacket framedPacket = new FramedPacket(packet.getId(), finalBuffer, packet);
final FramedPacket framedPacket = new FramedPacket(packet, finalBuffer);
// Send packet to all players
for (Player player : players) {
if (!player.isOnline() || !playerValidator.isValid(player))
@ -234,8 +234,8 @@ public final class PacketUtils {
public static FramedPacket allocateTrimmedPacket(@NotNull ServerPacket packet) {
final ByteBuffer temp = PacketUtils.createFramedPacket(packet).flip();
final ByteBuffer buffer = ByteBuffer.allocateDirect(temp.remaining())
.put(temp).flip().asReadOnlyBuffer();
return new FramedPacket(packet.getId(), buffer, packet);
.put(temp).flip();
return new FramedPacket(packet, buffer);
}
private static final class ViewableStorage {