encoding.uuid
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.
import encoding.uuid
func main:
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)
endReading and writing text
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.
import encoding.uuid
func main:
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
end
end
id := uuid.MustParse("f81d4fae-7dec-11d0-a765-00a0c91e6bf6")
println uuid.Upper(id)
println uuid.Compact(id)
println uuid.Braced(id)
println uuid.URN(id)
endIds 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.
import encoding.uuid
func main:
dns := uuid.NamespaceDNS()
println uuid.NewV5(dns, "www.example.com")
println uuid.NewV3(dns, "www.example.com")
println uuid.NewV5(dns, "www.example.com") == uuid.NewV5(dns, "www.example.com")
println uuid.Equal(uuid.NewV5(dns, "python.org"), uuid.NewV5(uuid.NamespaceURL(), "python.org"))
endTime based ids
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.
import encoding.uuid
func main:
v1 := uuid.FromV1Parts(0x1EC9414C232AB00, 0x33C8, 0x9F6BDECED846)
v6 := uuid.FromV6Parts(0x1EC9414C232AB00, 0x33C8, 0x9F6BDECED846)
v7 := uuid.FromV7Parts(1645557742000, 0xCC3, 0x18C4DC0C0C07398F)
println v1
println v6
println v7
println uuid.UnixMillis(v1), uuid.UnixMillis(v6), uuid.UnixMillis(v7)
println uuid.ClockSequence(v1), uuid.Node(v1) == 0x9F6BDECED846
first := uuid.NewV7()
second := uuid.NewV7()
println uuid.Less(first, second), uuid.String(first) < uuid.String(second)
println uuid.UnixMillis(second) - uuid.UnixMillis(first) < 1000
endMany threads at once
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.
import encoding.uuid
import mem
import pool
const WORKERS := 8
const PER := 1000
mut slots := null as u64*
func produce(worker: int):
repeat PER in i:
id := uuid.NewV7()
slot := (worker * PER + i) * 2
slots[slot] = id.hi
slots[slot + 1] = id.lo
end
end
func main:
slots = mem.Allocate((WORKERS * PER * 16) as u64) as u64*
repeat WORKERS in worker:
go produce(worker)
end
pool.GoWait()
mut seen := HashMap {} as HashMap<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)
end
println "generated", WORKERS * PER, "unique", seen.size()
mem.Free(slots as void*)
endShort 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.
import encoding.uuid
func main:
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
endCustom 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.
import encoding.uuid
func main:
custom := uuid.FromV8Parts(0x2489E9AD2EE2, 0xE00, 0xEC932D5F69181C0)
println custom, uuid.Version(custom), uuid.Variant(custom) == uuid.VARIANT_RFC
other := uuid.NewV8(0x0123456789ABCDEF as u64, 0xFEDCBA9876543210 as u64)
println other
mut bytes := uuid.Bytes(other)
println bytes.Len(), bytes.get(0), bytes.get(15)
println uuid.Equal(uuid.FromBytes(bytes), other)
bytes.free()
batch := uuid.Batch(3)
println batch.Len()
batch.free()
endWhat people get wrong:
- Using version 4 as a primary key in a big table. Random keys scatter writes over the whole index; version 7 keeps them together.
- Hiding secrets in the time of a version 1, 6 or 7 id. The time can be read back by anyone who has the id.
- Expecting version 5 to be secret. It is a hash of public values, anyone who knows the name can compute it.
- Comparing the text of ids made in different cases. Compare with
Equal, or write both withString. - Forgetting to free the vectors from
Bytes,BatchandBatchV7.
For random bytes and tokens see crypto; for hex and base64 of arbitrary data see encoding.
Types
ParseResult
struct ParseResult| Name | Type | Description |
|---|---|---|
ok | bool = false | True when the text was a valid UUID. |
id | UUID | The parsed value, the nil UUID when ok is false. |
error | str = "" | A short description of the problem, empty when ok is true. |
import encoding.uuid
func main:
r := uuid.Parse("{F81D4FAE-7DEC-11D0-A765-00A0C91E6BF6}")
println r.ok, uuid.String(r.id)
bad := uuid.Parse("not a uuid")
println bad.ok, bad.error
println uuid.ParseOr("nope", uuid.Nil())
endUUID
struct UUID| Name | Type | Description |
|---|---|---|
hi | u64 = 0 | The first eight bytes, most significant first. |
lo | u64 = 0 | The last eight bytes, most significant first. |
import encoding.uuid
func main:
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)
endto_str
func to_str(): strimport encoding.uuid
import mem
func main:
id := uuid.MustParse("f81d4fae-7dec-11d0-a765-00a0c91e6bf6")
buf := mem.Allocate(16 as u64)
defer mem.Free(buf)
uuid.ToBuffer(id, buf)
p := buf as u8*
println p[0], p[15]
back := uuid.FromBuffer(buf)
println back.to_str()
println back.hi == id.hi, back.lo == id.lo
println uuid.Equal(back, id)
endConstants and variables
VARIANT_NCS
const VARIANT_NCS: i32 = 0import encoding.uuid
func main:
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)
endVARIANT_RFC
const VARIANT_RFC: i32 = 1The example for this item is shown with the ones above: encoding-uuid-NewV4.salam
VARIANT_MICROSOFT
const VARIANT_MICROSOFT: i32 = 2The example for this item is shown with the ones above: encoding-uuid-NewV4.salam
VARIANT_FUTURE
const VARIANT_FUTURE: i32 = 3The example for this item is shown with the ones above: encoding-uuid-NewV4.salam
Functions
Parse
func Parse(s: str): ParseResultThe example for this item is shown with the ones above: encoding-uuid-Parse.salam
ParseOr
func ParseOr(s: str, fallback: UUID): UUIDThe example for this item is shown with the ones above: encoding-uuid-Parse.salam
IsValid
func IsValid(s: str): boolThe example for this item is shown with the ones above: encoding-uuid-Parse.salam
MustParse
func MustParse(s: str): UUIDimport encoding.uuid
func main:
id := uuid.MustParse("f81d4fae-7dec-11d0-a765-00a0c91e6bf6")
println uuid.String(id)
println uuid.Upper(id)
println uuid.Compact(id)
println uuid.Braced(id)
println uuid.URN(id)
endFromV4Parts
func FromV4Parts(hi: u64, lo: u64): UUIDThe example for this item is shown with the ones above: encoding-uuid-NewV4.salam
FromV7Parts
func FromV7Parts(unix_ms: i64, rand_a: i64, rand_b: i64): UUIDimport encoding.uuid
func main:
id := uuid.FromV7Parts(1645557742000, 0xCC3, 0x18C4DC0C0C07398F)
println id
println uuid.UnixMillis(id)
endFromV8Parts
func FromV8Parts(custom_a: i64, custom_b: i64, custom_c: i64): UUIDimport encoding.uuid
func main:
custom := uuid.FromV8Parts(0x2489E9AD2EE2, 0xE00, 0xEC932D5F69181C0)
println custom, uuid.Version(custom), uuid.Variant(custom) == uuid.VARIANT_RFC
other := uuid.NewV8(0x0123456789ABCDEF as u64, 0xFEDCBA9876543210 as u64)
println other
println uuid.Stamp(0 as u64, 0 as u64, 9)
endNewV4
func NewV4(): UUIDThe example for this item is shown with the ones above: encoding-uuid-NewV4.salam
NewV7
func NewV7(): UUIDimport encoding.uuid
func main:
ids := uuid.BatchV7(5)
defer ids.free()
mut ordered := true
repeat ids.Len() - 1 in i:
if not uuid.Less(ids.get(i), ids.get(i + 1)): ordered = false end
end
println "version", uuid.Version(ids.get(0)), "ordered", ordered
println uuid.HasTime(ids.get(0))
endNewV8
func NewV8(hi: u64, lo: u64): UUIDThe example for this item is shown with the ones above: encoding-uuid-Custom.salam
Nil
func Nil(): UUIDimport encoding.uuid
func main:
id := uuid.New()
println uuid.String(id).Len(), uuid.Version(id), uuid.Variant(id) == uuid.VARIANT_RFC
println uuid.IsValid(uuid.NewString())
println uuid.Nil(), uuid.IsNil(uuid.Nil()), uuid.IsNil(id)
println uuid.Max(), uuid.IsMax(uuid.Max())
ids := uuid.Batch(3)
println ids.Len()
ids.free()
endMax
func Max(): UUIDThe example for this item is shown with the ones above: encoding-uuid-New.salam
IsNil
func IsNil(u: UUID): boolThe example for this item is shown with the ones above: encoding-uuid-New.salam
IsMax
func IsMax(u: UUID): boolThe example for this item is shown with the ones above: encoding-uuid-New.salam
Equal
func Equal(a: UUID, b: UUID): boolThe example for this item is shown with the ones above: encoding-uuid-NewV4.salam
Compare
func Compare(a: UUID, b: UUID): intThe example for this item is shown with the ones above: encoding-uuid-NewV4.salam
Less
func Less(a: UUID, b: UUID): boolThe example for this item is shown with the ones above: encoding-uuid-NewV7.salam
Version
func Version(u: UUID): intThe example for this item is shown with the ones above: encoding-uuid-NewV4.salam
Variant
func Variant(u: UUID): intThe example for this item is shown with the ones above: encoding-uuid-NewV4.salam
Byte
func Byte(u: UUID, i: int): intThe example for this item is shown with the ones above: encoding-uuid-Bytes.salam
Bytes
func Bytes(u: UUID): Vector<u8>The example for this item is shown with the ones above: encoding-uuid-Bytes.salam
FromBytes
func FromBytes(b: Vector<u8>): UUIDThe example for this item is shown with the ones above: encoding-uuid-Bytes.salam
ToBuffer
func ToBuffer(u: UUID, out: void*)The example for this item is shown with the ones above: encoding-uuid-Buffer.salam
FromBuffer
func FromBuffer(src: void*): UUIDThe example for this item is shown with the ones above: encoding-uuid-Buffer.salam
NamespaceDNS
func NamespaceDNS(): UUIDimport encoding.uuid
func main:
id := uuid.NewV5(uuid.NamespaceDNS(), "www.example.com")
println id
println uuid.Version(id)
println uuid.NewV3(uuid.NamespaceDNS(), "www.example.com")
endNamespaceURL
func NamespaceURL(): UUIDThe example for this item is shown with the ones above: encoding-uuid-NewV5.salam
NamespaceOID
func NamespaceOID(): UUIDThe example for this item is shown with the ones above: encoding-uuid-NewV5.salam
NamespaceX500
func NamespaceX500(): UUIDThe example for this item is shown with the ones above: encoding-uuid-NewV5.salam
FromV1Parts
func FromV1Parts(ts: i64, clock_seq: int, node: i64): UUIDimport encoding.uuid
func main:
v1 := uuid.FromV1Parts(0x1EC9414C232AB00, 0x33C8, 0x9F6BDECED846)
v6 := uuid.FromV6Parts(0x1EC9414C232AB00, 0x33C8, 0x9F6BDECED846)
println v1
println v6
println uuid.UnixMillis(v1), uuid.ClockSequence(v6), uuid.Node(v1) == 0x9F6BDECED846
println uuid.Timestamp(v1) == uuid.Timestamp(v6)
a := uuid.NewV1()
b := uuid.NewV1()
println uuid.Timestamp(a) < uuid.Timestamp(b), uuid.Node(a) == uuid.NodeID()
own := uuid.NewV1WithNode(0x0123456789AB)
println uuid.Node(own) == 0x0123456789AB, uuid.Version(uuid.NewV6())
endFromV6Parts
func FromV6Parts(ts: i64, clock_seq: int, node: i64): UUIDThe example for this item is shown with the ones above: encoding-uuid-Time.salam
NewV1
func NewV1(): UUIDThe example for this item is shown with the ones above: encoding-uuid-Time.salam
NewV1WithNode
func NewV1WithNode(node: i64): UUIDThe example for this item is shown with the ones above: encoding-uuid-Time.salam
NewV6
func NewV6(): UUIDThe example for this item is shown with the ones above: encoding-uuid-Time.salam
HasTime
func HasTime(u: UUID): boolThe example for this item is shown with the ones above: encoding-uuid-NewV7.salam
Timestamp
func Timestamp(u: UUID): i64The example for this item is shown with the ones above: encoding-uuid-Time.salam
UnixNanos
func UnixNanos(u: UUID): i64The example for this item is shown with the ones above: encoding-uuid-FromV7Parts.salam
UnixMillis
func UnixMillis(u: UUID): i64The example for this item is shown with the ones above: encoding-uuid-FromV7Parts.salam
ClockSequence
func ClockSequence(u: UUID): intThe example for this item is shown with the ones above: encoding-uuid-Time.salam
Node
func Node(u: UUID): i64The example for this item is shown with the ones above: encoding-uuid-Time.salam
Base64URL
func Base64URL(u: UUID): strimport encoding.uuid
func main:
id := uuid.MustParse("f81d4fae-7dec-11d0-a765-00a0c91e6bf6")
println uuid.Base64URL(id)
println uuid.Base32(id)
println uuid.FromBase32(uuid.Base32(id)).ok
endFromBase64URL
func FromBase64URL(s: str): ParseResultThe example for this item is shown with the ones above: encoding-uuid-Base64URL.salam
Base32
func Base32(u: UUID): strThe example for this item is shown with the ones above: encoding-uuid-Base64URL.salam
FromBase32
func FromBase32(s: str): ParseResultThe example for this item is shown with the ones above: encoding-uuid-Base64URL.salam
Stamp
func Stamp(hi: u64, lo: u64, version: int): UUIDThe example for this item is shown with the ones above: encoding-uuid-Custom.salam
NewV3
func NewV3(ns: UUID, name: str): UUIDThe example for this item is shown with the ones above: encoding-uuid-NewV5.salam
NewV5
func NewV5(ns: UUID, name: str): UUIDThe example for this item is shown with the ones above: encoding-uuid-NewV5.salam
String
func String(u: UUID): strThe example for this item is shown with the ones above: encoding-uuid-Parse.salam
Upper
func Upper(u: UUID): strThe example for this item is shown with the ones above: encoding-uuid-Formats.salam
Compact
func Compact(u: UUID): strThe example for this item is shown with the ones above: encoding-uuid-Formats.salam
Braced
func Braced(u: UUID): strThe example for this item is shown with the ones above: encoding-uuid-Formats.salam
URN
func URN(u: UUID): strThe example for this item is shown with the ones above: encoding-uuid-Formats.salam
NodeID
func NodeID(): i64The example for this item is shown with the ones above: encoding-uuid-Time.salam
New
func New(): UUIDThe example for this item is shown with the ones above: encoding-uuid-New.salam
NewString
func NewString(): strThe example for this item is shown with the ones above: encoding-uuid-New.salam
Batch
func Batch(n: int): Vector<UUID>The example for this item is shown with the ones above: encoding-uuid-Custom.salam
BatchV7
func BatchV7(n: int): Vector<UUID>The example for this item is shown with the ones above: encoding-uuid-NewV7.salam