nanoid only.Expand description
§NanoID generation
URL-safe random strings of configurable length over a configurable
alphabet. The default alphabet is the 64-character URL-safe set
(A-Z, a-z, 0-9, _, -) and the default length is 21 —
the same defaults as the original JavaScript reference, giving
roughly 1 trillion years to a 1 % collision probability at 1000
IDs/second.
use id_forge::nanoid;
let id = nanoid::generate();
assert_eq!(id.len(), 21);
let short = nanoid::with_length(8);
assert_eq!(short.len(), 8);
let hex = nanoid::custom(16, b"0123456789abcdef");
assert_eq!(hex.len(), 16);
assert!(hex.chars().all(|c| "0123456789abcdef".contains(c)));§Bias-free selection
NanoID picks each character by drawing bits from the shared xoshiro256** generator, masking to the smallest power of two that covers the alphabet, and rejecting indices that fall above the alphabet’s size. For a 64-character alphabet the acceptance rate is 100 %; for a 17-character alphabet it’s 17/32 = 53 %. Either way, every character of the alphabet has identical probability of being chosen.
The 0.1.0 placeholder used a linear congruential generator with
byte % alphabet.len(), which biased the result whenever the
alphabet size was not a power of two. 0.9.3 fixes that.
§Randomness quality
The bit source is the same fast non-cryptographic generator
used by uuid and ulid. NanoIDs from this crate are suitable
for collision-resistant identifiers, not session tokens.
Enums§
- Alphabet
Error - Error returned by
try_customandvalidate_alphabet.
Constants§
- DEFAULT_
ALPHABET - Default alphabet: URL-safe, 64 characters (
_-+ alphanumeric). - DEFAULT_
LENGTH - Default length: 21 characters.
Functions§
- custom
- Generate a NanoID with a custom length and alphabet.
- generate
- Generate a NanoID using the default alphabet and length.
- try_
custom - Strict counterpart to
custom: validates the alphabet first. - validate_
alphabet - Verify that an alphabet is non-empty and free of duplicate bytes.
- with_
length - Generate a NanoID of the given length using the default alphabet.