use crate::fold;
use alloc::string::String;
use alloc::vec::Vec;
use unicode_segmentation::UnicodeSegmentation;
pub fn name<T: AsRef<str>>(t: T) -> String {
t.as_ref()
.unicode_words()
.fold(String::new(), |acc, w| fold(acc, w, ' '))
}
pub fn name_with_limit<T: AsRef<str>>(t: T, limit: usize) -> String {
let mut name: Vec<&str> = t.as_ref().unicode_words().collect();
if name.is_empty() {
return String::new();
}
let len = name.len();
let mut n = Vec::with_capacity(len);
let mut sum = 0;
for &w in &name {
let c = w.graphemes(true).count();
sum += c;
n.push(c);
}
let spaces = len - 1;
let mut count = sum + spaces;
let mut zip = name.iter_mut().zip(n);
let head = zip.next();
for (w, c) in zip {
if count <= limit {
break;
}
count -= c - 1;
*w = w.graphemes(true).next().unwrap();
}
if let Some((w, c)) = head {
if count > limit {
count -= c - 1;
*w = w.graphemes(true).next().unwrap();
}
}
if count <= limit {
name.join(" ")
} else if (count - spaces) <= limit {
name.concat()
} else {
name[..limit].concat()
}
}
pub fn username<T: AsRef<str>>(t: T) -> String {
name(t)
.chars()
.filter(|c| c.is_alphanumeric())
.flat_map(|c| c.to_lowercase())
.collect()
}
pub fn username_with_limit<T: AsRef<str>>(t: T, limit: usize) -> String {
name_with_limit(t, limit)
.chars()
.filter(|c| c.is_alphanumeric())
.flat_map(|c| c.to_lowercase())
.collect()
}