wordval-utils 1.0.8

Wordval utilities: string manipulation, date handling, masking, ID generation, validation, crypto, web helpers, collection tools, retry utilities
Documentation
//! 字符串工具:驼峰/蛇形互转、截断、判空、随机串等

/// 字符串扩展 trait(为 `&str` 添加实用方法)
///
/// 导入后可对任何字符串切片调用驼峰/蛇形/短横/标题互转、截断、判空、填充、分词等方法。
pub trait StrExt {
    /// 是否为空白(仅含空格/制表符/换行符)
    fn is_blank(&self) -> bool;
    /// 蛇形命名 → 驼峰命名(如 `user_name` → `userName`)
    fn to_camel(&self) -> String;
    /// 驼峰命名 → 蛇形命名(如 `UserName` → `user_name`)
    fn to_snake(&self) -> String;
    /// 蛇形/驼峰 → 短横命名(如 `user_name` → `user-name`)
    fn to_kebab(&self) -> String;
    /// 标题化(如 `hello world` → `Hello World`)
    fn to_title(&self) -> String;
    /// 按字符数截断(超出末尾补 `...`)
    fn truncate(&self, max: usize) -> String;
    /// 生成指定长度的随机字母数字串
    fn random(len: usize) -> String;
    /// 非空白字符(`is_blank` 的取反)
    fn has_text(&self) -> bool {
        !self.is_blank()
    }
    /// 按空白分词(如 `"hello  world\nfoo"` → `["hello", "world", "foo"]`)
    fn words(&self) -> Vec<&str>;
    /// 左填充到指定长度(如 `"42".pad_left(5, '0')` → `"00042"`)
    fn pad_left(&self, len: usize, ch: char) -> String;
    /// 右填充到指定长度(如 `"hi".pad_right(5, '.')` → `"hi..."`)
    fn pad_right(&self, len: usize, ch: char) -> String;
}

impl StrExt for str {
    fn is_blank(&self) -> bool {
        self.trim().is_empty()
    }

    fn to_camel(&self) -> String {
        // 单趟单分配:首词整体小写,`_` 后的首字符大写
        let mut out = String::with_capacity(self.len());
        let mut seen_sep = false;
        let mut upper_next = false;
        for ch in self.chars() {
            if ch == '_' {
                seen_sep = true;
                upper_next = true;
                continue;
            }
            if !seen_sep {
                out.extend(ch.to_lowercase());
            } else if upper_next {
                out.extend(ch.to_uppercase());
                upper_next = false;
            } else {
                out.push(ch);
            }
        }
        out
    }

    fn to_snake(&self) -> String {
        let mut result = String::with_capacity(self.len() + 4);
        for (i, ch) in self.chars().enumerate() {
            if ch.is_uppercase() && i > 0 {
                result.push('_');
            }
            result.push(ch.to_ascii_lowercase());
        }
        result
    }

    fn to_kebab(&self) -> String {
        // 先转蛇形,再把下划线替换为短横
        self.to_snake().replace('_', "-")
    }

    fn to_title(&self) -> String {
        self.split_whitespace()
            .map(|w| {
                let mut chars = w.chars();
                match chars.next() {
                    None => String::new(),
                    Some(c) => {
                        let mut s = c.to_uppercase().to_string();
                        s.extend(chars.map(|c| c.to_ascii_lowercase()));
                        s
                    }
                }
            })
            .collect::<Vec<_>>()
            .join(" ")
    }

    fn truncate(&self, max: usize) -> String {
        if self.chars().count() <= max {
            return self.to_string();
        }
        let byte_idx = self
            .char_indices()
            .take(max)
            .last()
            .map(|(i, c)| i + c.len_utf8())
            .unwrap_or(0);
        format!("{}...", &self[..byte_idx])
    }

    fn random(len: usize) -> String {
        use rand::Rng;
        const CHARSET: &[u8] = b"abcdefghijklmnopqrstuvwxyz0123456789";
        let mut rng = rand::thread_rng();
        (0..len)
            .map(|_| CHARSET[rng.gen_range(0..CHARSET.len())] as char)
            .collect()
    }

    fn words(&self) -> Vec<&str> {
        self.split_whitespace().collect()
    }

