From c727c16707f6a7315f043fdb7800be85d527b623 Mon Sep 17 00:00:00 2001 From: Alwayswithme Date: Thu, 7 May 2015 10:36:49 +0800 Subject: [PATCH] ByteBufUtil use IndexOfProcessor to find occurrence. Motivation: The way of firstIndexOf and lastIndexOf iterating the ByteBuf is similar to forEachByte and forEachByteDesc, but have many range checks. Modifications: Use forEachByte and a IndexOfProcessor to find occurrence. Result: eliminate range checks --- .../java/io/netty/buffer/ByteBufUtil.java | 29 ++++++++++--------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java b/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java index bb05b58a4d..bf601a023b 100644 --- a/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java +++ b/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java @@ -312,13 +312,7 @@ public final class ByteBufUtil { return -1; } - for (int i = fromIndex; i < toIndex; i ++) { - if (buffer.getByte(i) == value) { - return i; - } - } - - return -1; + return buffer.forEachByte(fromIndex, toIndex - fromIndex, new IndexOfProcessor(value)); } private static int lastIndexOf(ByteBuf buffer, int fromIndex, int toIndex, byte value) { @@ -327,13 +321,7 @@ public final class ByteBufUtil { return -1; } - for (int i = fromIndex - 1; i >= toIndex; i --) { - if (buffer.getByte(i) == value) { - return i; - } - } - - return -1; + return buffer.forEachByteDesc(toIndex, fromIndex - toIndex, new IndexOfProcessor(value)); } /** @@ -566,5 +554,18 @@ public final class ByteBufUtil { } } + private static class IndexOfProcessor implements ByteBufProcessor { + private final byte byteToFind; + + public IndexOfProcessor(byte byteToFind) { + this.byteToFind = byteToFind; + } + + @Override + public boolean process(byte value) { + return value != byteToFind; + } + } + private ByteBufUtil() { } }