#unique-id #id-generator #random #short #stack #tiny #url-friendly

pillid

A tinier, prefixed, URL-friendly, time-sortable, unique ID storable on the stack

6 releases

0.3.1 Sep 30, 2024
0.3.0 Mar 17, 2024
0.2.0 Nov 30, 2023
0.1.5 Nov 30, 2023

#22 in #short

Download history 4/week @ 2024-09-19 185/week @ 2024-09-26 26/week @ 2024-10-03 5/week @ 2024-10-10

424 downloads per month

MIT license

15KB
305 lines

pillid

Random, short collision-resistant IDs in Rust.


lib.rs:

A tiny, secure, URL-friendly, prefixed (optional), timestamped (optional), unique string ID generator

Safe. It uses cryptographically strong random APIs and guarantees a proper distribution of symbols.

Compact. It uses a larger alphabet than UUID (A-Za-z0-9) and has more unique IDs in just 22 symbols instead of 36.

[dependencies]
pillid = "0.4.0"
use pillid::pillid;

fn main() {
   let id = pillid!(); //=> "cNbQxzR55W2RbkPoERACA"
}

Usage

Simple

The main module uses URL-friendly symbols (A-Za-z0-9) and returns an ID with 22 characters (equivalent to 128 random bits).

use pillid::pillid;

fn main() {
   let id = pillid!(); //=> "cNbQxzR55W2RbkPoERACA"
}

Custom length

If you want to reduce ID length (and increase collisions probability), you can pass the length as an argument generate function:

use pillid::pillid;

fn main() {
   let id = pillid!(10); //=> "QhpvygNybI"
}

Custom Alphabet or Length

If you want to change the ID's alphabet or length you can use the low-level custom module.

use pillid::pillid;

fn main() {
    let alphabet: [char; 16] = [
        '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f'
    ];

   let id = pillid!(10, &alphabet); //=> "f42ega7402"
}

Alphabet must contain 256 symbols or less. Otherwise, the generator will not be secure.

Custom Random Bytes Generator

You can replace the default safe random generator using the complex module. For instance, to use a seed-based generator.

use pillid::pillid;

fn random_byte () -> u8 {
    0
}

fn main() {
    fn random (size: usize) -> Vec<u8> {
        let mut bytes: Vec<u8> = vec![0; size];

        for i in 0..size {
            bytes[i] = random_byte();
        }

        bytes
    }

    pillid!(10, &['a', 'b', 'c', 'd', 'e', 'f'], random); //=> "fbaefaadeb"
}

random function must accept the array size and return an vector with random numbers.

If you want to use the same URL-friendly symbols with format, you can get the default alphabet from the url module:

use pillid::pillid;

fn random (size: usize) -> Vec<u8> {
    let result: Vec<u8> = vec![0; size];

    result
}

fn main() {
    pillid!(10, &pillid::alphabet::DEFAULT, random); //=> "93celLtuub"
}

Dependencies

~240–340KB