    fn pad_left(&self, len: usize, ch: char) -> String {
        let char_count = self.chars().count();
        if char_count >= len {
            return self.to_string();
        }
        let mut result = String::with_capacity(len * ch.len_utf8());
        for _ in 0..(len - char_count) {
            result.push(ch);
        }
        result.push_str(self);
        result
    }

    fn pad_right(&self, len: usize, ch: char) -> String {
        let char_count = self.chars().count();
        if char_count >= len {
            return self.to_string();
        }
        let mut result = String::with_capacity(len * ch.len_utf8());
        result.push_str(self);
        for _ in 0..(len - char_count) {
            result.push(ch);
        }
        result
    }
}

/// 清理文件名 —— 将非字母/数字/点/横线/下划线的字符替换为 `_`
pub fn sanitize_filename(filename: &str) -> String {
    filename
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') {
                c
            } else {
                '_'
            }
        })
        .collect()
}

/// 解析 JSON 字符串为 `serde_json::Value`
pub fn parse_json_value(value: &str) -> Result<serde_json::Value, serde_json::Error> {
    serde_json::from_str(value)
}

/// 格式化文件大小(字节 → 人类可读)
///
/// # 示例
///
/// ```
/// assert_eq!(wordval_utils::str::format_file_size(0), "0 B");
/// assert_eq!(wordval_utils::str::format_file_size(1024), "1.00 KB");
/// assert_eq!(wordval_utils::str::format_file_size(1_500_000), "1.43 MB");
/// ```
pub fn format_file_size(bytes: u64) -> String {
    const UNITS: [&str; 7] = ["B", "KB", "MB", "GB", "TB", "PB", "EB"];

    if bytes == 0 {
        return "0 B".to_string();
    }

    // 循环除以 1024 定位单位,避免浮点 log 的精度误差与 u64::MAX 越界
    let mut size = bytes as f64;
    let mut unit = 0;
    while size >= 1024.0 && unit < UNITS.len() - 1 {
        size /= 1024.0;
        unit += 1;
    }

    format!("{:.2} {}", size, UNITS[unit])
}

/// 清理字符串参数 —— 去除前后空格
pub fn clean_string_param(s: &str) -> String {
    s.trim().to_string()
}

/// 清理邮箱参数 —— 去除前后空格,转为小写
pub fn clean_email(email: &str) -> String {
    email.trim().to_lowercase()
}

/// 清理密码参数 —— 只去除前后空格,保留中间空格
pub fn clean_password(password: &str) -> String {
    password.trim().to_string()
}

/// 用户输入清理器 —— 提供注册/登录请求参数的规范化清理
pub struct InputCleaner;

impl InputCleaner {
    /// 清理注册请求:邮箱小写去空格、密码去空格、昵称去空格
    ///
    /// 返回 `(email, password, nickname)` 三元组。
    pub fn clean_register_input(
        email: &str,
        password: &str,
        nickname: &str,
    ) -> (String, String, String) {
        let email = clean_email(email);
        let password = clean_password(password);
        let nickname = clean_string_param(nickname);
        (email, password, nickname)
    }

    /// 清理登录请求:邮箱小写去空格、密码去空格
    ///
    /// 返回 `(email, password)` 二元组。
    pub fn clean_login_input(email: &str, password: &str) -> (String, String) {
        let email = clean_email(email);
        let password = clean_password(password);
        (email, password)
    }
}

/// 生成邀请码 —— 12 位随机字母数字串
pub fn generate_invite_code() -> String {
    use rand::{distributions::Alphanumeric, Rng};
    rand::thread_rng()
        .sample_iter(&Alphanumeric)
        .take(12)
        .map(char::from)
        .collect()
}

/// 生成指定位数的不含数字 `0` 的随机数字串
///
/// # 参数
///
/// * `n` - 位数(若为 0 则返回空字符串)
///
/// # 示例
///
/// ```
/// let s = wordval_utils::str::generate_random_digits(6);
/// assert_eq!(s.len(), 6);
/// assert!(!s.chars().any(|c| c == '0'));
/// ```
pub fn generate_random_digits(n: usize) -> String {
    if n == 0 {
        return String::new();
    }
    use rand::Rng;
    let mut rng = rand::thread_rng();
    (0..n)
        .map(|_| (rng.gen_range(1..=9) + b'0') as char)
        .collect()
}

