kotlinx-io
kotlinx-io copied to clipboard
Add Buffer.copyTo(ByteArray) extension
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.
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 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.