Using Dream UUID
Dream UUID makes, reads and prints every kind of UUID in RFC 9562, on Erlang and on JavaScript, and any 16 bytes are a valid Uuid. This guide tells which version to use, how the text forms work, how v7 keeps its order, and how to use a Uuid with gleam/time, youid and PostgreSQL.
Which version to use
| Version | Function | Use it for | Order |
|---|---|---|---|
| v7 | v7() | New IDs of rows and records. The default choice. | Each new v7 sorts after the one before it, on one BEAM node or in one JavaScript realm. |
| v4 | v4() | IDs that must not show a time. | None. 122 random bits. |
| v5 | v5(namespace, name) | The same ID for the same name, each time. | None. |
| v3 | v3(namespace, name) | The same as v5, for systems that use MD5. | None. |
| v6 | v6() | Systems that read v1 fields and sort by time. | Each new v6 or v1 has a later time than the one before it. |
| v1 | v1() | Systems that need v1. | The time is in a field order that does not sort. |
| v8 | v8(bytes) | Your own layout of 122 bits. | Your layout. |
RFC 9562 section 5.7 recommends v7 over v1 and v6.
Parse and print
from_string reads the canonical form: 8-4-4-4-12 hexadecimal digits. The digits can be uppercase, lowercase or mixed. to_string prints lowercase.
Make an ID and read one 
import dream_uuid.{type ParseError, type Uuid, from_string, to_string, v7}
/// A new ID for a row, as text. Each new ID sorts after the one before it.
pub fn new_id() -> String {
v7() |> to_string
}
/// The ID in a request path, or why the text is not a UUID.
pub fn read_id(text: String) -> Result(Uuid, ParseError) {
from_string(text)
}
Each function reads one form of the RFC. Every other form gets an exact error:
| Input | Example | from_string | from_urn |
|---|---|---|---|
| Canonical | f81d4fae-7dec-11d0-a765-00a0c91e6bf6 | accepted | MissingUrnPrefix |
| Uppercase or mixed case | F81D4FAE-7DEC-11D0-A765-00A0C91E6BF6 | accepted | MissingUrnPrefix |
| URN | urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6 | WrongLength(45) | accepted |
| Braces | {f81d4fae-7dec-11d0-a765-00a0c91e6bf6} | WrongLength(38) | MissingUrnPrefix |
| 32 digits, no hyphens | f81d4fae7dec11d0a76500a0c91e6bf6 | WrongLength(32) | MissingUrnPrefix |
| A hyphen in another position | f81d-4fae7dec-11d0-a765-00a0c91e6bf6 | InvalidCharacter(4, "-") | MissingUrnPrefix |
| A space at an end | " f81d4fae-7dec-11d0-a765-00a0c91e6bf6" | WrongLength(37) | MissingUrnPrefix |
RFC 9562 does not define braces or the 32-digit form, so Dream UUID refuses them. If your input has braces, remove them before you call from_string.
The urn:uuid: prefix is not case-sensitive. A position in an error of from_urn counts from the start of the URN, and WrongLength gives the length of the whole text.
ParseError has three cases, so a handler can give an exact message:
Explain a parse error 
import dream_uuid.{
type ParseError, InvalidCharacter, MissingUrnPrefix, WrongLength,
}
import gleam/int.{to_string}
/// A message for a developer about text that is not a UUID.
pub fn explain(error: ParseError) -> String {
case error {
WrongLength(length:) ->
"a UUID has 36 characters, and this text has " <> to_string(length)
InvalidCharacter(position:, character:) ->
"the character "
<> character
<> " at position "
<> to_string(position)
<> " is not permitted"
MissingUrnPrefix -> "a URN starts with urn:uuid:"
}
}
The 16 bytes are the other form. from_bit_array accepts each 16-byte value and refuses each other size with SizeError(expected_bits: 128, bits: size). to_bit_array gives the bytes in network byte order.
The fixed values
nil: 128 zero bits (section 5.9).is_nilis true for it only.max: 128 one bits (section 5.10).is_maxis true for it only.namespace_dns,namespace_url,namespace_oidandnamespace_x500: the namespaces of section 6.6, for v3 and v5.
Make the same ID for the same name 
import dream_uuid.{type Uuid, namespace_url, v5}
/// The same ID for the same URL, on each run and on each machine.
pub fn id_of_url(url: String) -> Uuid {
v5(namespace_url, url)
}
v3_bytes and v5_bytes take a name that is bytes. A name that is not whole bytes gives a SizeError.
Read the fields
versiongives the version nibble, as it is stored, for each variant. The nibbles 0 and 9 to 15 giveUnknown(nibble). The nil UUID givesUnknown(0), and the max UUID givesUnknown(15).variantgivesNcs,Rfc,MicrosoftorFuture.compareorders two UUIDs by their bytes, as unsigned values, from the left. PostgreSQL orders auuidcolumn the same way.unix_milliseconds,unix_seconds_and_nanoseconds,clock_sequenceandnoderead a v1, v6 or v7 UUID of the RFC variant. They giveNonefor each other UUID.
Build a UUID from its fields
v1_from, v6_from and v7_from take the fields of a version, and refuse a field that is out of its range with a FieldError. A JavaScript number holds an integer exactly only up to 2^53. Thus each field that has more than 53 bits is a bit array: the 60-bit timestamp of v1 and v6, and the 62-bit rand_b of v7. Write a large value as parts of 32 bits or less, so that it is exact on both targets:
Build the v7 vector of the RFC 
import dream_uuid.{type FieldError, type Uuid, v7_from}
/// The v7 UUID of RFC 9562 Appendix A.6. `rand_b` has 62 bits, more than a
/// JavaScript number holds exactly, so it is a bit array of two parts.
pub fn rfc_v7() -> Result(Uuid, FieldError) {
v7_from(unix_milliseconds: 0x017F22E279B0, rand_a: 0xCC3, rand_b: <<
0x18C4DC0C:30,
0x0C07398F:32,
>>)
}
v4_from and v8 take 16 bytes of the caller. They set the version and the variant bits, and keep the other 122 bits.
How v7 keeps its order
v7 uses method 3 of RFC 9562 section 6.2. The 60 bits after the start are the Unix time: 48 bits of milliseconds, then a 12-bit fraction of the millisecond. The last 62 bits are new random bits for each UUID.
A counter holds the last 60-bit time. Each new v7 gets the clock time, or the last time plus one step (1/4096 ms), whichever is larger. Thus:
- Order. Each new v7 sorts after each earlier v7 on the same BEAM node, or in the same JavaScript realm. This is true for all processes together, with no limit for each millisecond.
- Bursts. Above 4,096 UUIDs in one millisecond, the time goes ahead of the clock by one step for each more UUID. RFC 9562 section 6.2 permits this. The clock gets ahead of the counter again when the rate goes down.
- A clock that goes back. The counter never goes back. The UUIDs continue from the last time, one step each, until the clock passes the counter.
- A restart. The counter does not survive a restart. If the clock went back during the restart, a new UUID can sort before an old one. The 62 random bits still make a collision improbable.
- Many nodes. Each BEAM node, and each JavaScript realm (each worker), has its own counter. The order holds in each, not between them.
On Erlang, the counter is an unsigned 64-bit atomic in a persistent term, made one time when the module loads. A compare-and-exchange keeps it correct when many processes call v7 at the same time. There is no process to start or to supervise. The clock is os:system_time/1, with steps of 1 ns.
On JavaScript, the counter is a BigInt at module level, so no value above 2^53 is ever a JavaScript number. The clock is Date.now(), with steps of 1 ms, so the fraction is 0 and the counter gives the order inside one millisecond.
v7_at(milliseconds) makes a v7 UUID for a given time, with 74 random bits. Use it for old records. It gives no order between two calls with the same time.
v1 and v6
v1 and v6 use one counter of 100 ns steps from 1582-10-15, in the same way as v7. Thus each new v1 or v6 has a later time than the one before it.
- The node of v1 is 48 random bits with the multicast bit set (RFC 9562 section 6.10). The clock sequence of v1 is 14 random bits. Both are made one time when the module loads. It never reads a MAC address.
- Each v6 gets a new random clock sequence and a new random node, with the multicast bit set, as RFC 9562 section 5.6 recommends.
Time fields with gleam/time
unix_seconds_and_nanoseconds gives the pair that gleam/time takes. Dream UUID depends only on gleam_stdlib, so add gleam_time to your project for this:
Read the time of a UUID 
import dream_uuid.{type Uuid, unix_seconds_and_nanoseconds}
import gleam/option.{type Option, map}
import gleam/time/timestamp.{type Timestamp, from_unix_seconds_and_nanoseconds}
/// The time of a v1, v6 or v7 UUID, as a `gleam/time` timestamp. `None`
/// for each other UUID.
pub fn created_at(uuid: Uuid) -> Option(Timestamp) {
unix_seconds_and_nanoseconds(uuid)
|> map(fn(time) { from_unix_seconds_and_nanoseconds(time.0, time.1) })
}
youid
Dream UUID has no dependency on youid. The text form carries each 128-bit value, so two functions convert in both directions. Copy them into your app:
Convert to and from youid 
import dream_uuid.{type ParseError}
import youid/uuid as youid
/// A youid UUID from a dream_uuid UUID. The text form carries each
/// 128-bit value. `youid.from_bit_array` refuses some of them.
pub fn to_youid(uuid: dream_uuid.Uuid) -> Result(youid.Uuid, Nil) {
uuid |> dream_uuid.to_string |> youid.from_string
}
/// A dream_uuid UUID from a youid UUID.
pub fn from_youid(uuid: youid.Uuid) -> Result(dream_uuid.Uuid, ParseError) {
uuid |> youid.to_string |> dream_uuid.from_string
}
youid.from_bit_array refuses the nil UUID, the max UUID, v6, v8 and the versions 9 to 14. Thus the conversion goes through the text. The tests of Dream UUID convert 1,000 random values, nil, max, and the v1, v6 and v8 vectors both ways.
PostgreSQL
dream_postgres reads and writes a uuid column as a dream_uuid.Uuid, through the 16 bytes of the binary protocol. Each value that PostgreSQL holds, the nil UUID and the max UUID too, goes in and comes out with the same bits. compare gives the same order as an ORDER BY on the column.
Erlang and JavaScript
Dream UUID is pure Gleam, with one Erlang file and one JavaScript file for random bits, clocks and the counters.
- Random bits come from
crypto:strong_rand_bytes/1on Erlang and fromcrypto.getRandomValueson JavaScript. On Erlang,cryptoraiseslow_entropywhen the operating system has no entropy. Dream UUID does not catch it, because a UUID from weak random bits is worse than a crash. - Hashes. v3 and v5 use
erlang:md5/1andcrypto:hash/2on Erlang. A browser has no synchronous hash, so on JavaScript v3 and v5 use MD5 and SHA-1 in pure Gleam. The tests compare the Gleam code with Erlang for each input length from 0 to 200 bytes. - Integers. The 128 bits are four words of 32 bits, and each value in the arithmetic stays below 2^53. Thus no value loses bits on JavaScript.
The tests use dream_test and run on the BEAM. Line coverage is measured on the BEAM only. The dream_test runner does not run on JavaScript, so CI compiles the package for JavaScript but does not run the tests there.