ForgePatch/fml/src/main/java/cpw/mods/fml/common/network/ByteBufUtils.java

63 lines
1.8 KiB
Java
Raw Normal View History

package cpw.mods.fml.common.network;
import org.apache.commons.lang3.Validate;
import com.google.common.base.Charsets;
import io.netty.buffer.ByteBuf;
public class ByteBufUtils {
public static int varIntByteCount(int toCount)
{
return (toCount & -128) == 0 ? 1 : ((toCount & -16384) == 0 ? 2 : ((toCount & -2097152) == 0 ? 3 : ((toCount & -268435456) == 0 ? 4 : 5)));
}
public static int readVarInt(ByteBuf buf, int maxSize)
{
Validate.isTrue(maxSize < 6 && maxSize > 0, "Varint length is between 1 and 5, not %d", maxSize);
int i = 0;
int j = 0;
byte b0;
do
{
b0 = buf.readByte();
i |= (b0 & 127) << j++ * 7;
if (j > maxSize)
{
throw new RuntimeException("VarInt too big");
}
}
while ((b0 & 128) == 128);
return i;
}
public static void writeVarInt(ByteBuf to, int toWrite, int maxSize)
{
Validate.isTrue(varIntByteCount(toWrite) < maxSize, "Integer is too big for %d bytes", maxSize);
while ((toWrite & -128) != 0)
{
to.writeByte(toWrite & 127 | 128);
toWrite >>>= 7;
}
to.writeByte(toWrite);
}
public static String readUTF8String(ByteBuf from)
{
int len = readVarInt(from,2);
String str = from.toString(from.readerIndex(), len, Charsets.UTF_8);
from.readerIndex(from.readerIndex() + len);
return str;
}
public static void writeUTF8String(ByteBuf to, String string)
{
byte[] utf8Bytes = string.getBytes(Charsets.UTF_8);
Validate.isTrue(varIntByteCount(utf8Bytes.length) < 3, "The string is too long for this encoding.");
writeVarInt(to, utf8Bytes.length, 2);
to.writeBytes(utf8Bytes);
}
}