Files
bytes.kt/src/commonMain/kotlin/com/infendro/bytes/bytearray/Operators.kt
Infendro ff0e17b5ad
All checks were successful
/ test (pull_request) Successful in 2m47s
switch to signed-first approach
It turns out signed math is more performant
2026-01-15 14:10:14 +01:00

91 lines
2.6 KiB
Kotlin

package com.infendro.bytes.bytearray
import kotlin.experimental.and
import kotlin.experimental.inv
import kotlin.experimental.or
import kotlin.experimental.xor
fun ByteArray.invInto(
destination: ByteArray,
destinationOffset: Int = 0,
startIndex: Int = 0,
endIndex: Int = size,
) {
val length = endIndex - startIndex
require(length >= 0)
require(startIndex in 0..(size - length))
require(destinationOffset in 0..(destination.size - length))
repeat(length) { i ->
destination[destinationOffset + i] = this[startIndex + i].inv()
}
}
fun ByteArray.inv() =
ByteArray(size).also { invInto(it) }
private inline fun ByteArray.combineInto(
that: ByteArray,
destination: ByteArray,
destinationOffset: Int = 0,
startIndex: Int = 0,
endIndex: Int = size,
thatStartIndex: Int = 0,
combine: (Byte, Byte) -> Byte,
) {
val length = endIndex - startIndex
require(length >= 0)
require(startIndex in 0..(size - length))
require(thatStartIndex in 0..(that.size - length))
require(destinationOffset in 0..(destination.size - length))
repeat(length) { i ->
destination[destinationOffset + i] = combine(this[startIndex + i], that[thatStartIndex + i])
}
}
private inline fun ByteArray.combine(
that: ByteArray,
combine: (Byte, Byte) -> Byte,
): ByteArray {
require(this.size == that.size)
return ByteArray(size).also { combineInto(that, it, combine = combine) }
}
fun ByteArray.andInto(
that: ByteArray,
destination: ByteArray,
destinationOffset: Int = 0,
startIndex: Int = 0,
endIndex: Int = size,
thatStartIndex: Int = 0,
) = combineInto(that, destination, destinationOffset, startIndex, endIndex, thatStartIndex) { a, b -> a and b }
infix fun ByteArray.and(that: ByteArray) =
combine(that) { a, b -> a and b }
fun ByteArray.orInto(
that: ByteArray,
destination: ByteArray,
destinationOffset: Int = 0,
startIndex: Int = 0,
endIndex: Int = size,
thatStartIndex: Int = 0,
) = combineInto(that, destination, destinationOffset, startIndex, endIndex, thatStartIndex) { a, b -> a or b }
infix fun ByteArray.or(that: ByteArray) =
combine(that) { a, b -> a or b }
fun ByteArray.xorInto(
that: ByteArray,
destination: ByteArray,
destinationOffset: Int = 0,
startIndex: Int = 0,
endIndex: Int = size,
thatStartIndex: Int = 0,
) = combineInto(that, destination, destinationOffset, startIndex, endIndex, thatStartIndex) { a, b -> a xor b }
infix fun ByteArray.xor(that: ByteArray) =
combine(that) { a, b -> a xor b }