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

VersionFunctionUse it forOrder
v7v7()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.
v4v4()IDs that must not show a time.None. 122 random bits.
v5v5(namespace, name)The same ID for the same name, each time.None.
v3v3(namespace, name)The same as v5, for systems that use MD5.None.
v6v6()Systems that read v1 fields and sort by time.Each new v6 or v1 has a later time than the one before it.
v1v1()Systems that need v1.The time is in a field order that does not sort.
v8v8(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 Tested snippet

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:

InputExamplefrom_stringfrom_urn
Canonicalf81d4fae-7dec-11d0-a765-00a0c91e6bf6acceptedMissingUrnPrefix
Uppercase or mixed caseF81D4FAE-7DEC-11D0-A765-00A0C91E6BF6acceptedMissingUrnPrefix
URNurn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6WrongLength(45)accepted
Braces{f81d4fae-7dec-11d0-a765-00a0c91e6bf6}WrongLength(38)MissingUrnPrefix
32 digits, no hyphensf81d4fae7dec11d0a76500a0c91e6bf6WrongLength(32)MissingUrnPrefix
A hyphen in another positionf81d-4fae7dec-11d0-a765-00a0c91e6bf6InvalidCharacter(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 Tested snippet

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

Make the same ID for the same name Tested snippet

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

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 Tested snippet

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:

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.

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 Tested snippet

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 Tested snippet

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.

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.

✨ Search Document