]> gitweb.factorcode.org Git - factor.git/commitdiff
uuid: adding version 6, 7, 8.
authorJohn Benediktsson <mrjbq7@gmail.com>
Mon, 13 Jun 2022 20:25:06 +0000 (13:25 -0700)
committerJohn Benediktsson <mrjbq7@gmail.com>
Mon, 13 Jun 2022 20:26:00 +0000 (13:26 -0700)
basis/uuid/uuid.factor

index 96481ae4bf77d62d566d3d075b72f90468587472..2f2f41dac065a236da327a6b23d078fd81488e25 100644 (file)
@@ -1,20 +1,17 @@
 ! 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
@@ -25,13 +22,6 @@ IN: uuid
     ! 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
@@ -39,6 +29,15 @@ IN: uuid
         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
@@ -58,8 +57,10 @@ PRIVATE>
     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
@@ -75,6 +76,19 @@ PRIVATE>
     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 ;