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

Add Buffer.copyTo(ByteArray) extension

Open fzhinkin opened this issue 2 years ago • 2 comments
trafficstars

Sometimes, data from a Buffer need to be partially copied into a byte array without consuming it from the buffer. The only way it could be achieved now is by creating a peek source and consuming data from it. Such an approach is far from being efficient. I'm proposing to add a Buffer.copyTo(dest: ByteArray, startIndex = 0, endIndex = dest.size) extension that will behave the same way other existing Buffer.copyTo methods currently do.

fzhinkin avatar Jul 28 '23 09:07 fzhinkin

Hey @fzhinkin, currently what's the most performant way to copy (or write) a Buffer to a byte array?
I'm using readByteArray(count) currenty, is that the way to do it?

Same for transforming a byte array into a Buffer. Currently it seems the only way is

val buffer = Buffer()
buffer.write(byteArray)

Is this the way to do it?
It feels like a Buffer could be initialized with a byte array directly, as a constructor argument.

lppedd avatar Sep 14 '23 12:09 lppedd

@lppedd what you mentioned is the way to read/write byte array from/to Buffer.

Note that readByteArray(count) doesn't copy the buffer, it consumes the buffer (so it's a read, not a copy operation). At the moment, a buffer could be copied into a byte array by using a peek buffer: buffer.peek().readByteArray(), this issue is about providing a better alternative to using peek.

It feels like a Buffer could be initialized with a byte array directly, as a constructor argument.

There's an issue suggesting providing an API to wrap arrays in Buffers (https://github.com/Kotlin/kotlinx-io/issues/166), I'll take a look at what could be done there in the context of https://github.com/Kotlin/kotlinx-io/issues/135.

fzhinkin avatar Sep 14 '23 13:09 fzhinkin