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 }