Skip to content

Commit

Permalink
Fix immutableCopyOf bug (#4266)
Browse files Browse the repository at this point in the history
* Set limit when cloning ByteBuffer

* Add changelog
  • Loading branch information
davidh44 committed Aug 9, 2023
1 parent 0fc8eff commit 87b1738
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
6 changes: 6 additions & 0 deletions .changes/next-release/bugfix-AWSSDKforJavav2-5ae7899.json
Original file line number Diff line number Diff line change
@@ -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()"
}
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down

0 comments on commit 87b1738

Please sign in to comment.