summaryrefslogtreecommitdiff
path: root/formats/json-tests/commonTest/src/kotlinx/serialization/test/InternalHexConverter.kt
diff options
context:
space:
mode:
Diffstat (limited to 'formats/json-tests/commonTest/src/kotlinx/serialization/test/InternalHexConverter.kt')
-rw-r--r--formats/json-tests/commonTest/src/kotlinx/serialization/test/InternalHexConverter.kt51
1 files changed, 51 insertions, 0 deletions
diff --git a/formats/json-tests/commonTest/src/kotlinx/serialization/test/InternalHexConverter.kt b/formats/json-tests/commonTest/src/kotlinx/serialization/test/InternalHexConverter.kt
new file mode 100644
index 00000000..349eb43c
--- /dev/null
+++ b/formats/json-tests/commonTest/src/kotlinx/serialization/test/InternalHexConverter.kt
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
+ */
+
+package kotlinx.serialization.test
+
+object InternalHexConverter {
+ private const val hexCode = "0123456789ABCDEF"
+
+ fun parseHexBinary(s: String): ByteArray {
+ val len = s.length
+ require(len % 2 == 0) { "HexBinary string must be even length" }
+ val bytes = ByteArray(len / 2)
+ var i = 0
+
+ while (i < len) {
+ val h = hexToInt(s[i])
+ val l = hexToInt(s[i + 1])
+ require(!(h == -1 || l == -1)) { "Invalid hex chars: ${s[i]}${s[i+1]}" }
+
+ bytes[i / 2] = ((h shl 4) + l).toByte()
+ i += 2
+ }
+
+ return bytes
+ }
+
+ private fun hexToInt(ch: Char): Int = when (ch) {
+ in '0'..'9' -> ch - '0'
+ in 'A'..'F' -> ch - 'A' + 10
+ in 'a'..'f' -> ch - 'a' + 10
+ else -> -1
+ }
+
+ fun printHexBinary(data: ByteArray, lowerCase: Boolean = false): String {
+ val r = StringBuilder(data.size * 2)
+ for (b in data) {
+ r.append(hexCode[b.toInt() shr 4 and 0xF])
+ r.append(hexCode[b.toInt() and 0xF])
+ }
+ return if (lowerCase) r.toString().lowercase() else r.toString()
+ }
+
+ fun toHexString(n: Int): String {
+ val arr = ByteArray(4)
+ for (i in 0 until 4) {
+ arr[i] = (n shr (24 - i * 8)).toByte()
+ }
+ return printHexBinary(arr, true).trimStart('0').takeIf { it.isNotEmpty() } ?: "0"
+ }
+}