     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

! 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 ;
IN: uuid

<PRIVATE

: (timestamp) ( -- time_high time_mid time_low )
    ! 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 ;

: (hardware) ( -- address )
    ! Choose a random 48-bit number with eighth bit

    ! Choose a random 14-bit number
    14 random-bits ;

: (version) ( n version -- n' )
    [
        0xc000 48 shift bitnot bitand
        0x8000 48 shift bitor
        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
