Nanoid.Alphabet (Nanoid v3.0.0-rc.2)

Copy Markdown View Source

Validation and normalisation of the inputs accepted by the generators.

This module centralises the checks for the two generator options:

Both functions are pure and never raise: they return {:ok, value} on success or :error on invalid input, leaving the decision of how to react (raise, fall back to a default, …) to the caller.

Alphabets may be given as a binary (e.g. "abcdef") or a charlist (e.g. ~c"abcdef"). Multi-byte graphemes such as "äöü" or emoji are supported, since the alphabet is split with String.graphemes/1 rather than by byte.

Summary

Functions

Converts an alphabet into a tuple of graphemes for O(1) symbol lookup.

Validates a requested ID size.

Functions

convert_alphabet(alphabet)

@spec convert_alphabet(binary() | charlist()) :: {:ok, tuple()} | :error

Converts an alphabet into a tuple of graphemes for O(1) symbol lookup.

Returns {:ok, tuple} when the alphabet contains at least two symbols, or :error otherwise. Charlists are converted via List.to_string/1, which is Unicode-aware.

Examples

iex> Nanoid.Alphabet.convert_alphabet("abc")
{:ok, {"a", "b", "c"}}

iex> Nanoid.Alphabet.convert_alphabet(~c"abc")
{:ok, {"a", "b", "c"}}

iex> Nanoid.Alphabet.convert_alphabet("äöü")
{:ok, {"ä", "ö", "ü"}}

iex> Nanoid.Alphabet.convert_alphabet("a")
:error

iex> Nanoid.Alphabet.convert_alphabet("ä")
:error

validate_size(size)

@spec validate_size(term()) :: {:ok, pos_integer()} | :error

Validates a requested ID size.

Returns {:ok, size} for a positive integer, or :error otherwise.

Examples

iex> Nanoid.Alphabet.validate_size(16)
{:ok, 16}

iex> Nanoid.Alphabet.validate_size(0)
:error

iex> Nanoid.Alphabet.validate_size(-5)
:error

iex> Nanoid.Alphabet.validate_size("16")
:error