Files
tuliprox/src/utils/string_utils.rs
T

74 lines
2.1 KiB
Rust
Raw Normal View History

2025-04-28 19:52:59 +02:00
use rand::Rng;
// other implementations like calculating text_distance on all titles took too much time
// we keep it now as simple as possible and less memory intensive.
2024-11-04 18:46:56 +01:00
pub fn get_title_group(text: &str) -> String {
let alphabetic_only: String = text.chars().map(|c| if c.is_alphanumeric() { c } else { ' ' }).collect();
let parts = alphabetic_only.split_whitespace();
2024-05-10 10:13:50 +02:00
let mut combination = String::new();
for p in parts {
combination = format!("{combination} {p}").trim().to_string();
if combination.len() > 2 {
return combination;
}
}
text.to_string()
}
2024-09-18 19:50:38 +02:00
2024-11-04 18:46:56 +01:00
pub trait Capitalize {
2024-09-18 19:50:38 +02:00
fn capitalize(&self) -> String;
}
// Implement the Capitalize trait for &str
impl Capitalize for &str {
fn capitalize(&self) -> String {
let mut chars = self.chars();
2024-11-04 18:46:56 +01:00
chars.next().map_or_else(String::new, |first_char| first_char.to_uppercase().collect::<String>() + chars.as_str())
2024-09-18 19:50:38 +02:00
}
}
// Implement the trait for String as well
impl Capitalize for String {
fn capitalize(&self) -> String {
self.as_str().capitalize() // Reuse the &str implementation
}
2025-02-14 17:51:33 +01:00
}
pub fn get_trimmed_string(value: &Option<String>) -> Option<String> {
if let Some(v) = value {
let trimmed = v.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
None
}
2025-04-28 19:52:59 +02:00
pub fn generate_random_string(length: usize) -> String {
let charset = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let mut rng = rand::rng();
let random_string: String = (0..length)
.map(|_| {
let idx = rng.random_range(0..charset.len());
charset[idx] as char
})
.collect();
random_string
}
#[cfg(test)]
mod test {
use std::collections::HashSet;
2025-05-04 10:59:08 +02:00
use crate::utils::generate_random_string;
2025-04-28 19:52:59 +02:00
#[test]
fn test_generate_random_string() {
let mut strings = HashSet::new();
for _i in 0..100 {
strings.insert(generate_random_string(5));
}
assert_eq!(strings.len(), 100);
}
}