Skip to content

Commit

Permalink
Makes EmptyByteBuf#hashCode and AbstractByteBuf#hashCode consiste…
Browse files Browse the repository at this point in the history
…nt (netty#7870)

Motivation:
The `AbstractByteBuf#equals` method doesn't take into account the
class of buffer instance. So the two buffers with different classes
must have the same `hashCode` values if `equals` method returns `true`.
But `EmptyByteBuf#hashCode` is not consistent with `#hashCode`
of the empty `AbstractByteBuf`, that is violates the contract and
can lead to errors.

Modifications:
Return `1` in `EmptyByteBuf#hashCode`.

Result:
Consistent behavior of `EmptyByteBuf#hashCode` and `AbstractByteBuf#hashCode`.
  • Loading branch information
fenik17 authored and normanmaurer committed Apr 16, 2018
1 parent f874a37 commit 81a7d14
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
2 changes: 1 addition & 1 deletion buffer/src/main/java/io/netty/buffer/ByteBufUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ public static int hashCode(ByteBuf buffer) {
final int intCount = aLen >>> 2;
final int byteCount = aLen & 3;

int hashCode = 1;
int hashCode = EmptyByteBuf.EMPTY_BYTE_BUF_HASH_CODE;
int arrayIndex = buffer.readerIndex();
if (buffer.order() == ByteOrder.BIG_ENDIAN) {
for (int i = intCount; i > 0; i --) {
Expand Down
3 changes: 2 additions & 1 deletion buffer/src/main/java/io/netty/buffer/EmptyByteBuf.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
*/
public final class EmptyByteBuf extends ByteBuf {

static final int EMPTY_BYTE_BUF_HASH_CODE = 1;
private static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.allocateDirect(0);
private static final long EMPTY_BYTE_BUFFER_ADDRESS;

Expand Down Expand Up @@ -976,7 +977,7 @@ public String toString(int index, int length, Charset charset) {

@Override
public int hashCode() {
return 0;
return EMPTY_BYTE_BUF_HASH_CODE;
}

@Override
Expand Down
11 changes: 11 additions & 0 deletions buffer/src/test/java/io/netty/buffer/EmptyByteBufTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,15 @@ public void testMemoryAddress() {
}
}
}

@Test
public void consistentEqualsAndHashCodeWithAbstractBytebuf() {
ByteBuf empty = new EmptyByteBuf(UnpooledByteBufAllocator.DEFAULT);
ByteBuf emptyAbstract = new UnpooledHeapByteBuf(UnpooledByteBufAllocator.DEFAULT, 0, 0);
assertEquals(emptyAbstract, empty);
assertEquals(emptyAbstract.hashCode(), empty.hashCode());
assertEquals(EmptyByteBuf.EMPTY_BYTE_BUF_HASH_CODE, empty.hashCode());
assertTrue(emptyAbstract.release());
assertFalse(empty.release());
}
}

0 comments on commit 81a7d14

Please sign in to comment.