UUIDs
A UUID is a 128-bit identifier that can be made anywhere, with no central
counter, and still be unique. std/uuids makes, parses and compares them.
#import "std/uuids"
'' NewV4 is random; NewV7 starts with the time, so later ones sort later.
dim ids( 0 to 2 ) as uuids.Uuid
for i as int32 = 0 to 2
ids( i ) = uuids.NewV7( )
next
print "version:"; ids( 0 ).Version( )
print "sorted by creation? "; ids( 0 ) < ids( 1 ) andalso ids( 1 ) < ids( 2 )
print "a random one is version"; uuids.NewV4( ).Version( )
'' Parsing takes the usual spellings and always prints one form.
dim spellings( 0 to 3 ) as ustring = { _
"F81D4FAE-7DEC-11D0-A765-00A0C91E6BF6", _
"{f81d4fae-7dec-11d0-a765-00a0c91e6bf6}", _
"f81d4fae7dec11d0a76500a0c91e6bf6", _
"f81d4fae-7dec-11d0-a765" }
for each s in spellings
var r = uuids.Parse( s )
if r.IsOk( ) then
print r.Value( ).ToString( )
else
print s; ": "; r.Failure( ).Message( )
end if
next
Output
version: 7
sorted by creation? true
a random one is version 4
f81d4fae-7dec-11d0-a765-00a0c91e6bf6
f81d4fae-7dec-11d0-a765-00a0c91e6bf6
f81d4fae-7dec-11d0-a765-00a0c91e6bf6
f81d4fae-7dec-11d0-a765: uuid: invalid length
uuids.NewV4( ) is 122 random bits from the operating system's secure
generator. uuids.NewV7( ) starts with the time in milliseconds, so later ones
sort later — good for database keys — and within a program each one is
greater than the one before. The time inside a v7 is readable with
UnixMillis( ), so use v4 where creation time should stay private.
uuids.Parse accepts upper or lower case, with or without hyphens, in braces,
or after urn:uuid:; ToString( ) always gives the lower-case hyphenated
form. A Uuid has =, < and a hash, so it can be a
Map key or be sorted.
Activities
- Print
uuids.NilUuid( ).ToString( )anduuids.MaxUuid( ).ToString( ). - Keep a
containers.Map( of uuids.Uuid, ustring )of names, and look one up by aUuidyou parsed from text.