pub trait StrExt {
fn is_blank(&self) -> bool;
fn to_camel(&self) -> String;
fn to_snake(&self) -> String;
fn to_kebab(&self) -> String;
fn to_title(&self) -> String;
fn truncate(&self, max: usize) -> String;
fn random(len: usize) -> String;
fn has_text(&self) -> bool {
!self.is_blank()
}
fn words(&self) -> Vec<&str>;
fn pad_left(&self, len: usize, ch: char) -> String;
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()
}
pub fn parse_json_value(value: &str) -> Result<serde_json::Value, serde_json::Error> {
serde_json::from_str(value)
}
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();
}
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 {
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)
}
pub fn clean_login_input(email: &str, password: &str) -> (String, String) {
let email = clean_email(email);
let password = clean_password(password);
(email, password)
}
}
pub fn generate_invite_code() -> String {
use rand::{distributions::Alphanumeric, Rng};
rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(12)
.map(char::from)
.collect()
}
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()
}
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, '*'), "***");
}
}