Minestom/src/main/java/net/minestom/server/utils/PacketUtils.java

77 lines
2.2 KiB
Java
Raw Normal View History

2020-04-24 03:25:58 +02:00
package net.minestom.server.utils;
2019-08-22 14:52:32 +02:00
2020-04-17 01:16:02 +02:00
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
2020-04-24 03:25:58 +02:00
import net.minestom.server.network.packet.server.ServerPacket;
import net.minestom.server.utils.binary.BinaryWriter;
2020-11-05 22:20:51 +01:00
import org.jetbrains.annotations.NotNull;
2019-08-22 14:52:32 +02:00
2020-08-15 04:05:15 +02:00
/**
2020-10-15 21:16:31 +02:00
* Class used to write packets.
2020-08-15 04:05:15 +02:00
*/
public final class PacketUtils {
private PacketUtils() {
}
2019-08-22 14:52:32 +02:00
2020-08-15 04:05:15 +02:00
/**
2020-10-15 21:16:31 +02:00
* Writes a {@link ServerPacket} into a {@link ByteBuf}.
2020-08-15 04:05:15 +02:00
*
* @param buf the recipient of {@code packet}
* @param packet the packet to write into {@code buf}
*/
2020-11-05 22:20:51 +01:00
public static void writePacket(@NotNull ByteBuf buf, @NotNull ServerPacket packet) {
2020-04-17 01:16:02 +02:00
final ByteBuf packetBuffer = getPacketBuffer(packet);
writePacket(buf, packetBuffer, packet.getId());
}
2020-04-17 01:16:02 +02:00
2020-08-15 04:05:15 +02:00
/**
2020-10-15 21:16:31 +02:00
* Writes a {@link ServerPacket} into a newly created {@link ByteBuf}.
2020-08-15 04:05:15 +02:00
*
* @param packet the packet to write
* @return a {@link ByteBuf} containing {@code packet}
*/
2020-11-05 22:20:51 +01:00
@NotNull
public static ByteBuf writePacket(@NotNull ServerPacket packet) {
final ByteBuf packetBuffer = getPacketBuffer(packet);
2020-04-17 01:16:02 +02:00
// Add 5 for the packet id and for the packet size
final int size = packetBuffer.writerIndex() + 5 + 5;
ByteBuf buffer = Unpooled.buffer(size);
writePacket(buffer, packetBuffer, packet.getId());
2020-03-20 19:50:22 +01:00
return buffer;
2019-08-23 15:37:38 +02:00
}
/**
2020-10-15 21:16:31 +02:00
* Writes a packet buffer into {@code buf}.
*
* @param buf the buffer which will receive the packet id/data
* @param packetBuffer the buffer containing the raw packet data
* @param packetId the packet id
*/
2020-11-05 22:20:51 +01:00
private static void writePacket(@NotNull ByteBuf buf, @NotNull ByteBuf packetBuffer, int packetId) {
Utils.writeVarIntBuf(buf, packetId);
buf.writeBytes(packetBuffer);
}
/**
2020-10-15 21:16:31 +02:00
* Gets the buffer representing the raw packet data.
*
* @param packet the packet to write
* @return the {@link ByteBuf} containing the raw packet data
*/
2020-11-05 22:20:51 +01:00
@NotNull
private static ByteBuf getPacketBuffer(@NotNull ServerPacket packet) {
BinaryWriter writer = new BinaryWriter();
packet.write(writer);
return writer.getBuffer();
}
2019-08-22 14:52:32 +02:00
}