Skip to content

Commit dd2c2bb

Browse files
authored
Use Two-Way for finding the delimiter in DelimiterBasedFrameDecoder (#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
1 parent 26a7df3 commit dd2c2bb

File tree

1 file changed

+5
-20
lines changed

1 file changed

+5
-20
lines changed

codec/src/main/java/io/netty/handler/codec/DelimiterBasedFrameDecoder.java

+5-20
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import static io.netty.util.internal.ObjectUtil.checkPositive;
1919

2020
import io.netty.buffer.ByteBuf;
21+
import io.netty.buffer.ByteBufUtil;
2122
import io.netty.channel.ChannelHandlerContext;
2223
import io.netty.util.internal.ObjectUtil;
2324

@@ -311,27 +312,11 @@ private void fail(long frameLength) {
311312
* found in the haystack.
312313
*/
313314
private static int indexOf(ByteBuf haystack, ByteBuf needle) {
314-
for (int i = haystack.readerIndex(); i < haystack.writerIndex(); i ++) {
315-
int haystackIndex = i;
316-
int needleIndex;
317-
for (needleIndex = 0; needleIndex < needle.capacity(); needleIndex ++) {
318-
if (haystack.getByte(haystackIndex) != needle.getByte(needleIndex)) {
319-
break;
320-
} else {
321-
haystackIndex ++;
322-
if (haystackIndex == haystack.writerIndex() &&
323-
needleIndex != needle.capacity() - 1) {
324-
return -1;
325-
}
326-
}
327-
}
328-
329-
if (needleIndex == needle.capacity()) {
330-
// Found the needle from the haystack!
331-
return i - haystack.readerIndex();
332-
}
315+
int index = ByteBufUtil.indexOf(needle, haystack);
316+
if (index == -1) {
317+
return -1;
333318
}
334-
return -1;
319+
return index - haystack.readerIndex();
335320
}
336321

337322
private static void validateDelimiter(ByteBuf delimiter) {

0 commit comments

Comments
 (0)