/// 生成由大小写字母和数字(不含 `0` 和 `O`/`I`/`l` 等易混淆字符)组成的随机字符串
///
/// # 参数
///
/// * `length` - 字符串长度(若为 0 则返回空字符串)
///
/// # 示例
///
/// ```
/// let s = wordval_utils::str::generate_random_alphanum(8);
/// assert_eq!(s.len(), 8);
/// assert!(!s.chars().any(|c| c == '0' || c == 'O' || c == 'I' || c == 'l'));
/// ```
pub fn generate_random_alphanum(length: usize) -> String {
    const CHARSET: &[u8] = b"ABCDEFGHJKMNPQRSTUVWXYZ\
                              abcdefghjkmnpqrstuvwxyz\
                              123456789";
    use rand::Rng;
    let mut rng = rand::thread_rng();
    let mut result = String::with_capacity(length);
    for _ in 0..length {
        let idx = rng.gen_range(0..CHARSET.len());
        result.push(CHARSET[idx] as char);
    }
    result
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_camel() {
        assert_eq!("user_name".to_camel(), "userName");
    }
    #[test]
    fn test_snake() {
        assert_eq!("UserName".to_snake(), "user_name");
    }
    #[test]
    fn test_blank() {
        assert!("  ".is_blank());
        assert!(!"abc".is_blank());
    }

    #[test]
    fn test_truncate_short() {
        let s = "hello";
        assert_eq!(StrExt::truncate(s, 10), "hello");
    }
    #[test]
    fn test_truncate_long() {
        let s = "hello world this is a test";
        let r = StrExt::truncate(s, 10);
        assert!(r.ends_with("..."));
        assert!(r.len() <= 13);
    }
    #[test]
    fn test_truncate_utf8() {
        let s = "你好世界测试";
        let r = StrExt::truncate(s, 3);
        assert!(r.ends_with("..."));
    }
    #[test]
    fn test_truncate_boundary() {
        let s = "aaaaa".repeat(20);
        let r = StrExt::truncate(s.as_str(), 5);
        assert_eq!(r, "aaaaa...");
    }
    #[test]
    fn test_sanitize_filename_clean() {
        assert_eq!(sanitize_filename("hello.txt"), "hello.txt");
        assert_eq!(sanitize_filename("file-name_v2.rs"), "file-name_v2.rs");
    }
    #[test]
    fn test_sanitize_filename_dirty() {
        assert_eq!(sanitize_filename("hello world!.txt"), "hello_world_.txt");
        assert_eq!(sanitize_filename("path/to/file"), "path_to_file");
    }
    #[test]
    fn test_random_length() {
        let s1: String = <str as StrExt>::random(8);
        let s2: String = <str as StrExt>::random(16);
        assert_eq!(s1.len(), 8);
        assert_eq!(s2.len(), 16);
    }

    #[test]
    fn test_to_kebab() {
        assert_eq!("user_name".to_kebab(), "user-name");
        assert_eq!("UserName".to_kebab(), "user-name");
        assert_eq!("userId".to_kebab(), "user-id");
    }

    #[test]
    fn test_to_title() {
        assert_eq!("hello world".to_title(), "Hello World");
        assert_eq!("RUST is GREAT".to_title(), "Rust Is Great");
        assert_eq!("  spaces  between  ".to_title(), "Spaces Between");
    }

    #[test]
    fn test_words() {
        assert_eq!("hello  world\nfoo".words(), vec!["hello", "world", "foo"]);
        assert_eq!("".words(), Vec::<&str>::new());
        assert_eq!("single".words(), vec!["single"]);
    }

    #[test]
    fn test_pad_left() {
        assert_eq!("42".pad_left(5, '0'), "00042");
        assert_eq!("hello".pad_left(3, ' '), "hello"); // 已超出
        assert_eq!("".pad_left(3, '-'), "---");
    }

    #[test]
    fn test_pad_right() {
        assert_eq!("hi".pad_right(5, '.'), "hi...");
        assert_eq!("hello".pad_right(3, ' '), "hello"); // 已超出
        assert_eq!("".pad_right(3, '*'), "***");
    }
}