From a5097b937e8430eb4cdc8f64856520e8169cde54 Mon Sep 17 00:00:00 2001 From: Trustin Lee Date: Thu, 26 Jun 2014 18:53:50 +0900 Subject: [PATCH] Fix incorrect bytesBefore/indexOf() in ReplayingDecoderBuffer Motivation: bytesBefore(length, ...), bytesBefore(index, length, ...), and indexOf(fromIndex, toIndex,...) in ReplayingDecoderBuffer are buggy. They trigger 'REPLAY even when they don't need to. Modification: Implement the buggy methods properly so that REPLAYs are not triggered unnecessarily. Result: Correct behvaior --- .../handler/codec/ReplayingDecoderBuffer.java | 36 ++++++++++++------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/codec/src/main/java/io/netty/handler/codec/ReplayingDecoderBuffer.java b/codec/src/main/java/io/netty/handler/codec/ReplayingDecoderBuffer.java index 108608dea5..4fa55cdf19 100644 --- a/codec/src/main/java/io/netty/handler/codec/ReplayingDecoderBuffer.java +++ b/codec/src/main/java/io/netty/handler/codec/ReplayingDecoderBuffer.java @@ -307,11 +307,15 @@ final class ReplayingDecoderBuffer extends ByteBuf { @Override public int indexOf(int fromIndex, int toIndex, byte value) { - int endIndex = buffer.indexOf(fromIndex, toIndex, value); - if (endIndex < 0) { + if (fromIndex == toIndex) { + return -1; + } + + if (Math.max(fromIndex, toIndex) > buffer.writerIndex()) { throw REPLAY; } - return endIndex; + + return buffer.indexOf(fromIndex, toIndex, value); } @Override @@ -325,21 +329,27 @@ final class ReplayingDecoderBuffer extends ByteBuf { @Override public int bytesBefore(int length, byte value) { - checkReadableBytes(length); - int bytes = buffer.bytesBefore(length, value); - if (bytes < 0) { - throw REPLAY; - } - return bytes; + final int readerIndex = buffer.readerIndex(); + return bytesBefore(readerIndex, buffer.writerIndex() - readerIndex, value); } @Override public int bytesBefore(int index, int length, byte value) { - int bytes = buffer.bytesBefore(index, length, value); - if (bytes < 0) { + final int writerIndex = buffer.writerIndex(); + if (index >= writerIndex) { throw REPLAY; } - return bytes; + + if (index <= writerIndex - length) { + return buffer.bytesBefore(index, length, value); + } + + int res = buffer.bytesBefore(index, writerIndex - index, value); + if (res < 0) { + throw REPLAY; + } else { + return res; + } } @Override @@ -359,7 +369,7 @@ final class ReplayingDecoderBuffer extends ByteBuf { throw REPLAY; } - if (index + length <= writerIndex) { + if (index <= writerIndex - length) { return buffer.forEachByte(index, length, processor); }