Skip to content

Commit

Permalink
Use Two-Way for finding the delimiter in DelimiterBasedFrameDecoder (#…
Browse files Browse the repository at this point in the history
…13451)

Motivation:
We were using the naive and inefficient O(nm) algorithm here.

Modification:
Remove the naive algorithm and instead call out to the optimised Two-Way
search we already have in ByteBufUtil.

Result:
The DelimiterBasedFrameDecoder now searches for delimiters using the
fastest algorithm available to us.

Fixes #13313
  • Loading branch information
chrisvest authored Jun 16, 2023
1 parent 26a7df3 commit dd2c2bb
Showing 1 changed file with 5 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import static io.netty.util.internal.ObjectUtil.checkPositive;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.internal.ObjectUtil;

Expand Down Expand Up @@ -311,27 +312,11 @@ private void fail(long frameLength) {
* found in the haystack.
*/
private static int indexOf(ByteBuf haystack, ByteBuf needle) {
for (int i = haystack.readerIndex(); i < haystack.writerIndex(); i ++) {
int haystackIndex = i;
int needleIndex;
for (needleIndex = 0; needleIndex < needle.capacity(); needleIndex ++) {
if (haystack.getByte(haystackIndex) != needle.getByte(needleIndex)) {
break;
} else {
haystackIndex ++;
if (haystackIndex == haystack.writerIndex() &&
needleIndex != needle.capacity() - 1) {
return -1;
}
}
}

if (needleIndex == needle.capacity()) {
// Found the needle from the haystack!
return i - haystack.readerIndex();
}
int index = ByteBufUtil.indexOf(needle, haystack);
if (index == -1) {
return -1;
}
return -1;
return index - haystack.readerIndex();
}

private static void validateDelimiter(ByteBuf delimiter) {
Expand Down

0 comments on commit dd2c2bb

Please sign in to comment.