Any hints as to how to convert a Node `Buffer` to...
# javascript
d
Any hints as to how to convert a Node
Buffer
to a Kotlin
ByteArray
, and vice-versa ?
👀 1
t
Not sure 🤔 What if you convert the Buffer into a String, and then use Kotlin's toByteArray function?
d
Not sure whether that would be good if the Buffer contains binary data...
t
Maybe you can do something like
Copy code
val byteArray = listOf(*nodeBuffer).toByteArray()
d
@Tristan it doesn't type-check. :(
After a little research, it seems that
ByteArray
is backed by a JavaScript
Int8Array
and that
Buffer
extends from
UInt8Array
. So the following did the trick:
Copy code
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>()
}
💡 1