stackify_common/
util.rs

1use rand::{thread_rng, Rng};
2
3pub fn random_hex(byte_len: usize) -> String {
4    let bytes: Vec<u8> = (0..byte_len).map(|_| thread_rng().gen::<u8>()).collect();
5    bytes
6        .iter()
7        .map(|b| format!("{:02x}", b))
8        .collect::<String>()
9}
10
11pub fn truncate(s: &str, max_chars: usize) -> &str {
12    match s.char_indices().nth(max_chars) {
13        None => s,
14        Some((idx, _)) => &s[..idx],
15    }
16}
17
18pub fn to_alphanumeric_snake(s: &str) -> String {
19    let mut out = String::new();
20    for char in s.chars() {
21        if char.is_alphanumeric() {
22            out += &char.to_ascii_lowercase().to_string();
23        } else {
24            if out.chars().last().unwrap() != '-' {
25                out += "-";
26            }
27        }
28    }
29
30    if out.chars().last().unwrap() == '-' {
31        out.pop();
32    }
33
34    out
35}