| Crates.io | cuid2-rs |
| lib.rs | cuid2-rs |
| version | 0.1.0 |
| created_at | 2025-03-08 18:11:14.707262+00 |
| updated_at | 2025-03-08 18:11:14.707262+00 |
| description | Collision-resistant unique ids. |
| homepage | https://github.com/OnlyF0uR/cuid2-rs |
| repository | https://github.com/OnlyF0uR/cuid2-rs |
| max_upload_size | |
| id | 1584699 |
| size | 23,065 |
A Rust implementation of CUID2 (Collision-resistant Unique IDentifiers) - secure, short, URL-friendly unique string IDs.
Add this to your Cargo.toml:
[dependencies]
cuid2-rs = "0.1.0"
use cuid2_rs::generate;
fn main() {
// Generate a CUID with default length (24 characters)
let id = generate().unwrap();
println!("Generated CUID: {}", id);
// Example output: "a1b2c3d4e5f6g7h8i9j0k1l2m3"
}
use cuid2_rs::generate_cuid;
fn main() {
// Generate a shorter CUID (10 characters)
let short_id = generate_cuid(10).unwrap();
println!("Short CUID: {}", short_id);
// Example output: "a1b2c3d4e5"
// Generate a longer CUID (32 characters)
let long_id = generate_cuid(32).unwrap();
println!("Long CUID: {}", long_id);
// Example output: "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8"
}
use cuid2_rs::{is_valid_cuid, MIN_LENGTH, MAX_LENGTH};
fn main() {
let id = "a1b2c3d4e5";
let is_valid = is_valid_cuid(id, MIN_LENGTH, MAX_LENGTH);
println!("Is valid CUID: {}", is_valid);
// Invalid CUID (starts with a number)
let invalid_id = "1abc123";
let is_valid = is_valid_cuid(invalid_id, MIN_LENGTH, MAX_LENGTH);
assert!(!is_valid);
}
CUID2 generates secure, collision-resistant IDs by combining several sources of entropy:
The result is securely hashed with SHA3-512 and formatted to the desired length.
The library provides several constants that you can use:
pub const DEFAULT_LENGTH: usize = 24; // Default CUID length
pub const MAX_LENGTH: usize = 32; // Maximum allowed length
pub const MIN_LENGTH: usize = 2; // Minimum allowed length
The generate() and generate_cuid() functions return a Result that can contain errors:
use cuid2_rs::{generate_cuid, CuidError};
fn main() {
// Length is too large (over MAX_LENGTH)
let result = generate_cuid(100);
match result {
Err(CuidError::InvalidLength(len, min, max)) => {
println!("Error: Invalid length {} (must be between {} and {})",
len, min, max);
},
_ => panic!("Unexpected result"),
}
}
CUID2 is designed to be efficient while maintaining security. The implementation uses:
This project is licensed under the MIT License - see the LICENSE file for details.
Contributions are welcome! Please feel free to submit a Pull Request.
This is a Rust implementation of the CUID2 algorithm, originally developed by Eric Elliott.