91 lines
2.6 KiB
Kotlin
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
|
|
|
|
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.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 =
|
|
ByteArray(size).also { invInto(it) }
|
|
|
|
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): 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): 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): ByteArray =
|
|
combine(that) { a, b -> a xor b }
|