1 ! Copyright (C) 2008 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
3 USING: byte-arrays calendar checksums checksums.md5
4 checksums.sha io.binary kernel math math.parser math.ranges
5 random sequences strings system unicode ;
10 : (timestamp) ( -- time_high time_mid time_low )
11 ! 0x01b21dd213814000L is the number of 100-ns intervals
12 ! between the UUID epoch 1582-10-15 00:00:00 and the
13 ! Unix epoch 1970-01-01 00:00:00.
14 gmt timestamp>micros 10 * 0x01b21dd213814000 +
15 [ -48 shift 0x0fff bitand ]
16 [ -32 shift 0xffff bitand ]
20 : (hardware) ( -- address )
21 ! Choose a random 48-bit number with eighth bit
22 ! set to 1 (as recommended in RFC 4122)
23 48 random-bits 0x010000000000 bitor ;
25 : (clock) ( -- clockseq )
26 ! Choose a random 14-bit number
29 : <uuid> ( address clockseq time_high time_mid time_low -- n )
31 [ 80 shift ] dip bitor
32 [ 64 shift ] dip bitor
33 [ 48 shift ] dip bitor
36 : (version) ( n version -- n' )
38 0xc000 48 shift bitnot bitand
40 0xf000 64 shift bitnot bitand
41 ] dip 76 shift bitor ;
43 : uuid>string ( n -- string )
44 >hex 32 CHAR: 0 pad-head
45 [ CHAR: - 20 ] dip insert-nth
46 [ CHAR: - 16 ] dip insert-nth
47 [ CHAR: - 12 ] dip insert-nth
48 [ CHAR: - 8 ] dip insert-nth ;
50 : string>uuid ( string -- n )
51 [ CHAR: - = ] reject hex> ;
55 : uuid-parse ( string -- byte-array )
58 : uuid-unparse ( byte-array -- string )
62 (hardware) (clock) (timestamp) <uuid>
63 1 (version) uuid>string ;
65 : uuid3 ( namespace name -- string )
66 [ uuid-parse ] dip append
67 md5 checksum-bytes 16 short head be>
68 3 (version) uuid>string ;
72 4 (version) uuid>string ;
74 : uuid5 ( namespace name -- string )
75 [ uuid-parse ] dip append
76 sha1 checksum-bytes 16 short head be>
77 5 (version) uuid>string ;
79 CONSTANT: NAMESPACE_DNS "6ba7b810-9dad-11d1-80b4-00c04fd430c8"
80 CONSTANT: NAMESPACE_URL "6ba7b811-9dad-11d1-80b4-00c04fd430c8"
81 CONSTANT: NAMESPACE_OID "6ba7b812-9dad-11d1-80b4-00c04fd430c8"
82 CONSTANT: NAMESPACE_X500 "6ba7b814-9dad-11d1-80b4-00c04fd430c8"