block-id
block-id
is a Rust library for generating opaque, unique, and short string values from (unsigned) integers.
tl;dr:
use ;
Introduction
Random-looking alphanumeric strings are often used in place of sequential numeric IDs for user-facing purposes. This has several advantages:
- String identifiers are usually visually distinct, even if they were generated adjacently in sequence.
- The higher information density of a larger alphabet allows for shorter codes.
- Sequential identifiers reveal unnecessary information about ordering and object creation rate that you may not want to reveal.
block-id
is the successor to tiny_id
, which allows the creation of tightly-packed alphanumeric strings. tiny_id
turned out to be difficult to use in a distributed environment because its state needs to be synchronized across every node that needs to generate IDs. Rather than building distributed functionality into a short ID generator, block-id
provides a way of turning a sequential ID generator into a string ID generator by creating a one-to-one mapping between integers and random-looking short strings. That way, any system of generating sequential numeric IDs (for example, a database's sequence generator) can be turned into a system for generating random-looking string IDs.
use ;
How it works
block-id
applies a pipeline of reversible transformations on a data in order to turn it into a string.
- Base conversion turns the input integer into a base-N representation where N is the number of characters in the desired output alphabet.
- Rounds consisting of:
- Permutation applies an N-to-N map to every digit of the base-N representation. The permutation is generated from the random seed passed in the
BlockId
constructor. - Cascade applies a left-to-right cumulative sum, modulo N, to the base-N representation.
- Rotate takes the first digit of the base-N representation and moves it to the last digit, shifting all of the other digits left by one.
- Permutation applies an N-to-N map to every digit of the base-N representation. The permutation is generated from the random seed passed in the
- Alphabetization translates every digit of the base-N representation to a “letter” in the alphabet provided at construction.
The number of rounds is the same as the number of digits in the base-N representation. This gives every digit a chance to influence every other digit.
Security
block-id
is designed to make it easy for a human to distinguish between two sequential codes, not to make it impossible for an adversary to reverse. It should not be considered cryptographically secure.