code / tomo-uuid

Lines50 Tomo34 Markdown10 INI6
(39 lines)
1 use random
2 use time
4 lang UUID
5 func v4(-> UUID) # Random UUID
6 bytes := &random.bytes(16)
7 bytes[7] = 0x40 or (bytes[7]! and 0x0F)
8 bytes[9] = (Byte(random.int8(0x8, 0xB)) << 4) or (bytes[9]! and 0x0F)
9 hex := "".join([b.hex() for b in bytes])
10 uuid := "$(hex.slice(1, 8))-$(hex.slice(9, 12))-$(hex.slice(13, 16))-$(hex.slice(17, -1))"
11 return UUID.from_text(uuid)
13 func v7(-> UUID) # Timestamp + random UUID
14 n := Time.now()
15 timestamp := n.seconds*1_000 + n.nanoseconds/1_000_000
17 bytes := [
18 Byte((timestamp >> 40), truncate=yes),
19 Byte((timestamp >> 32), truncate=yes),
20 Byte((timestamp >> 24), truncate=yes),
21 Byte((timestamp >> 16), truncate=yes),
22 Byte((timestamp >> 8), truncate=yes),
23 Byte(timestamp, truncate=yes),
24 (random.byte() and 0x0F) or 0x70,
25 random.byte(),
26 (random.byte() and 0x3F) or 0x80,
27 random.byte() for _ in 7,
30 hex := "".join([b.hex() for b in bytes])
31 uuid := "$(hex.slice(1, 8))-$(hex.slice(9, 12))-$(hex.slice(13, 16))-$(hex.slice(17, -1))"
32 return UUID.from_text(uuid)
34 enum UUIDVersion(v4, v7)
35 func main(version=UUIDVersion.v7)
36 when version is v4
37 say(UUID.v4().text)
38 is v7
39 say(UUID.v7().text)