Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature is cuid2 #10

Merged
merged 3 commits into from
Aug 2, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions crates/cuid2/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,35 @@ fn hash<S: AsRef<[u8]>, T: IntoIterator<Item = S>>(input: T, length: u16) -> Str
// Other Utility Functions
// =======================

/// Return whether a string is a legitimate CUID2
/// ```rust
/// use cuid2;
/// let id = cuid2::create_id();
/// let empty_id = "";
/// let too_small = "a";
/// let too_big = "a1l23j1l2k3j12o8312j3k12j3lj12k3j1lk2j312j3lkj12l3g1kj2h312312lk3j1l2j3lk12j3lkjlj1lk23jl131l2k3jl12j3lk1j2lk3j12lk3h12k3hhl1j2j3";
/// let non_ascii_alphanumeric = "a#";
/// assert!(cuid2::is_cuid2(id));
/// assert!(!cuid2::is_cuid2(empty_id));
/// assert!(!cuid2::is_cuid2(too_small));
/// assert!(!cuid2::is_cuid2(too_big));
/// assert!(!cuid2::is_cuid2(non_ascii_alphanumeric));
/// ```
#[inline]
pub fn is_cuid2<S: AsRef<str>>(to_check: S) -> bool {
let to_check = to_check.as_ref();
const MAX_LENGTH: usize = BIG_LENGTH as usize;
match to_check.len() {
2..=MAX_LENGTH => {
STARTING_CHARS.contains(&to_check[..1])
&& to_check[1..].chars().into_iter().fold(true, |acc, ch| {
acc && (ch.is_ascii_lowercase()) || ch.is_ascii_digit()
})
}
_ => false,
}
}

/// Creates a random string of the specified length.
fn create_entropy(length: u16) -> String {
let mut rng = thread_rng();
Expand Down