Skip to content

Commit 59ff99b

Browse files
committed
Duplicate buffer in asByteBufferUnsafe
1 parent 0b7a1af commit 59ff99b

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

core/shared/src/main/scala/scodec/bits/ByteVector.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1464,7 +1464,7 @@ object ByteVector extends ByteVectorCompanionCrossPlatform {
14641464
asByteBufferUnsafe(offset, size).asReadOnlyBuffer()
14651465

14661466
override def asByteBufferUnsafe(offset: Long, size: Int): ByteBuffer = {
1467-
val b = buf
1467+
val b = buf.duplicate()
14681468
if (offset == 0 && b.position() == 0 && size == b.remaining()) b
14691469
else {
14701470
b.position(offset.toInt)

core/shared/src/test/scala/scodec/bits/ByteVectorTest.scala

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -487,6 +487,18 @@ class ByteVectorTest extends BitsSuite {
487487
assert(arr eq ByteVector.view(ByteBuffer.wrap(arr)).drop(1).toByteBufferUnsafe.array)
488488
}
489489

490+
test("toByteBufferUnsafe has independent position+limit") {
491+
val bv = ByteVector.view(ByteBuffer.wrap("Hello, world!".getBytes))
492+
val bb1 = bv.toByteBufferUnsafe
493+
assertEquals(bb1.position(), 0)
494+
assertEquals(bb1.limit(), 13)
495+
val bb2 = bv.toByteBufferUnsafe
496+
bb2.position(1)
497+
bb2.limit(2)
498+
assertEquals(bb1.position(), 0)
499+
assertEquals(bb1.limit(), 13)
500+
}
501+
490502
property("dropping from a view is consistent with dropping from a strict vector") {
491503
forAll { (b: ByteVector, n0: Long) =>
492504
val view = ByteVector.view(b.toArray)

0 commit comments

Comments
 (0)