Sortable unique identifiers: ULID text and binary forms, a thread safe monotonic generator, and range bounds for queries.
import encoding.ulid
A ULID is a 128 bit identifier made of a 48 bit timestamp in milliseconds and 80 random bits, written as 26 characters of Crockford base32. It is the sortable alternative to a random UUID: the text sorts in the order the ids were made, so a database index stays compact and a range of time is a range of ids. This package follows the ULID specification and is written in Salam.
The text uses the digits and the letters without I, L, O and U. The largest id is 7ZZZZZZZZZZZZZZZZZZZZZZZZZ, because 130 bits are used to hold 128. Parsing accepts lowercase, reads I and L as 1 and O as 0, and refuses U and anything above that largest id.
Piece
What it is
ULID
The value: time plus two 40 bit halves of the randomness. Compare with Compare, Equal and Less.
New, NewString, NewBatch
Ids from the default generator. Strictly increasing in one process, safe from any number of threads.
Generator
The monotonic generator of the specification, one lock around the last id. NewGeneratorWith takes your clock and entropy.
Parse, String
Text in and out. Bytes and FromBytes give the 16 bytes, also the bytes of a UUID.
FromParts
A time and 10 given bytes: no randomness, for exact tests.
MinAt, MaxAt
The first and the last id of a millisecond, the bounds of a range query.
Make, print and read back
New gives the next id of the default generator and String writes the 26 characters. NewAt makes an id for a time you choose. Every id is a value: copy it, compare it, keep it in a struct.
encoding-ulid-guide-basics.salam
import encoding.ulid
funcmain:
id := ulid.New()
text := ulid.String(id)
println"length:", text.Len()
back := ulid.Parse(text)
println"round trip:", back.ok and ulid.Equal(back.id, id)
println"close to now:", ulid.Time(id) - ulid.Now() < 5000
stamp := ulid.NewAt(1469918176385)
println ulid.String(stamp.id).Len(), ulid.Time(stamp.id)
end
Output
length: 26
round trip: true
close to now: true
26 1469918176385
Parsing and the rules of the text
Parse follows the specification: lowercase and the aliases I, L and O are accepted, U is not, and the first character may not be above 7 because the value would not fit in 128 bits. ParseStrict wants exactly what String writes. Errors are codes, with ErrorText for a message.
01ARYZ6S41TSV4RRFFQ69G5FAV -> 1469918176385 01ARYZ6S41TSV4RRFFQ69G5FAV
01aryz6s41tsv4rrffq69g5fav -> 1469918176385 01ARYZ6S41TSV4RRFFQ69G5FAV
O1ARYZ6S41TSV4RRFFQ69G5FAV -> 1469918176385 01ARYZ6S41TSV4RRFFQ69G5FAV
7ZZZZZZZZZZZZZZZZZZZZZZZZZ -> 281474976710655 7ZZZZZZZZZZZZZZZZZZZZZZZZZ
80000000000000000000000000 -> ULID value is larger than 7ZZZZZZZZZZZZZZZZZZZZZZZZZ
01ARYZ6S41TSV4RRFFQ69G5FAU -> invalid character in ULID
01ARYZ6S41 -> a ULID is 26 characters
false
true
Order and range queries
Text order is time order, so ids sort by a plain string sort. To select the ids of a time window ask for everything between MinAt(start) and MaxAt(end); in SQL that is a BETWEEN on the id column.
encoding-ulid-guide-order.salam
import encoding.ulid
funcmain:
mut ids := Vector {} asVector<ulid.ULID>
defer ids.Free()
mut mark := 1700000000000asi64repeat4:
ids.Push(ulid.MinAt(mark))
mark += 1500endrepeat ids.Len() in i:
println ulid.String(ids.Get(i))
end
low := ulid.MinAt(1700000001000)
high := ulid.MaxAt(1700000003000)
println"range:", ulid.String(low), ulid.String(high)
repeat ids.Len() in i:
inside := ulid.Compare(ids.Get(i), low) >= 0and ulid.Compare(ids.Get(i), high) <= 0println i, inside
endend
Two ids made in the same millisecond must still sort in the order they were made. A Generator does what the specification says: in a new millisecond it draws fresh randomness, in the same one it adds 1 to the last random part, and when the clock moves back it keeps the last timestamp. If the 80 bits ever overflow, the timestamp moves one millisecond ahead instead of failing. The example uses a fake clock and a fixed entropy function so every character is known.
encoding-ulid-guide-monotonic.salam
import encoding.ulid
mut now_ms := 1000asi64mut chunk := 7asi64funcclock(): i64:
ret now_ms
endfuncsource(): i64:
ret chunk
endfuncmain:
g := ulid.NewGeneratorWith((): retclock() end, (): retsource() end)
defer ulid.Free(g)
repeat3:
println ulid.String(ulid.Next(g).id)
end
now_ms = 1001
chunk = 9println ulid.String(ulid.Next(g).id)
now_ms = 900
last := ulid.Next(g)
println"clock went back:", ulid.Time(last.id), ulid.String(last.id)
println ulid.String(ulid.Increment(last.id).id)
end
Output
00000000Z80000000700000007
00000000Z80000000700000008
00000000Z80000000700000009
00000000Z90000000900000009
clock went back: 1001 00000000Z9000000090000000A
00000000Z9000000090000000B
Many threads
The default generator and every Generator guard their state with a mutex, so threads share one without duplicates and without going out of order: every thread sees its own ids increase, and all ids together are distinct. NewBatch takes the lock once for n ids. The cost is one lock and one clock read per id.
encoding-ulid-guide-threads.salam
import encoding.ulid
import pool
import mem
const WORKERS := 8const EACH := 500funcmain:
out := mem.AllocateZeroed((WORKERS * EACH * 3 * 8) asu64) asi64*
shared := ulid.Default()
pool.ParallelFor(
WORKERS asi64, 4asi64, (task: i64):
repeat EACH in k:
id := ulid.New()
slot := ((task * EACH + k) * 3) asint
out[slot] = id.time
out[slot + 1] = id.hi
out[slot + 2] = id.lo
endend
)
mut seen := HashMap {} asHashMap<str, bool>
defer seen.Free()
repeat WORKERS * EACH in n:
id := ulid.ULID { time = out[n * 3], hi = out[n * 3 + 1], lo = out[n * 3 + 2] }
seen.Put(ulid.String(id), true)
endprintln"ids:", WORKERS * EACH, "distinct:", seen.Size()
println ulid.Last(shared).ok
mem.Free(out asvoid*)
end
Output
ids: 4000 distinct: 4000
true
When the random source fails
The built in source reads the operating system random generator through crypto.RandomBytes, which stops the program if the system cannot give random bytes: a weak id is never made. A source of your own, passed to NewGeneratorWith, can fail politely by returning a negative number. Next then returns ERR_ENTROPY and leaves the generator untouched, so the next call can succeed.
encoding-ulid-guide-entropy.salam
import encoding.ulid
mut failing := truefuncclock(): i64:
ret5000endfuncsource(): i64:
if failing:
ret -1endret123456endfuncmain:
g := ulid.NewGeneratorWith((): retclock() end, (): retsource() end)
defer ulid.Free(g)
r := ulid.Next(g)
println r.ok, r.err == ulid.ERR_ENTROPY, ulid.ErrorText(r.err)
println"state untouched:", ulid.Last(g).ok
failing = false
ok := ulid.Next(g)
println ok.ok, ulid.String(ok.id)
end
Output
false true the entropy source failed
state untouched: false
true 00000004W800003RJ000003RJ0
Bytes, UUIDs and fixed ids
Bytes gives 16 bytes, big endian, the same size as a UUID, and FromBytes reads them back; the package does not depend on a UUID type, only on the bytes. FromParts builds an id from a time and 10 bytes you pick, which is how tests get exact answers. Free the byte vectors.
encoding-ulid-guide-bytes.salam
import encoding.ulid
importstrfunchex(data: Vector<u8>): str:
digits := "0123456789abcdef"mut out := ""repeat data.Len() in i:
code := data.Get(i) asint
out = out + str.Substr(digits, code / 16, 1) + str.Substr(digits, code % 16, 1)
endret out
endfuncmain:
r := ulid.Parse("01ARYZ6S41TSV4RRFFQ69G5FAV")
raw := ulid.ToUUIDBytes(r.id)
defer raw.Free()
println raw.Len(), hex(raw)
back := ulid.FromUUIDBytes(raw)
println back.ok, ulid.String(back.id)
mut seed := Vector {} asVector<u8>
defer seed.Free()
repeat10in i:
seed.Push((i * 3) asu8)
end
made := ulid.FromParts(1469918176385, seed)
println ulid.String(made.id)
part := ulid.Entropy(made.id)
defer part.Free()
printlnhex(part)
end
A 128 bit identifier: a 48 bit millisecond timestamp and 80 random bits. It is a plain value, copy it freely. Ids compare in the same order as their times.
Name
Type
Description
time
i64 = 0
The timestamp in milliseconds since the Unix epoch.
A monotonic generator. It owns a lock and its last id, so the copies of one Generator share state and any number of threads may call it. Release it with Free.
Name
Type
Description
state
i64*
The shared last timestamp and random parts, behind the lock.
mu
sync.Mutex
The lock that guards the state.
clock
func(): i64
The function that returns the current time in milliseconds.
entropy
func(): i64
The function that returns 40 random bits, or a negative number when it fails.
encoding-ulid-Next.salam
import encoding.ulid
mut tick := 100asi64funcclock(): i64:
ret tick
endfuncsource(): i64:
ret1endfuncmain:
g := ulid.NewGeneratorWith((): retclock() end, (): retsource() end)
defer ulid.Free(g)
first := ulid.Next(g)
second := ulid.Next(g)
println ulid.String(first.id)
println ulid.String(second.id)
println ulid.Less(first.id, second.id)
forced := ulid.NextAt(g, 50)
println ulid.Time(forced.id), ulid.Less(second.id, forced.id)
end
The largest timestamp a ULID can hold, 281474976710655 milliseconds (48 bits), which is the year 10889.
encoding-ulid-Errors.salam
import encoding.ulid
funcmain:
each code in [
ulid.OK, ulid.ERR_LENGTH, ulid.ERR_CHAR, ulid.ERR_OVERFLOW, ulid.ERR_TIME, ulid.ERR_ENTROPY,
ulid.ERR_BYTES, 99
]:
println code, ulid.ErrorText(code)
end
r := ulid.Parse("short")
println r.ok, r.err, ulid.IsZero(r.id)
println ulid.MAX_TIME
top := ulid.MaxAt(ulid.MAX_TIME)
println top.time, top.hi, top.lo
end
Output
0 ok
1 a ULID is 26 characters
2 invalid character in ULID
3 ULID value is larger than 7ZZZZZZZZZZZZZZZZZZZZZZZZZ
4 timestamp is outside 0 to 281474976710655
5 the entropy source failed
6 wrong number of bytes
99 unknown error
false 1 true
281474976710655
281474976710655 1099511627775 1099511627775
A new id from the default generator, using the system clock and the operating system random source. Ids from one process are strictly increasing, even from many threads at once.
An id for a chosen millisecond with fresh random bits. It keeps no state, so two calls in one millisecond are not ordered; use a Generator when order matters. Fails with ERR_TIME outside 0 to MAX_TIME.
A generator with your own clock and entropy functions, for tests and for sources that can fail. The entropy function returns 40 random bits (0 to 1099511627775) or a negative number on failure, which makes Next report ERR_ENTROPY.
The next id of a generator. In a new millisecond the random part is fresh; in the same millisecond, or when the clock went back, the previous random part grows by one. If the 80 bits run out the timestamp moves one millisecond ahead. Safe from many threads.