scoop:scoop.std:0.1.0
src/text/hex.scoop
Selected production source · src/text/hex.scoop
1
package scoop.text3
import scoop.bytes.ByteArrayBuilder5
/**6
* Encodes each byte as two hexadecimal digits, using the selected letter case.7
*/8
public fun List<Byte>.toHexString(uppercase: Boolean = false): String {9
val length = size10
val chars = MutableArray<Char>(checkedTextProduct(length, 2L)) { _ -> '0' }11
val alphabet = if (uppercase) "0123456789ABCDEF" else "0123456789abcdef"12
var index = 0L13
while (index < length) {14
val value = this[index].toUByte().toInt()15
chars[index * 2L] = alphabet.getCharAt((value / 16).toLong())16
chars[index * 2L + 1L] = alphabet.getCharAt((value % 16).toLong())17
index += 1L18
}19
return String.fromChars(chars)20
}22
private enum HexResult { Bytes(val value: Array<Byte>), Invalid(val index: Long) }24
private fun parseHex(text: String): HexResult {25
val output = ByteArrayBuilder()26
var first = -127
var index = 0L28
for (character in text) {29
val digit = textDigit(character)30
if (digit < 0 || digit >= 16) return HexResult.Invalid(index)31
if (first < 0) first = digit32
else { output.append((first * 16 + digit).toByte()); first = -1 }33
index += 1L34
}35
if (first >= 0) return HexResult.Invalid(index)36
return HexResult.Bytes(output.toByteArray())37
}39
/**40
* Decodes an even-length hexadecimal string; malformed input throws IllegalArgumentException.41
*/42
public fun String.hexToByteArray(): Array<Byte> = when (parseHex(this)) {43
case HexResult.Bytes(val value) -> value44
case HexResult.Invalid(val index) -> throw IllegalArgumentException(Some("invalid hex at index " + index.toString()))45
}47
/**48
* Decodes an even-length hexadecimal string, returning None for invalid digits or odd length.49
*/50
public fun String.hexToByteArrayOrNone(): Array<Byte>? = when (parseHex(this)) {51
case HexResult.Bytes(val value) -> Some(value)52
case HexResult.Invalid(_) -> None53
}