Skip to content

Commit

Permalink
Merge pull request #2862 from armanbilge/fix/chunk-js-interop
Browse files Browse the repository at this point in the history
`Chunk` <-> JS `Uint8Array` conversion should respect offset/length
  • Loading branch information
mpilquist authored Mar 29, 2022
2 parents 6993229 + d07eafa commit 652b021
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
4 changes: 3 additions & 1 deletion core/js/src/main/scala/fs2/ChunkRuntimePlatform.scala
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ trait ChunkCompanionRuntimePlatform { self: Chunk.type =>
byteBuffer(TypedArrayBuffer.wrap(buffer))

def uint8Array(array: Uint8Array): Chunk[Byte] =
jsArrayBuffer(array.buffer)
byteBuffer(
TypedArrayBuffer.wrap(array.buffer, array.byteOffset, array.byteLength)
)

}
16 changes: 16 additions & 0 deletions core/js/src/test/scala/fs2/ChunkRuntimePlatformSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ import org.scalacheck.Arbitrary
import org.scalacheck.Gen
import org.scalacheck.Prop.forAll

import scala.scalajs.js.typedarray.Int8Array
import scala.scalajs.js.typedarray.Uint8Array

class ChunkRuntimePlatformSuite extends Fs2Suite {
override def scalaCheckTestParameters =
super.scalaCheckTestParameters
Expand All @@ -50,6 +53,19 @@ class ChunkRuntimePlatformSuite extends Fs2Suite {
assertEquals(Chunk.uint8Array(c.toUint8Array), c)
}
}
property("Uint8Array conversion respects offset and length") {
forAll[(Chunk[Byte], Int, Int), Unit](for {
chunk <- genChunk
offset <- Gen.chooseNum(0, chunk.size)
length <- Gen.chooseNum(0, chunk.size - offset)
} yield (chunk, offset, length)) { case (chunk, offset, length) =>
val buffer = chunk.toJSArrayBuffer
assertEquals(
Chunk.uint8Array(new Uint8Array(buffer, offset, length)),
Chunk.array(new Int8Array(buffer, offset, length).toArray)
)
}
}
}

testByteChunk(byteBufferChunkGenerator, "ByteBuffer")
Expand Down

0 comments on commit 652b021

Please # to comment.