UUIDs as RFC 9562 defines them: versions 1 to 8, nil and max, strict parsing, and generation that is safe from many threads.
import encoding.uuid
A UUID is a 128 bit identifier that can be made on any machine without asking a server. This package follows RFC 9562, which replaced RFC 4122, and checks its output against the test vectors of that RFC. A UUID is a small value of two 64 bit halves, so it is cheap to copy, compare and use as a key.
Which version to use:
Version
Made by
Use it for
4
NewV4, New
Plain random ids. The default choice.
7
NewV7
Database keys and anything you sort or index: the time comes first, so new ids land at the end of an index.
5
NewV5
The same name must always give the same id, for example an id for a URL.
3
NewV3
Like 5 with MD5, only to match ids that already exist.
1 and 6
NewV1, NewV6
Time based ids that other systems expect. Version 6 is version 1 reordered so it sorts by time; prefer it for new code.
8
NewV8
Your own layout in the 122 free bits.
The random versions read only the operating system secure random source. The package never uses std/rand, which is not meant for identifiers. If the secure source cannot be read the process stops, because an id built from anything weaker would be a security hole; there is no half working mode to handle.
Making an id
New makes a random version 4 id and String writes it as the usual 36 characters. Nil and Max are the all zero and all one ids. Printing a UUID with println writes the same text.
encoding-uuid-guide-basics.salam
import encoding.uuid
funcmain:
id := uuid.New()
println uuid.String(id).Len(), uuid.Version(id), uuid.Variant(id) == uuid.VARIANT_RFC
text := uuid.NewString()
println uuid.IsValid(text), text.Len()
println uuid.Nil()
println uuid.Max()
println uuid.IsNil(uuid.Nil()), uuid.IsNil(id)
end
Parse accepts the canonical form, the form in braces, the urn:uuid: form and the form with no hyphens, in capitals or not. It is strict: no spaces around the text, every hyphen where it belongs, nothing but hex digits. It returns a ParseResult with ok, id and error. Use MustParse for literals in your own code and ParseOr when you have a fallback. String, Upper, Compact, Braced and URN write the other direction.
encoding-uuid-guide-parse.salam
import encoding.uuid
funcmain:
forms := [
"f81d4fae-7dec-11d0-a765-00a0c91e6bf6", "F81D4FAE-7DEC-11D0-A765-00A0C91E6BF6",
"f81d4fae7dec11d0a76500a0c91e6bf6", "{f81d4fae-7dec-11d0-a765-00a0c91e6bf6}",
"urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6", "f81d4fae-7dec-11d0-a765",
"f81d4fae-7dec-11d0-a765-00a0c91e6bfz"
]
each text in forms:
r := uuid.Parse(text)
if r.ok:
println"ok ", uuid.String(r.id)
else:
println"error", r.error
endend
id := uuid.MustParse("f81d4fae-7dec-11d0-a765-00a0c91e6bf6")
println uuid.Upper(id)
println uuid.Compact(id)
println uuid.Braced(id)
println uuid.URN(id)
end
Output
ok f81d4fae-7dec-11d0-a765-00a0c91e6bf6
ok f81d4fae-7dec-11d0-a765-00a0c91e6bf6
ok f81d4fae-7dec-11d0-a765-00a0c91e6bf6
ok f81d4fae-7dec-11d0-a765-00a0c91e6bf6
ok f81d4fae-7dec-11d0-a765-00a0c91e6bf6
error uuid: invalid length 23
error uuid: invalid character at position 35
F81D4FAE-7DEC-11D0-A765-00A0C91E6BF6
f81d4fae7dec11d0a76500a0c91e6bf6
{f81d4fae-7dec-11d0-a765-00a0c91e6bf6}
urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6
Ids made from names
Version 5 (and 3) hashes a namespace id and a name, so the same pair always gives the same id. The four namespaces of the RFC are NamespaceDNS, NamespaceURL, NamespaceOID and NamespaceX500; you can also use any UUID of your own as a namespace. The values below are the ones printed in RFC 9562.
Versions 1, 6 and 7 carry a time. UnixMillis and UnixNanos read it back, Timestamp gives the raw 60 bit count of version 1 and 6. The From...Parts functions build an id from exact parts, which is how the tests pin the RFC test vectors. NewV7 returns a larger id on every call, even in the same millisecond, even from other threads, and even when the clock is set back. NewV1 and NewV6 never repeat either: ids in the same 100 nanosecond tick move the time forward by one tick, and a clock that jumps far back changes the clock sequence as RFC 9562 asks. Their node is random per process with the multicast bit set, never a real network address.
All the generators can be called from any number of threads, with go, spawn or a pool. The clock state, the version 7 counter and the buffer of random bytes sit behind locks of their own, so there are no duplicates and no id goes backwards in a thread. The example makes 8000 ids from 8 tasks and counts the different ones.
encoding-uuid-guide-threads.salam
import encoding.uuid
import mem
import pool
const WORKERS := 8const PER := 1000mut slots := nullasu64*
funcproduce(worker: int):
repeat PER in i:
id := uuid.NewV7()
slot := (worker * PER + i) * 2
slots[slot] = id.hi
slots[slot + 1] = id.lo
endendfuncmain:
slots = mem.Allocate((WORKERS * PER * 16) asu64) asu64*
repeat WORKERS in worker:
go produce(worker)
end
pool.GoWait()
mut seen := HashMap {} asHashMap<str, int>
defer seen.Free()
repeat WORKERS * PER in i:
seen.Put(uuid.Compact(uuid.UUID { hi = slots[i * 2], lo = slots[i * 2 + 1] }), 1)
endprintln"generated", WORKERS * PER, "unique", seen.Size()
mem.Free(slots asvoid*)
end
Output
generated 8000 unique 8000
Short forms
Base64URL writes an id in 22 characters that are safe in a URL and Base32 in 26 lowercase characters that are safe in a file name or a host name. Reading them back is as strict as Parse: the unused bits must be zero, so one id has one text.
encoding-uuid-guide-short.salam
import encoding.uuid
funcmain:
id := uuid.MustParse("f81d4fae-7dec-11d0-a765-00a0c91e6bf6")
short := uuid.Base64URL(id)
println short, short.Len()
println uuid.Base32(id)
back := uuid.FromBase64URL(short)
println back.ok, uuid.Equal(back.id, id)
println uuid.FromBase64URL("too short").error
end
Output
-B1Prn3sEdCnZQCgyR5r9g 22
7aou7lt55qi5bj3facqmshtl6y
true true
uuid: base64url text must have 22 characters
Custom ids and bytes
Version 8 keeps the version and variant bits and leaves the rest to you: FromV8Parts takes the three fields of the RFC and NewV8 takes two 64 bit halves. Bytes and FromBytes convert to the 16 bytes in network order, and ToBuffer and FromBuffer do the same for raw memory.
A 128 bit identifier kept as two unsigned 64 bit halves, hi (the first eight bytes) and lo (the last eight). It is a plain value: copy it, compare it with Equal and Compare, print it with println.
Name
Type
Description
hi
u64 = 0
The first eight bytes, most significant first.
lo
u64 = 0
The last eight bytes, most significant first.
encoding-uuid-Bytes.salam
import encoding.uuid
funcmain:
id := uuid.MustParse("f81d4fae-7dec-11d0-a765-00a0c91e6bf6")
mut bytes := uuid.Bytes(id)
defer bytes.Free()
println bytes.Len(), bytes.Get(0), bytes.Get(15)
println uuid.Equal(uuid.FromBytes(bytes), id)
end
Variant of old NCS identifiers, the top bit of the variant field is 0.
encoding-uuid-NewV4.salam
import encoding.uuid
funcmain:
a := uuid.NewV4()
b := uuid.NewV4()
println uuid.Version(a), uuid.Variant(a) == uuid.VARIANT_RFC
println uuid.Equal(a, b), uuid.Compare(a, a)
end
The namespace UUID for fully qualified domain names, 6ba7b810-9dad-11d1-80b4-00c04fd430c8.
encoding-uuid-NewV5.salam
import encoding.uuid
funcmain:
id := uuid.NewV5(uuid.NamespaceDNS(), "www.example.com")
println id
println uuid.Version(id)
println uuid.NewV3(uuid.NamespaceDNS(), "www.example.com")
end
Builds a version 1 UUID from a 60 bit timestamp (100 nanosecond steps since 1582-10-15), a 14 bit clock sequence and a 48 bit node. The deterministic builder behind NewV1.
A time based UUID, version 1: the current time, a clock sequence and the process node. It never repeats: when two calls land in the same tick the time is moved forward by one tick, and when the clock jumps far back the clock sequence is changed.
A random UUID, version 4. It has 122 random bits from the operating system secure random source and nothing else. The source is read in large blocks under a lock, so it is safe from many threads.
A UUID made of the Unix time in milliseconds followed by a counter and random bits, version 7. Every call returns a larger UUID than the one before, in the whole process and across threads, even when the clock stands still or goes back.
A name based UUID using MD5, version 3. The same namespace and name always give the same UUID. Prefer NewV5 unless you must match existing version 3 ids.
A name based UUID using SHA-1, version 5. The same namespace and name always give the same UUID, on every machine and in every language that follows RFC 9562.
The 48 bit node this process puts in version 1 and 6 UUIDs: random, with the multicast bit set as RFC 9562 asks, so it never equals a real network card address.
Reads a UUID from text. It accepts the canonical form, the form in braces, the urn:uuid: form and the form with no hyphens, in any case. Everything else is an error: spaces, a missing or misplaced hyphen, a character that is not a hex digit, a wrong length.