From c5256195d6f888d6f6081b68e9453f17a5ed2c0b Mon Sep 17 00:00:00 2001 From: Thach Le Date: Mon, 1 Jul 2024 23:16:54 +0700 Subject: [PATCH 1/2] Handle NPE --- src/main/java/io/lettuce/core/codec/ByteArrayCodec.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/io/lettuce/core/codec/ByteArrayCodec.java b/src/main/java/io/lettuce/core/codec/ByteArrayCodec.java index c8a9cffd06..bcecd3d283 100644 --- a/src/main/java/io/lettuce/core/codec/ByteArrayCodec.java +++ b/src/main/java/io/lettuce/core/codec/ByteArrayCodec.java @@ -90,9 +90,11 @@ public ByteBuffer encodeValue(byte[] value) { } private static byte[] getBytes(ByteBuffer buffer) { + if (buffer == null) { + return EMPTY; + } int remaining = buffer.remaining(); - if (remaining == 0) { return EMPTY; } From 035b5a4e75a7b5f3824692f018e3047214e6b238 Mon Sep 17 00:00:00 2001 From: Thach Le Date: Tue, 2 Jul 2024 21:51:40 +0700 Subject: [PATCH 2/2] Add Unit Test --- .../core/codec/ByteArrayCodecUnitTests.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/test/java/io/lettuce/core/codec/ByteArrayCodecUnitTests.java diff --git a/src/test/java/io/lettuce/core/codec/ByteArrayCodecUnitTests.java b/src/test/java/io/lettuce/core/codec/ByteArrayCodecUnitTests.java new file mode 100644 index 0000000000..c8f2394dac --- /dev/null +++ b/src/test/java/io/lettuce/core/codec/ByteArrayCodecUnitTests.java @@ -0,0 +1,35 @@ +package io.lettuce.core.codec; + +import org.junit.jupiter.api.Test; + +import java.nio.ByteBuffer; + +import static org.assertj.core.api.Assertions.assertThat; + +class ByteArrayCodecUnitTests { + + @Test + void testDecodeValue_withNonEmptyByteBuffer() { + final ByteArrayCodec byteArrayCodec = ByteArrayCodec.INSTANCE; + final byte[] expectedBytes = { 1, 2, 3, 4, 5 }; + final ByteBuffer buffer = ByteBuffer.wrap(expectedBytes); + final byte[] result = byteArrayCodec.decodeValue(buffer); + assertThat(result).isEqualTo(expectedBytes); + } + + @Test + void testDecodeValue_withEmptyByteBuffer() { + final ByteArrayCodec byteArrayCodec = ByteArrayCodec.INSTANCE; + final ByteBuffer buffer = ByteBuffer.allocate(0); + final byte[] result = byteArrayCodec.decodeValue(buffer); + assertThat(result).isEmpty(); + } + + @Test + void testDecodeValue_withNullByteBuffer() { + final ByteArrayCodec byteArrayCodec = ByteArrayCodec.INSTANCE; + final byte[] result = byteArrayCodec.decodeValue(null); + assertThat(result).isEmpty(); + } + +}