From bd2793b5b4768227187fdbf3c31cbd9a5b668964 Mon Sep 17 00:00:00 2001 From: soywiz Date: Thu, 25 Jul 2024 08:08:35 +0200 Subject: [PATCH] Fixes native --- .../src/korlibs/memory/_Memory_Internal.kt | 24 +++++++++++++++++++ .../korlibs/memory/Buffer.native.kt | 1 + 2 files changed, 25 insertions(+) diff --git a/korlibs-memory/src/korlibs/memory/_Memory_Internal.kt b/korlibs-memory/src/korlibs/memory/_Memory_Internal.kt index 80dca5d..537b2f9 100644 --- a/korlibs-memory/src/korlibs/memory/_Memory_Internal.kt +++ b/korlibs-memory/src/korlibs/memory/_Memory_Internal.kt @@ -21,3 +21,27 @@ internal fun Int.extractByte(offset: Int): Byte = (this ushr offset).toByte() /** Takes n[bits] of [this] [Int], and extends the last bit, creating a plain [Int] in one's complement */ internal fun Int.signExtend(bits: Int): Int = (this shl (32 - bits)) shr (32 - bits) // Int.SIZE_BITS + +/** Reverses the bytes of [this] [Short]: AABB -> BBAA */ +internal fun Short.reverseBytes(): Short { + val low = ((this.toInt() ushr 0) and 0xFF) + val high = ((this.toInt() ushr 8) and 0xFF) + return ((high and 0xFF) or (low shl 8)).toShort() +} + +/** Reverses the bytes of [this] [Int]: AABBCCDD -> DDCCBBAA */ +internal fun Int.reverseBytes(): Int { + val v0 = ((this ushr 0) and 0xFF) + val v1 = ((this ushr 8) and 0xFF) + val v2 = ((this ushr 16) and 0xFF) + val v3 = ((this ushr 24) and 0xFF) + return (v0 shl 24) or (v1 shl 16) or (v2 shl 8) or (v3 shl 0) +} + +/** Reverses the bytes of [this] [Long]: AABBCCDDEEFFGGHH -> HHGGFFEEDDCCBBAA */ +internal fun Long.reverseBytes(): Long { + val v0 = (this ushr 0).toInt().reverseBytes().toLong() and 0xFFFFFFFFL + val v1 = (this ushr 32).toInt().reverseBytes().toLong() and 0xFFFFFFFFL + return (v0 shl 32) or (v1 shl 0) +} + diff --git a/korlibs-memory/src@native/korlibs/memory/Buffer.native.kt b/korlibs-memory/src@native/korlibs/memory/Buffer.native.kt index 08a0e91..9ddb3b9 100644 --- a/korlibs-memory/src@native/korlibs/memory/Buffer.native.kt +++ b/korlibs-memory/src@native/korlibs/memory/Buffer.native.kt @@ -2,6 +2,7 @@ package korlibs.memory +import korlibs.memory.internal.* import kotlinx.cinterop.* import platform.posix.* import kotlin.experimental.*