diff --git a/.changes/next-release/bugfix-AWSSDKforJavav2-5ae7899.json b/.changes/next-release/bugfix-AWSSDKforJavav2-5ae7899.json new file mode 100644 index 000000000000..45f374c0377c --- /dev/null +++ b/.changes/next-release/bugfix-AWSSDKforJavav2-5ae7899.json @@ -0,0 +1,6 @@ +{ + "category": "AWS SDK for Java v2", + "contributor": "", + "type": "bugfix", + "description": "Fixed bug where limit was not copied over when cloning ByteBuffer using immutableCopyOf()" +} diff --git a/utils/src/main/java/software/amazon/awssdk/utils/BinaryUtils.java b/utils/src/main/java/software/amazon/awssdk/utils/BinaryUtils.java index 192ea7cead9b..e8d9271f3b65 100644 --- a/utils/src/main/java/software/amazon/awssdk/utils/BinaryUtils.java +++ b/utils/src/main/java/software/amazon/awssdk/utils/BinaryUtils.java @@ -133,12 +133,12 @@ public static ByteBuffer immutableCopyOf(ByteBuffer bb) { if (bb == null) { return null; } - int sourceBufferPosition = bb.position(); ByteBuffer readOnlyCopy = bb.asReadOnlyBuffer(); readOnlyCopy.rewind(); ByteBuffer cloned = ByteBuffer.allocate(readOnlyCopy.capacity()) .put(readOnlyCopy); - cloned.position(sourceBufferPosition); + cloned.position(bb.position()); + cloned.limit(bb.limit()); return cloned.asReadOnlyBuffer(); } diff --git a/utils/src/test/java/software/amazon/awssdk/utils/BinaryUtilsTest.java b/utils/src/test/java/software/amazon/awssdk/utils/BinaryUtilsTest.java index 4e416ea9e3b6..b1287e2990ec 100644 --- a/utils/src/test/java/software/amazon/awssdk/utils/BinaryUtilsTest.java +++ b/utils/src/test/java/software/amazon/awssdk/utils/BinaryUtilsTest.java @@ -226,6 +226,17 @@ public void testImmutableCopyOfByteBuffer() { assertArrayEquals(bytesInSourceAfterCopy, fromSource); } + @Test + public void immutableCopyOf_retainsOriginalLimit() { + ByteBuffer sourceBuffer = ByteBuffer.allocate(10); + byte[] bytes = {1, 2, 3, 4}; + sourceBuffer.put(bytes); + sourceBuffer.rewind(); + sourceBuffer.limit(bytes.length); + ByteBuffer copy = BinaryUtils.immutableCopyOf(sourceBuffer); + assertThat(copy.limit()).isEqualTo(sourceBuffer.limit()); + } + @Test public void testImmutableCopyOfByteBuffer_nullBuffer() { assertNull(BinaryUtils.immutableCopyOf(null));