kotlinx-io
kotlinx-io copied to clipboard
Add `ByteString` conversions for JVM `ByteBuffer`
In the same vibe as https://github.com/Kotlin/kotlinx-io/issues/266 and https://github.com/Kotlin/kotlinx-io/issues/268, it would be nice to have built-in conversions in kotlinx-io-bytestring
for the JVM ByteBuffer
type for a full multi-platform experience.
Examples:
/**
* Exposes the contents of this [ByteString] as a read-only [ByteBuffer] without copying data.
*/
fun ByteString.asReadOnlyByteBuffer(): ByteBuffer = ByteBuffer.wrap(getBackingArrayReference()).asReadOnlyBuffer()
/**
* Reads all remaining bytes in this [ByteBuffer] into a new [ByteString].
*/
fun ByteBuffer.readByteString(): ByteString = ByteString.wrap(readByteArray())
/**
* Reads all remaining bytes in this [ByteBuffer] into a new [ByteArray].
*/
// private because that's not really the role of kotlinx-io-bytestring, more of the stdlib
private fun ByteBuffer.readByteArray(): ByteArray {
val array = ByteArray(remaining())
get(array)
return array
}
Arguably the last one could be a stdlib function instead.
Note: this might slightly overlap with https://github.com/Kotlin/kotlinx-io/issues/239, but I still believe it's a different use case, and much easier to add. This is less about using ByteBuffer
internally, nor about being able to wrap those directly as backing storage, but more about being able to interop with it conveniently.