-
Notifications
You must be signed in to change notification settings - Fork 26
/
uuidv7.tcl
36 lines (28 loc) · 891 Bytes
/
uuidv7.tcl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package require Tcl 8.6
namespace eval uuidv7 {
namespace export uuidv7
}
proc ::uuidv7::generate { } {
# random bytes
set randomBytes {}
for {set i 0} {$i < 16} {incr i} {
lappend randomBytes [expr {int(rand() * 256)}]
}
# current timestamp in ms
set timestamp_ms [expr {[clock milliseconds]}]
# timestamp
set timestamp_bytes {}
for {set i 5} {$i >= 0} {incr i -1} {
lappend timestamp_bytes [expr {($timestamp_ms >> ($i * 8)) & 0xFF}]
}
# version and variant
set bytes [lreplace $randomBytes 0 5 {*}$timestamp_bytes]
lset bytes 6 [expr {([lindex $bytes 6] & 0x0F) | 0x70}]
lset bytes 8 [expr {([lindex $bytes 8] & 0x3F) | 0x80}]
return [binary format c* $bytes]
}
proc ::uuidv7::tostring { uuid } {
binary scan $uuid H* s
return [string tolower $s]
}
puts [uuidv7::tostring [uuidv7::generate]]