Reduce varint reading cost from max(1, 2n) to n+1 operations on ByteBuf
The previous code, in an attempt to avoid exceptions, checked in.isReadable() each iteration of the loop. This isn't very efficient since it's possible for us to know the maximum size of the varint to read: it's the minimum of either the largest size a varint can be (5 bytes) or the size of the remaining readable bytes in the buffer.
This commit is contained in:
@@ -67,21 +67,15 @@ public enum ProtocolUtils {
|
||||
*/
|
||||
public static int readVarIntSafely(ByteBuf buf) {
|
||||
int i = 0;
|
||||
int j = 0;
|
||||
while (true) {
|
||||
if (!buf.isReadable()) {
|
||||
return Integer.MIN_VALUE;
|
||||
}
|
||||
int maxRead = Math.min(5, buf.readableBytes());
|
||||
for (int j = 0; j < maxRead; j++) {
|
||||
int k = buf.readByte();
|
||||
i |= (k & 0x7F) << j++ * 7;
|
||||
if (j > 5) {
|
||||
return Integer.MIN_VALUE;
|
||||
}
|
||||
i |= (k & 0x7F) << j * 7;
|
||||
if ((k & 0x80) != 128) {
|
||||
break;
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return i;
|
||||
return Integer.MIN_VALUE;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@@ -42,8 +42,6 @@ public class MinecraftVarintFrameDecoder extends ByteToMessageDecoder {
|
||||
if (in.isReadable(minimumRead)) {
|
||||
out.add(in.retainedSlice(varintEnd + 1, reader.readVarint));
|
||||
in.skipBytes(minimumRead);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else if (reader.result == DecodeResult.TOO_BIG) {
|
||||
|
Reference in New Issue
Block a user