Didier Villevalois
08/16/2021, 3:56 PMBuffer
to a Kotlin ByteArray
, and vice-versa ?Tristan
08/16/2021, 5:00 PMDidier Villevalois
08/16/2021, 6:25 PMTristan
08/16/2021, 7:16 PMval byteArray = listOf(*nodeBuffer).toByteArray()
Didier Villevalois
08/16/2021, 9:00 PMDidier Villevalois
08/16/2021, 10:25 PMByteArray
is backed by a JavaScript Int8Array
and that Buffer
extends from UInt8Array
. So the following did the trick:
import Buffer
import org.khronos.webgl.Int8Array
import org.khronos.webgl.Uint8Array
fun ByteArray.toBuffer(): Buffer {
val int8Array: Int8Array = this.unsafeCast<Int8Array>()
return Uint8Array(
int8Array.buffer,
int8Array.byteOffset,
int8Array.byteLength
).unsafeCast<Buffer>()
}
fun Buffer.toByteArray(): ByteArray {
val uint8Array: Uint8Array = this.unsafeCast<Uint8Array>()
return Int8Array(
uint8Array.buffer,
uint8Array.byteOffset,
uint8Array.byteLength
).unsafeCast<ByteArray>()
}