Skip to content

Commit

Permalink
chore: Do not duplicate byte buffer if it has no capacity.
Browse files Browse the repository at this point in the history
  • Loading branch information
nstdio committed Dec 11, 2022
1 parent 2b245da commit 913b611
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/main/java/io/github/nstdio/http/ext/Buffers.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ private Buffers() {
}

static ByteBuffer duplicate(ByteBuffer buf) {
if (buf.capacity() == 0) {
return buf;
}

var dup = buf.asReadOnlyBuffer();
return dup.hasRemaining() ? dup : dup.flip();
}
Expand Down
13 changes: 13 additions & 0 deletions src/test/kotlin/io/github/nstdio/http/ext/BuffersTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package io.github.nstdio.http.ext

import io.kotest.matchers.types.shouldBeSameInstanceAs
import io.kotest.property.Arb
import io.kotest.property.arbitrary.int
import io.kotest.property.arbitrary.map
Expand Down Expand Up @@ -54,6 +55,18 @@ internal class BuffersTest {
assertThat(actual.position()).isZero
}

@Test
fun shouldNotCreateNewBufferIfInputIsEmpty() {
//given
val buffer = ByteBuffer.allocate(0)

//when
val actual = Buffers.duplicate(buffer)

//then
actual.shouldBeSameInstanceAs(buffer)
}

companion object {
@JvmStatic
fun listBuffersData(): Stream<List<ByteBuffer>> {
Expand Down

0 comments on commit 913b611

Please sign in to comment.