Skip to content

new_short_id

A short id of len characters drawn from an Alphabet with the operating system’s random source, every character equally likely.

Needs the random-entropy feature. Bytes that would favor some characters (256 is rarely a multiple of the alphabet size) are discarded, not folded with a modulo. The result carries len × log2(size) bits of randomness: 21 characters of url_safe give 126 bits, as much as a UUID.

use helpers4::id::new_short_id;

Cargo feature id (enabled by default). To compile only this module:

cargo add helpers4 --no-default-features --features id

or in Cargo.toml:

[dependencies]
helpers4 = { version = "0.0.9", default-features = false, features = ["id"] }
pub fn new_short_id(alphabet: &Alphabet, len: usize) -> Result<String, EntropyError>
ParameterTypeDescription
alphabet&AlphabetThe characters to draw from.
lenusizeThe number of characters.

Result<String, EntropyError> — A string of len characters.

Returns an EntropyError when the operating system cannot provide random bytes.

use helpers4::id::{new_short_id, Alphabet};

let id = new_short_id(&Alphabet::url_safe(), 21)?;
assert_eq!(id.chars().count(), 21);

src/id/new_short_id.rs