Scoop API

scoop:scoop.std:0.1.0

src/text/hex.scoop

Selected production source · src/text/hex.scoop

1package scoop.text
3import scoop.bytes.ByteArrayBuilder
5/**
6 * Encodes each byte as two hexadecimal digits, using the selected letter case.
7 */
8public fun List<Byte>.toHexString(uppercase: Boolean = false): String {
9 val length = size
10 val chars = MutableArray<Char>(checkedTextProduct(length, 2L)) { _ -> '0' }
11 val alphabet = if (uppercase) "0123456789ABCDEF" else "0123456789abcdef"
12 var index = 0L
13 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 += 1L
18 }
19 return String.fromChars(chars)
22private enum HexResult { Bytes(val value: Array<Byte>), Invalid(val index: Long) }
24private fun parseHex(text: String): HexResult {
25 val output = ByteArrayBuilder()
26 var first = -1
27 var index = 0L
28 for (character in text) {
29 val digit = textDigit(character)
30 if (digit < 0 || digit >= 16) return HexResult.Invalid(index)
31 if (first < 0) first = digit
32 else { output.append((first * 16 + digit).toByte()); first = -1 }
33 index += 1L
34 }
35 if (first >= 0) return HexResult.Invalid(index)
36 return HexResult.Bytes(output.toByteArray())
39/**
40 * Decodes an even-length hexadecimal string; malformed input throws IllegalArgumentException.
41 */
42public fun String.hexToByteArray(): Array<Byte> = when (parseHex(this)) {
43 case HexResult.Bytes(val value) -> value
44 case HexResult.Invalid(val index) -> throw IllegalArgumentException(Some("invalid hex at index " + index.toString()))
47/**
48 * Decodes an even-length hexadecimal string, returning None for invalid digits or odd length.
49 */
50public fun String.hexToByteArrayOrNone(): Array<Byte>? = when (parseHex(this)) {
51 case HexResult.Bytes(val value) -> Some(value)
52 case HexResult.Invalid(_) -> None