Open
Description
In the same vibe as #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