scoop:scoop.std:0.1.0
src/uuid/uuid_parse.scoop
Selected production source · src/uuid/uuid_parse.scoop
1
package scoop.uuid3
import scoop.text.hexToByteArrayOrNone5
internal fun uuidFromBytes(bytes: List<Byte>): Uuid {6
if (bytes.size != 16L) throw IllegalArgumentException(Some("UUID requires 16 bytes"))7
var high = 0uL8
var low = 0uL9
var index = 0L10
while (index < 16L) {11
val byte = bytes[index].toUByte().toULong()12
if (index < 8L) high = (high shl 8L) or byte13
else low = (low shl 8L) or byte14
index += 1L15
}16
return Uuid(high, low)17
}19
internal fun parseUuid(text: String): Uuid? {20
if (text.byteLength != 32L && text.byteLength != 36L) return None21
val chars = text.toCharArray()22
if (chars.size != text.byteLength) return None23
var compact = text24
if (chars.size == 36L) {25
if (chars[8L] != '-' || chars[13L] != '-' || chars[18L] != '-' || chars[23L] != '-') return None26
compact = String.fromChars(Array<Char>(32L) { index ->27
val offset = if (index < 8L) 0L else if (index < 12L) 1L else if (index < 16L) 2L28
else if (index < 20L) 3L else 4L29
chars[index + offset]30
})31
}32
return when (compact.hexToByteArrayOrNone()) {33
case None -> None34
case Some(val bytes) -> Some(uuidFromBytes(bytes))35
}36
}