Skip to content

Commit 87b1738

Browse files
authored
Fix immutableCopyOf bug (#4266)
* Set limit when cloning ByteBuffer * Add changelog
1 parent 0fc8eff commit 87b1738

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"category": "AWS SDK for Java v2",
3+
"contributor": "",
4+
"type": "bugfix",
5+
"description": "Fixed bug where limit was not copied over when cloning ByteBuffer using immutableCopyOf()"
6+
}

utils/src/main/java/software/amazon/awssdk/utils/BinaryUtils.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -133,12 +133,12 @@ public static ByteBuffer immutableCopyOf(ByteBuffer bb) {
133133
if (bb == null) {
134134
return null;
135135
}
136-
int sourceBufferPosition = bb.position();
137136
ByteBuffer readOnlyCopy = bb.asReadOnlyBuffer();
138137
readOnlyCopy.rewind();
139138
ByteBuffer cloned = ByteBuffer.allocate(readOnlyCopy.capacity())
140139
.put(readOnlyCopy);
141-
cloned.position(sourceBufferPosition);
140+
cloned.position(bb.position());
141+
cloned.limit(bb.limit());
142142
return cloned.asReadOnlyBuffer();
143143
}
144144

utils/src/test/java/software/amazon/awssdk/utils/BinaryUtilsTest.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,17 @@ public void testImmutableCopyOfByteBuffer() {
226226
assertArrayEquals(bytesInSourceAfterCopy, fromSource);
227227
}
228228

229+
@Test
230+
public void immutableCopyOf_retainsOriginalLimit() {
231+
ByteBuffer sourceBuffer = ByteBuffer.allocate(10);
232+
byte[] bytes = {1, 2, 3, 4};
233+
sourceBuffer.put(bytes);
234+
sourceBuffer.rewind();
235+
sourceBuffer.limit(bytes.length);
236+
ByteBuffer copy = BinaryUtils.immutableCopyOf(sourceBuffer);
237+
assertThat(copy.limit()).isEqualTo(sourceBuffer.limit());
238+
}
239+
229240
@Test
230241
public void testImmutableCopyOfByteBuffer_nullBuffer() {
231242
assertNull(BinaryUtils.immutableCopyOf(null));

0 commit comments

Comments
 (0)