// retoor <retoor@molodetz.nl>
import "crypto" for Crypto
import "strutil" for Str
import "bytes" for Bytes
class Uuid {
static toHex_(bytes) { Str.hexEncode(Bytes.fromList(bytes)) }
static v4() {
var bytes = Crypto.randomBytes(16)
bytes[6] = (bytes[6] & 0x0F) | 0x40
bytes[8] = (bytes[8] & 0x3F) | 0x80
var hex = toHex_(bytes)
return hex[0..7] + "-" + hex[8..11] + "-" + hex[12..15] + "-" + hex[16..19] + "-" + hex[20..31]
}
static isValid(string) {
if (!(string is String)) return false
if (string.count != 36) return false
if (string[8] != "-" || string[13] != "-" || string[18] != "-" || string[23] != "-") return false
var hexChars = "0123456789abcdefABCDEF"
var positions = [0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 14, 15, 16, 17, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]
for (pos in positions) {
if (!hexChars.contains(string[pos])) return false
}
return true
}
static isV4(string) {
if (!isValid(string)) return false
var version = string[14]
if (version != "4") return false
var variant = string[19]
if (variant != "8" && variant != "9" && variant != "a" && variant != "b" && variant != "A" && variant != "B") return false
return true
}
}