! Copyright (C) 2008 John Benediktsson
! See http://factorcode.org/license.txt for BSD license
-USING: calendar checksums checksums.md5 checksums.sha endian
-kernel math math.parser random sequences ;
+USING: calendar checksums checksums.md5 checksums.sha
+combinators endian kernel literals math math.bitwise math.parser
+random sequences ;
IN: uuid
<PRIVATE
-: (timestamp) ( -- time_high time_mid time_low )
+: (timestamp) ( -- time )
! 0x01b21dd213814000L is the number of 100-ns intervals
! between the UUID epoch 1582-10-15 00:00:00 and the
! Unix epoch 1970-01-01 00:00:00.
- now timestamp>micros 10 * 0x01b21dd213814000 +
- [ -48 shift 0x0fff bitand ]
- [ -32 shift 0xffff bitand ]
- [ 0xffffffff bitand ]
- tri ;
+ now timestamp>micros 10 * 0x01b21dd213814000 + ;
: (hardware) ( -- address )
! Choose a random 48-bit number with eighth bit
! Choose a random 14-bit number
14 random-bits ;
-: <uuid> ( address clockseq time_high time_mid time_low -- n )
- 96 shift
- [ 80 shift ] dip bitor
- [ 64 shift ] dip bitor
- [ 48 shift ] dip bitor
- bitor ;
-
: (version) ( n version -- n' )
[
0xc000 48 shift bitnot bitand
0xf000 64 shift bitnot bitand
] dip 76 shift bitor ;
+: (uuid) ( a version b variant c -- n )
+ {
+ [ 48 bits 80 shift ]
+ [ 76 shift + ]
+ [ 12 bits 64 shift + ]
+ [ 62 shift + ]
+ [ 62 bits + ]
+ } spread ;
+
: uuid>string ( n -- string )
>hex 32 CHAR: 0 pad-head
[ CHAR: - 20 ] dip insert-nth
be> uuid>string ;
: uuid1 ( -- string )
- (hardware) (clock) (timestamp) <uuid>
- 1 (version) uuid>string ;
+ (timestamp)
+ [ 32 bits 16 shift ] [ -32 shift 16 bits + 1 ] [ -48 shift ] tri
+ 0b01 (clock) 48 shift (hardware) +
+ (uuid) uuid>string ;
: uuid3 ( namespace name -- string )
[ uuid-parse ] dip append
sha1 checksum-bytes 16 short head be>
5 (version) uuid>string ;
+: uuid6 ( -- string )
+ (timestamp) [ -12 shift 6 ] [ 12 bits ] bi
+ 0b10 (clock) 48 shift $[ 48 random-bits ] +
+ (uuid) uuid>string ;
+
+: uuid7 ( -- string )
+ now timestamp>millis 7
+ 12 random-bits 0b11
+ 62 random-bits (uuid) uuid>string ;
+
+: uuid8 ( a b c -- string )
+ [ 8 ] 2dip [ 0b01 ] dip (uuid) uuid>string ;
+
: uuid-urn ( string -- url )
"url:urn:" prepend ;