kotlinx-io icon indicating copy to clipboard operation
kotlinx-io copied to clipboard

Add `ByteString` conversions for JS binary types like `ArrayBuffer`, `Int8Array`, `Blob`, etc.

Open joffrey-bion opened this issue 1 year ago • 3 comments
trafficstars

In the same vibe as https://github.com/Kotlin/kotlinx-io/issues/266, we could add conversions from JS binary types like ArrayBuffer, Blob, Int8Array...

Dealing with binary data in JS is a bit annoying. For example, the ArrayBuffer type is not directly usable and needs to be wrapped in a view. Providing such conversions out of the box in the kotlinx-io-bytestring artifact would be useful for a true multiplatform experience.

Examples:

/**
 * Creates a new [ArrayBuffer] containing the data copied from this [ByteString].
 */
fun ByteString.toArrayBuffer(): ArrayBuffer = toInt8Array().buffer

/**
 * Creates a new [Int8Array] containing the data copied from this [ByteString].
 */
fun ByteString.toInt8Array() = Int8Array(toArrayOfBytes())

private fun ByteString.toArrayOfBytes() = Array(size) { this[it] }

/**
 * Creates a new [ByteString] containing the data copied from this [ArrayBuffer].
 */
fun ArrayBuffer.toByteString(): ByteString = ByteString.wrap(toByteArray())

/**
 * Creates a new [ByteArray] containing the data copied from this [ArrayBuffer].
 */
fun ArrayBuffer.toByteArray(): ByteArray = Int8Array(this).toByteArray()

/**
 * Creates a new [ByteArray] containing the data copied from this [Int8Array].
 */
fun Int8Array.toByteArray() = ByteArray(length) { this[it] } // maybe there is more efficient here

joffrey-bion avatar Feb 26 '24 11:02 joffrey-bion