Hi guys, is there any way to get a slice of a Byte...
# announcements
a
Hi guys, is there any way to get a slice of a ByteArray without copying the content in a new ByteArray? Say I have a ByteArray of 100 bytes and I just want a slice (without copying the original ByteArray) from 2 to 10 for example
a
if you have vertx as a dependency - you can use its Buffer#slice method
a
I don’t unfortunately, I saw there is a slice also on ByteArray but I suspect it’s gonna copy the items
z
asList().subList()
👍 1
d
One thing to be mindful with
asList().subList()
(and `List`s in general) is boxing. I'm not sure if both of those actually box the values since they just wrap the array, but if they do there will be both a performance hit and a significant memory hit (boxed bytes are 16 times larger in memory than primitive bytes). This of course only applies if you are memory/performance constrained and if those calls actually box the primitives.
👍 1
m
It would probably be better if we know the reason as to why you would want this. What you could always do is the following:
Copy code
typealias PartialByteArray = Pair<IntRange, ByteArray>
fun main() {
    val bytes = ByteArray(100)
    val slice: PartialByteArray = 2..10 to bytes
}
and then extend the PartialByteArray with your neccesary functions if need be like so:
Copy code
operator fun PartialByteArray.get(index: Int) = second[first.first + index]
operator fun PartialByteArray.set(index: Int, value: Byte) {
    second[first.first + index] = value
}
operator fun PartialByteArray.iterator() = first.map(second::get)
j
ByteBuffer.wrap(foo).limit(10).position(2).slice()
will emit the native code you are looking for though you don't get to use a new jvm array directly against the backing store.
https://github.com/jnorthrup/PrematureXorSwap benchmarks a half dozen relevant small byte accesses.