sqid
Types
An alphabet that can be used to encode and decode Sqids.
The alphabet used to encode numbers determines which characters can be used
in their string representation.
You can build one using the alphabet function.
Examples
If you want Sqids that only contains lowercase letters you can define an alphabet like this:
let assert Ok(alphabet) =
sqid.alphabet("abcdefghijklmnopqrstuvwxyz")
pub opaque type Alphabet
Values
pub fn alphabet(string: String) -> Result(Alphabet, Nil)
Creates a new alphabet from the letters making up the given string. An alphabet is what defines what characters can end up in a generated Sqid.
This function will fail if:
- The alphabet has less than 3 characters
- The alphabet contains repeated characters
- The alphabet has multi-byte characters
Examples
If you want Sqids that only contains lowercase letters you can define an alphabet like this:
let assert Ok(alphabet) =
sqid.alphabet("abcdefghijklmnopqrstuvwxyz")
assert Error(Nil) == sqid.alphabet("wibble")
as "wrong alphabet: it contains duplicates"
assert Error(Nil) == sqid.alphabet("dziękuję")
as "wrong alphabet: it contains non ascii characters"
assert Error(Nil) == sqid.alphabet("01")
as "wrong alphabet: it contains less than 3 characters"
pub fn decode(
options: Options,
sqid: String,
) -> Result(List(Int), Nil)
Decodes a Sqid into the list of integers that was used to generate it. To decode a Sqid, always use the same options that were used to encode it, otherwise you will get nonsense results!
This function will fail if the Sqid has carachters that are not allowed by these options, meaning that the Sqid was encoded with a different alphabet.
pub fn encode(
options: Options,
numbers: List(Int),
) -> Result(String, Nil)
Encodes a list of numbers into a readable string using the given options. This function might fail if it’s not possible to generate a string that is not excluded by the options’ blocklist.
pub fn new(alphabet: Alphabet) -> Options
Creates an Options object from a valid alphabet.
Options determine how Sqids are encoded and decoded.
If you want to change the generated Sqids you can also use:
set_minimum_length: to pick a minimum length for the generated Sqids.set_blocklist: to specify a blocklist of words that will not end up in any of the generated Sqids.
pub fn set_blocklist(
options: Options,
blocklist: List(String),
) -> Options
Sets the list of blocked words that cannot appear inside any of the generated Sqids. This is useful if you want to make sure a generated Sqid cannot contain profanities.
There’s a couple of things to note:
- The blocklist is case insensitive. If
"gleam"is a blocked word, generated Sqids will not contain any of"gLeaM","GLEAM","GLeam", … and so on. - All words in the blocklist must be more than three characters long, any word shorter than that will be ignored.