Files
bytes.kt/src/commonMain/kotlin/com/infendro/bytearray/ByteArray.kt
2025-12-12 21:20:44 +01:00

160 lines
3.2 KiB
Kotlin

package com.infendro.bytearray
import com.infendro.bytearray.ByteOrder.BIG_ENDIAN
import kotlin.experimental.and
import kotlin.experimental.or
import kotlin.experimental.xor
infix fun ByteArray.and(
that: ByteArray,
): ByteArray {
if (this.size != that.size)
throw IllegalArgumentException()
return ByteArray(size) { i ->
this[i] and that[i]
}
}
infix fun ByteArray.or(
that: ByteArray,
): ByteArray {
if (this.size != that.size)
throw IllegalArgumentException()
return ByteArray(size) { i ->
this[i] or that[i]
}
}
infix fun ByteArray.xor(
that: ByteArray,
): ByteArray {
if (this.size != that.size)
throw IllegalArgumentException()
return ByteArray(size) { i ->
this[i] xor that[i]
}
}
fun ByteArray.padStart(
length: Int,
padByte: Byte,
): ByteArray {
val bytes = mutableListOf<Byte>()
repeat(length - size) {
bytes += padByte
}
bytes += this.toList()
return bytes.toByteArray()
}
fun ByteArray.padEnd(
length: Int,
padByte: Byte,
): ByteArray {
val bytes = mutableListOf<Byte>()
bytes += this.toList()
repeat(length - size) {
bytes += padByte
}
return bytes.toByteArray()
}
fun ByteArray.toInt(
order: ByteOrder = BIG_ENDIAN,
): Int {
if (size != 4)
throw IllegalArgumentException()
return normalize(order)
.fold(0) { acc, byte ->
(acc shl 8) or (byte.toInt() and 0xFF)
}
}
fun ByteArray.toIntArray(
order: ByteOrder = BIG_ENDIAN,
): IntArray {
if (size % 4 != 0)
throw IllegalArgumentException()
return toList()
.chunked(4) { it.toByteArray() }
.map { it.toInt(order) }
.toIntArray()
}
fun ByteArray.toLong(
order: ByteOrder = BIG_ENDIAN,
): Long {
if (size != 8)
throw IllegalArgumentException()
return normalize(order)
.fold(0L) { acc, byte ->
(acc shl 8) or (byte.toLong() and 0xFFL)
}
}
fun ByteArray.toLongArray(
order: ByteOrder = BIG_ENDIAN,
): LongArray {
if (size % 8 != 0)
throw IllegalArgumentException()
return toList()
.chunked(8) { it.toByteArray() }
.map { it.toLong(order) }
.toLongArray()
}
fun ByteArray.toUInt(
order: ByteOrder = BIG_ENDIAN,
): UInt {
if (size != 4)
throw IllegalArgumentException()
return normalize(order)
.fold(0U) { acc, byte ->
(acc shl 8) or (byte.toUInt() and 0xFFU)
}
}
fun ByteArray.toUIntArray(
order: ByteOrder = BIG_ENDIAN,
): UIntArray {
if (size % 4 != 0)
throw IllegalArgumentException()
return toList()
.chunked(4) { it.toByteArray() }
.map { it.toUInt(order) }
.toUIntArray()
}
fun ByteArray.toULong(
order: ByteOrder = BIG_ENDIAN,
): ULong {
if (size != 8)
throw IllegalArgumentException()
return normalize(order)
.fold(0UL) { acc, byte ->
(acc shl 8) or (byte.toULong() and 0xFFUL)
}
}
fun ByteArray.toULongArray(
order: ByteOrder = BIG_ENDIAN,
): ULongArray {
if (size % 8 != 0)
throw IllegalArgumentException()
return toList()
.chunked(8) { it.toByteArray() }
.map { it.toULong(order) }
.toULongArray()
}