ShortUUID.Builder (ShortUUID v4.3.0)

Copy Markdown View Source

ShortUUID.Builder is a module for encoding and decoding UUIDs (Universally Unique Identifiers) using various predefined or custom alphabets.

Usage

To create your module, simply use it and optionally provide an alphabet option:

defmodule MyModule do
  use ShortUUID.Builder, alphabet: :base58
end

The alphabet option must be one of the predefined alphabets or a custom string of 16 to 256 unique characters.

Alphabets are not required to be URL-safe. Custom alphabets may contain any characters, including ones with a special meaning in URLs. All predefined alphabets are URL-safe except :base64, which uses + and /; use :base64_url if you need URL-safe base64.

The alphabet is split into characters by grapheme, but encoded strings are matched by exact codepoints, so characters that visually merge when concatenated (combining marks, regional indicators, emoji modifiers) are supported. No character may be a prefix of another one, characters must be in Unicode NFC form, and alphabets that could make a Unicode-normalized ID decode to a different UUID are rejected.

Predefined Alphabets

The following predefined alphabets are available:

  • :base57_shortuuid - "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
  • :base32 - "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
  • :base32_crockford - "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
  • :base32_hex - "0123456789ABCDEFGHIJKLMNOPQRSTUV"
  • :base32_z - "ybndrfg8ejkmcpqxot1uwisza345h769"
  • :base58 - "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
  • :base62 - "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  • :base64 - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
  • :base64_url - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"

Functions

The following functions are available for encoding and decoding UUIDs:

  • encode/1 - Encodes a UUID using the specified or default alphabet.
  • encode!/1 - Encodes a UUID using the specified or default alphabet, raising an error on failure.
  • decode/1 - Decodes a string into a UUID using the specified or default alphabet.
  • decode!/1 - Decodes a string into a UUID using the specified or default alphabet, raising an error on failure.
  • __shortuuid__/0 - Describes the module: alphabet, base, encoded length and canonical: true. See ShortUUID.Behaviour.__shortuuid__/0.

Example

iex> ShortUUID.encode("550e8400-e29b-41d4-a716-446655440000")
{:ok, "H9cNmGXLEc8NWcZzSThA9S"}

iex> ShortUUID.decode("H9cNmGXLEc8NWcZzSThA9S")
{:ok, "550e8400-e29b-41d4-a716-446655440000"}