1 ! Copyright (C) 2008 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
3 USING: byte-arrays checksums checksums.md5 checksums.sha
4 kernel math math.parser math.ranges random unicode.case
5 sequences strings system io.binary ;
11 : (timestamp) ( -- time_high time_mid time_low )
12 ! 0x01b21dd213814000L is the number of 100-ns intervals
13 ! between the UUID epoch 1582-10-15 00:00:00 and the
14 ! Unix epoch 1970-01-01 00:00:00.
15 micros 10 * HEX: 01b21dd213814000 +
16 [ -48 shift HEX: 0fff bitand ]
17 [ -32 shift HEX: ffff bitand ]
18 [ HEX: ffffffff bitand ]
21 : (hardware) ( -- address )
22 ! Choose a random 48-bit number with eighth bit
23 ! set to 1 (as recommended in RFC 4122)
24 48 random-bits HEX: 010000000000 bitor ;
26 : (clock) ( -- clockseq )
27 ! Choose a random 14-bit number
30 : <uuid> ( address clockseq time_high time_mid time_low -- n )
32 [ 80 shift ] dip bitor
33 [ 64 shift ] dip bitor
34 [ 48 shift ] dip bitor
37 : (version) ( n version -- n' )
39 HEX: c000 48 shift bitnot bitand
40 HEX: 8000 48 shift bitor
41 HEX: f000 64 shift bitnot bitand
42 ] dip 76 shift bitor ;
44 : uuid>string ( n -- string )
45 >hex 32 CHAR: 0 pad-head
46 [ CHAR: - 20 ] dip insert-nth
47 [ CHAR: - 16 ] dip insert-nth
48 [ CHAR: - 12 ] dip insert-nth
49 [ CHAR: - 8 ] dip insert-nth ;
51 : string>uuid ( string -- n )
52 [ CHAR: - = not ] filter 16 base> ;
56 : uuid-parse ( string -- byte-array )
59 : uuid-unparse ( byte-array -- string )
63 (hardware) (clock) (timestamp) <uuid>
64 1 (version) uuid>string ;
66 : uuid3 ( namespace name -- string )
67 [ uuid-parse ] dip append
68 md5 checksum-bytes 16 short head be>
69 3 (version) uuid>string ;
73 4 (version) uuid>string ;
75 : uuid5 ( namespace name -- string )
76 [ uuid-parse ] dip append
77 sha1 checksum-bytes 16 short head be>
78 5 (version) uuid>string ;
80 CONSTANT: NAMESPACE_DNS "6ba7b810-9dad-11d1-80b4-00c04fd430c8"
81 CONSTANT: NAMESPACE_URL "6ba7b811-9dad-11d1-80b4-00c04fd430c8"
82 CONSTANT: NAMESPACE_OID "6ba7b812-9dad-11d1-80b4-00c04fd430c8"
83 CONSTANT: NAMESPACE_X500 "6ba7b814-9dad-11d1-80b4-00c04fd430c8"