switch to signed-first approach
All checks were successful
/ test (pull_request) Successful in 2m47s
All checks were successful
/ test (pull_request) Successful in 2m47s
It turns out signed math is more performant
This commit is contained in:
57
src/commonMain/kotlin/com/infendro/bytes/longarray/Copy.kt
Normal file
57
src/commonMain/kotlin/com/infendro/bytes/longarray/Copy.kt
Normal file
@@ -0,0 +1,57 @@
|
||||
package com.infendro.bytes.longarray
|
||||
|
||||
import com.infendro.bytes.ByteOrder
|
||||
import com.infendro.bytes.ByteOrder.BIG_ENDIAN
|
||||
import com.infendro.bytes.ByteOrder.LITTLE_ENDIAN
|
||||
|
||||
fun LongArray.copyInto(
|
||||
destination: ByteArray,
|
||||
destinationOffset: Int = 0,
|
||||
startIndex: Int = 0,
|
||||
endIndex: Int = size,
|
||||
order: ByteOrder = BIG_ENDIAN,
|
||||
) {
|
||||
val length = endIndex - startIndex
|
||||
require(length >= 0)
|
||||
require(startIndex in 0..(size - length))
|
||||
require(destinationOffset in 0..(destination.size - (length * 8)))
|
||||
|
||||
when (order) {
|
||||
BIG_ENDIAN -> {
|
||||
repeat(length) { i ->
|
||||
val offset = destinationOffset + (i * 8)
|
||||
val value = this[startIndex + i]
|
||||
destination[offset] = (value shr 56).toByte()
|
||||
destination[offset + 1] = (value shr 48).toByte()
|
||||
destination[offset + 2] = (value shr 40).toByte()
|
||||
destination[offset + 3] = (value shr 32).toByte()
|
||||
destination[offset + 4] = (value shr 24).toByte()
|
||||
destination[offset + 5] = (value shr 16).toByte()
|
||||
destination[offset + 6] = (value shr 8).toByte()
|
||||
destination[offset + 7] = value.toByte()
|
||||
}
|
||||
}
|
||||
LITTLE_ENDIAN -> {
|
||||
repeat(length) { i ->
|
||||
val offset = destinationOffset + (i * 8)
|
||||
val value = this[startIndex + i]
|
||||
destination[offset] = value.toByte()
|
||||
destination[offset + 1] = (value shr 8).toByte()
|
||||
destination[offset + 2] = (value shr 16).toByte()
|
||||
destination[offset + 3] = (value shr 24).toByte()
|
||||
destination[offset + 4] = (value shr 32).toByte()
|
||||
destination[offset + 5] = (value shr 40).toByte()
|
||||
destination[offset + 6] = (value shr 48).toByte()
|
||||
destination[offset + 7] = (value shr 56).toByte()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun LongArray.copyInto(
|
||||
destination: UByteArray,
|
||||
destinationOffset: Int = 0,
|
||||
startIndex: Int = 0,
|
||||
endIndex: Int = size,
|
||||
order: ByteOrder = BIG_ENDIAN,
|
||||
) = copyInto(destination.asByteArray(), destinationOffset, startIndex, endIndex, order)
|
||||
Reference in New Issue
Block a user