]> gitweb.factorcode.org Git - factor.git/blob - basis/uuid/uuid.factor
Merge branch 'new-math-parser' of git://factorcode.org/git/factor into new-math-parser
[factor.git] / basis / uuid / uuid.factor
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 ;
6
7 IN: uuid 
8
9 <PRIVATE
10
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     system-micros 10 * HEX: 01b21dd213814000 +
16     [ -48 shift HEX: 0fff bitand ] 
17     [ -32 shift HEX: ffff bitand ]
18     [ HEX: ffffffff bitand ]
19     tri ;
20
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 ;
25
26 : (clock) ( -- clockseq ) 
27     ! Choose a random 14-bit number
28     14 random-bits ;
29
30 : <uuid> ( address clockseq time_high time_mid time_low -- n )
31     96 shift 
32     [ 80 shift ] dip bitor 
33     [ 64 shift ] dip bitor
34     [ 48 shift ] dip bitor
35     bitor ;
36
37 : (version) ( n version -- n' )
38     [
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 ;
43
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 ;
50  
51 : string>uuid ( string -- n )
52     [ CHAR: - = not ] filter 16 base> ;
53
54 PRIVATE>
55
56 : uuid-parse ( string -- byte-array ) 
57     string>uuid 16 >be ;
58
59 : uuid-unparse ( byte-array -- string ) 
60     be> uuid>string ;
61
62 : uuid1 ( -- string )
63     (hardware) (clock) (timestamp) <uuid> 
64     1 (version) uuid>string ;
65
66 : uuid3 ( namespace name -- string )
67     [ uuid-parse ] dip append 
68     md5 checksum-bytes 16 short head be> 
69     3 (version) uuid>string ;
70
71 : uuid4 ( -- string )
72     128 random-bits 
73     4 (version) uuid>string ;
74
75 : uuid5 ( namespace name -- string )
76     [ uuid-parse ] dip append 
77     sha1 checksum-bytes 16 short head be> 
78     5 (version) uuid>string ;
79
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"
84
85