Skip to content

Add ByteString conversions for JVM ByteBuffer #269

Closed
@joffrey-bion

Description

@joffrey-bion

In the same vibe as #266 and #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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DesignenhancementintegrationAn issue related to the integration with other libraries or platform-specific APIs

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions