79 lines
2.7 KiB
Kotlin
79 lines
2.7 KiB
Kotlin
package com.infendro.bytes.uint
|
|
|
|
import com.infendro.bytes.ByteOrder
|
|
import com.infendro.bytes.ByteOrder.BIG_ENDIAN
|
|
import com.infendro.bytes.ByteOrder.LITTLE_ENDIAN
|
|
|
|
fun UInt.copyInto(
|
|
destination: UByteArray,
|
|
destinationOffset: Int = 0,
|
|
order: ByteOrder = BIG_ENDIAN,
|
|
) {
|
|
require(destinationOffset in 0..(destination.size - 4))
|
|
|
|
when (order) {
|
|
BIG_ENDIAN -> {
|
|
destination[destinationOffset] = (this shr 24).toUByte()
|
|
destination[destinationOffset + 1] = (this shr 16).toUByte()
|
|
destination[destinationOffset + 2] = (this shr 8).toUByte()
|
|
destination[destinationOffset + 3] = this.toUByte()
|
|
}
|
|
LITTLE_ENDIAN -> {
|
|
destination[destinationOffset] = this.toUByte()
|
|
destination[destinationOffset + 1] = (this shr 8).toUByte()
|
|
destination[destinationOffset + 2] = (this shr 16).toUByte()
|
|
destination[destinationOffset + 3] = (this shr 24).toUByte()
|
|
}
|
|
}
|
|
}
|
|
|
|
fun UInt.copyInto(
|
|
destination: ByteArray,
|
|
destinationOffset: Int = 0,
|
|
order: ByteOrder = BIG_ENDIAN,
|
|
) = copyInto(destination.asUByteArray(), destinationOffset, order)
|
|
|
|
fun UIntArray.copyInto(
|
|
destination: UByteArray,
|
|
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 * 4)))
|
|
|
|
when (order) {
|
|
BIG_ENDIAN -> {
|
|
repeat(length) { i ->
|
|
val offset = destinationOffset + (i * 4)
|
|
val value = this[startIndex + i]
|
|
destination[offset] = (value shr 24).toUByte()
|
|
destination[offset + 1] = (value shr 16).toUByte()
|
|
destination[offset + 2] = (value shr 8).toUByte()
|
|
destination[offset + 3] = value.toUByte()
|
|
}
|
|
}
|
|
LITTLE_ENDIAN -> {
|
|
repeat(length) { i ->
|
|
val offset = destinationOffset + (i * 4)
|
|
val value = this[startIndex + i]
|
|
destination[offset] = value.toUByte()
|
|
destination[offset + 1] = (value shr 8).toUByte()
|
|
destination[offset + 2] = (value shr 16).toUByte()
|
|
destination[offset + 3] = (value shr 24).toUByte()
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fun UIntArray.copyInto(
|
|
destination: ByteArray,
|
|
destinationOffset: Int = 0,
|
|
startIndex: Int = 0,
|
|
endIndex: Int = size,
|
|
order: ByteOrder = BIG_ENDIAN,
|
|
) = copyInto(destination.asUByteArray(), destinationOffset, startIndex, endIndex, order)
|