Skip to main content

larastvel_core/support/
str.rs

1use rand::Rng;
2
3pub struct Str;
4
5impl Str {
6    pub fn slug(s: &str, separator: &str) -> String {
7        let s = s.to_lowercase();
8        let mut result = String::with_capacity(s.len());
9        let mut prev_was_sep = true;
10        for c in s.chars() {
11            if c.is_ascii_alphanumeric() {
12                result.push(c);
13                prev_was_sep = false;
14            } else if !prev_was_sep {
15                result.push_str(separator);
16                prev_was_sep = true;
17            }
18        }
19        if result.ends_with(separator) && separator.len() <= result.len() {
20            result.truncate(result.len() - separator.len());
21        }
22        result
23    }
24
25    pub fn studly(s: &str) -> String {
26        words(s).into_iter().map(|w| capitalize(&w)).collect()
27    }
28
29    pub fn camel(s: &str) -> String {
30        let mut result = Self::studly(s);
31        if let Some(c) = result.chars().next() {
32            result.replace_range(..c.len_utf8(), &c.to_lowercase().to_string());
33        }
34        result
35    }
36
37    pub fn snake(s: &str) -> String {
38        words(s).join("_")
39    }
40
41    pub fn kebab(s: &str) -> String {
42        words(s).join("-")
43    }
44
45    pub fn title(s: &str) -> String {
46        let small_words = [
47            "a", "an", "the", "and", "or", "but", "in", "on", "at", "to", "for", "of", "by",
48            "with", "nor", "as", "is", "it",
49        ];
50        let words: Vec<String> = words(s);
51        let mut result = Vec::with_capacity(words.len());
52        for (i, w) in words.iter().enumerate() {
53            let lower = w.to_lowercase();
54            if i > 0 && i < words.len() - 1 && small_words.contains(&lower.as_str()) {
55                result.push(lower);
56            } else {
57                result.push(capitalize(w));
58            }
59        }
60        result.join(" ")
61    }
62
63    pub fn headline(s: &str) -> String {
64        let s = s.replace('_', " ");
65        let s = s.replace('-', " ");
66        let words: Vec<&str> = s.split_whitespace().collect();
67        words
68            .into_iter()
69            .map(|w| {
70                let w = w.to_lowercase();
71                capitalize(&w)
72            })
73            .collect::<Vec<_>>()
74            .join(" ")
75    }
76
77    pub fn contains(s: &str, needle: &str) -> bool {
78        s.contains(needle)
79    }
80
81    pub fn contains_all(s: &str, needles: &[&str]) -> bool {
82        needles.iter().all(|n| s.contains(*n))
83    }
84
85    pub fn starts_with(s: &str, needle: &str) -> bool {
86        s.starts_with(needle)
87    }
88
89    pub fn ends_with(s: &str, needle: &str) -> bool {
90        s.ends_with(needle)
91    }
92
93    pub fn after<'a>(s: &'a str, search: &str) -> &'a str {
94        s.split_once(search).map(|(_, after)| after).unwrap_or("")
95    }
96
97    pub fn before<'a>(s: &'a str, search: &str) -> &'a str {
98        s.split_once(search).map(|(before, _)| before).unwrap_or(s)
99    }
100
101    pub fn between<'a>(s: &'a str, from: &str, to: &str) -> &'a str {
102        let s = Self::after(s, from);
103        Self::before(s, to)
104    }
105
106    pub fn limit(s: &str, limit: usize, end: &str) -> String {
107        if s.len() <= limit {
108            s.to_string()
109        } else {
110            let mut result = s[..limit].to_string();
111            result.push_str(end);
112            result
113        }
114    }
115
116    pub fn substr(s: &str, start: usize, length: Option<usize>) -> String {
117        s.chars()
118            .skip(start)
119            .take(length.unwrap_or(usize::MAX))
120            .collect()
121    }
122
123    pub fn position(s: &str, needle: &str, offset: usize) -> Option<usize> {
124        if offset >= s.len() {
125            return None;
126        }
127        let search = &s[offset..];
128        search.find(needle).map(|pos| pos + offset)
129    }
130
131    pub fn length(s: &str) -> usize {
132        s.chars().count()
133    }
134
135    pub fn is_ascii(s: &str) -> bool {
136        s.is_ascii()
137    }
138
139    pub fn word_count(s: &str) -> usize {
140        s.split_whitespace().filter(|w| !w.is_empty()).count()
141    }
142
143    pub fn is_json(s: &str) -> bool {
144        serde_json::from_str::<serde_json::Value>(s).is_ok()
145    }
146
147    pub fn pad_left(s: &str, length: usize, pad: &str) -> String {
148        let current = s.chars().count();
149        if current >= length {
150            return s.to_string();
151        }
152        let needed = length - current;
153        let mut result = String::with_capacity(length);
154        let pad_chars: Vec<char> = pad.chars().collect();
155        for i in 0..needed {
156            result.push(pad_chars[i % pad_chars.len()]);
157        }
158        result.push_str(s);
159        result
160    }
161
162    pub fn pad_right(s: &str, length: usize, pad: &str) -> String {
163        let current = s.chars().count();
164        if current >= length {
165            return s.to_string();
166        }
167        let needed = length - current;
168        let mut result = s.to_string();
169        let pad_chars: Vec<char> = pad.chars().collect();
170        for i in 0..needed {
171            result.push(pad_chars[i % pad_chars.len()]);
172        }
173        result
174    }
175
176    pub fn pad_both(s: &str, length: usize, pad: &str) -> String {
177        let current = s.chars().count();
178        if current >= length {
179            return s.to_string();
180        }
181        let needed = length - current;
182        let left = needed / 2;
183        let right = needed - left;
184        let mut result = String::with_capacity(length);
185        let pad_chars: Vec<char> = pad.chars().collect();
186        for i in 0..left {
187            result.push(pad_chars[i % pad_chars.len()]);
188        }
189        result.push_str(s);
190        for i in 0..right {
191            result.push(pad_chars[(left + i) % pad_chars.len()]);
192        }
193        result
194    }
195
196    pub fn replace(s: &str, search: &str, replace: &str) -> String {
197        s.replace(search, replace)
198    }
199
200    pub fn replace_first(s: &str, search: &str, replace: &str) -> String {
201        s.replacen(search, replace, 1)
202    }
203
204    pub fn random(length: usize) -> String {
205        let chars: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
206        let mut rng = rand::rngs::OsRng;
207        (0..length)
208            .map(|_| {
209                let idx = rng.gen_range(0..chars.len());
210                chars[idx] as char
211            })
212            .collect()
213    }
214
215    pub fn random_numeric(length: usize) -> String {
216        let mut rng = rand::rngs::OsRng;
217        (0..length)
218            .map(|_| rng.gen_range(0..10).to_string())
219            .collect()
220    }
221
222    pub fn mask(s: &str, character: &str, start: usize, length: usize) -> String {
223        let chars: Vec<char> = s.chars().collect();
224        let mut result = String::with_capacity(s.len());
225        let mask_char = character.chars().next().unwrap_or('*');
226        for (i, &c) in chars.iter().enumerate() {
227            if i >= start && i < start + length {
228                result.push(mask_char);
229            } else {
230                result.push(c);
231            }
232        }
233        result
234    }
235
236    pub fn ucfirst(s: &str) -> String {
237        let mut chars = s.chars();
238        match chars.next() {
239            None => String::new(),
240            Some(c) => c.to_uppercase().to_string() + chars.as_str(),
241        }
242    }
243
244    pub fn lcfirst(s: &str) -> String {
245        let mut chars = s.chars();
246        match chars.next() {
247            None => String::new(),
248            Some(c) => c.to_lowercase().to_string() + chars.as_str(),
249        }
250    }
251
252    pub fn repeat(s: &str, times: usize) -> String {
253        s.repeat(times)
254    }
255
256    pub fn trim(s: &str) -> String {
257        s.trim().to_string()
258    }
259
260    pub fn trim_slashes(s: &str) -> String {
261        s.trim_matches('/').to_string()
262    }
263
264    pub fn finish(s: &str, cap: &str) -> String {
265        if s.ends_with(cap) {
266            s.to_string()
267        } else {
268            format!("{}{}", s, cap)
269        }
270    }
271
272    pub fn start(s: &str, prefix: &str) -> String {
273        if s.starts_with(prefix) {
274            s.to_string()
275        } else {
276            format!("{}{}", prefix, s)
277        }
278    }
279
280    pub fn is_url(s: &str) -> bool {
281        s.starts_with("http://") || s.starts_with("https://")
282    }
283
284    pub fn of(s: &str) -> crate::support::Stringable {
285        crate::support::Stringable::new(s)
286    }
287
288    pub fn is_uuid(s: &str) -> bool {
289        let s = s.trim();
290        if s.len() != 36 {
291            return false;
292        }
293        let parts: Vec<&str> = s.split('-').collect();
294        if parts.len() != 5 {
295            return false;
296        }
297        parts[0].len() == 8
298            && parts[1].len() == 4
299            && parts[2].len() == 4
300            && parts[3].len() == 4
301            && parts[4].len() == 12
302            && parts
303                .iter()
304                .all(|p| p.chars().all(|c| c.is_ascii_hexdigit()))
305    }
306}
307
308pub(crate) fn words(s: &str) -> Vec<String> {
309    let s = s.trim();
310    if s.is_empty() {
311        return vec![];
312    }
313
314    let unified: String = s
315        .chars()
316        .map(|c| if c.is_ascii_alphanumeric() { c } else { ' ' })
317        .collect();
318
319    let tokens: Vec<&str> = unified.split_whitespace().collect();
320    let mut result = Vec::new();
321    for token in tokens {
322        for word in split_camel(token) {
323            if !word.is_empty() {
324                result.push(word.to_lowercase());
325            }
326        }
327    }
328    result
329}
330
331fn split_camel(s: &str) -> Vec<String> {
332    let mut result = Vec::new();
333    let mut current = String::new();
334    let chars: Vec<char> = s.chars().collect();
335
336    for (i, &c) in chars.iter().enumerate() {
337        if c.is_ascii_uppercase() && !current.is_empty() {
338            let prev = chars[i - 1];
339            let next = chars.get(i + 1).copied();
340            let prev_is_lower = prev.is_ascii_lowercase();
341            let next_is_lower = next.is_some_and(|n| n.is_ascii_lowercase());
342
343            if prev_is_lower || (next_is_lower && current.chars().all(|pc| pc.is_ascii_uppercase()))
344            {
345                result.push(current.clone());
346                current.clear();
347            }
348        }
349        current.push(c);
350    }
351
352    if !current.is_empty() {
353        result.push(current);
354    }
355    result
356}
357
358pub(crate) fn capitalize(s: &str) -> String {
359    let mut chars = s.chars();
360    match chars.next() {
361        None => String::new(),
362        Some(c) => c.to_uppercase().to_string() + chars.as_str(),
363    }
364}
365
366#[cfg(test)]
367mod tests {
368    use super::*;
369
370    #[test]
371    fn test_slug_basic() {
372        assert_eq!(Str::slug("Hello World", "-"), "hello-world");
373    }
374
375    #[test]
376    fn test_slug_multi_spaces() {
377        assert_eq!(Str::slug("Hello   World", "-"), "hello-world");
378    }
379
380    #[test]
381    fn test_slug_special_chars() {
382        assert_eq!(Str::slug("Hello! World?", "-"), "hello-world");
383    }
384
385    #[test]
386    fn test_slug_trailing_separator() {
387        assert_eq!(Str::slug("Hello World! ", "-"), "hello-world");
388    }
389
390    #[test]
391    fn test_slug_custom_separator() {
392        assert_eq!(Str::slug("Hello World", "_"), "hello_world");
393    }
394
395    #[test]
396    fn test_slug_empty() {
397        assert_eq!(Str::slug("", "-"), "");
398    }
399
400    #[test]
401    fn test_studly() {
402        assert_eq!(Str::studly("hello_world"), "HelloWorld");
403        assert_eq!(Str::studly("hello-world"), "HelloWorld");
404        assert_eq!(Str::studly("hello world"), "HelloWorld");
405    }
406
407    #[test]
408    fn test_studly_camel_case_input() {
409        assert_eq!(Str::studly("helloWorld"), "HelloWorld");
410    }
411
412    #[test]
413    fn test_camel() {
414        assert_eq!(Str::camel("hello_world"), "helloWorld");
415        assert_eq!(Str::camel("HelloWorld"), "helloWorld");
416        assert_eq!(Str::camel("hello-world"), "helloWorld");
417    }
418
419    #[test]
420    fn test_snake() {
421        assert_eq!(Str::snake("HelloWorld"), "hello_world");
422        assert_eq!(Str::snake("helloWorld"), "hello_world");
423        assert_eq!(Str::snake("hello-world"), "hello_world");
424    }
425
426    #[test]
427    fn test_kebab() {
428        assert_eq!(Str::kebab("HelloWorld"), "hello-world");
429        assert_eq!(Str::kebab("hello_world"), "hello-world");
430        assert_eq!(Str::kebab("hello world"), "hello-world");
431    }
432
433    #[test]
434    fn test_title() {
435        assert_eq!(Str::title("hello world"), "Hello World");
436        assert_eq!(Str::title("the quick brown fox"), "The Quick Brown Fox");
437    }
438
439    #[test]
440    fn test_title_with_small_words() {
441        assert_eq!(Str::title("a tale of two cities"), "A Tale of Two Cities");
442    }
443
444    #[test]
445    fn test_headline() {
446        assert_eq!(Str::headline("hello_world"), "Hello World");
447        assert_eq!(Str::headline("hello-world"), "Hello World");
448        assert_eq!(Str::headline("hello world"), "Hello World");
449    }
450
451    #[test]
452    fn test_contains() {
453        assert!(Str::contains("Hello World", "World"));
454        assert!(!Str::contains("Hello World", "world"));
455    }
456
457    #[test]
458    fn test_contains_all() {
459        assert!(Str::contains_all("Hello World", &["Hello", "World"]));
460        assert!(!Str::contains_all("Hello World", &["Hello", "world"]));
461    }
462
463    #[test]
464    fn test_starts_with() {
465        assert!(Str::starts_with("Hello World", "Hello"));
466        assert!(!Str::starts_with("Hello World", "World"));
467    }
468
469    #[test]
470    fn test_ends_with() {
471        assert!(Str::ends_with("Hello World", "World"));
472        assert!(!Str::ends_with("Hello World", "Hello"));
473    }
474
475    #[test]
476    fn test_after() {
477        assert_eq!(Str::after("Hello World", "Hello "), "World");
478        assert_eq!(Str::after("Hello World", "xyz"), "");
479    }
480
481    #[test]
482    fn test_before() {
483        assert_eq!(Str::before("Hello World", " World"), "Hello");
484        assert_eq!(Str::before("Hello World", "xyz"), "Hello World");
485    }
486
487    #[test]
488    fn test_between() {
489        assert_eq!(Str::between("[Hello]", "[", "]"), "Hello");
490        assert_eq!(Str::between("Hello {World}", "{", "}"), "World");
491    }
492
493    #[test]
494    fn test_limit() {
495        assert_eq!(Str::limit("Hello World", 5, "..."), "Hello...");
496        assert_eq!(Str::limit("Hi", 5, "..."), "Hi");
497    }
498
499    #[test]
500    fn test_substr() {
501        assert_eq!(Str::substr("Hello World", 0, Some(5)), "Hello");
502        assert_eq!(Str::substr("Hello World", 6, None), "World");
503    }
504
505    #[test]
506    fn test_position() {
507        assert_eq!(Str::position("Hello World", "World", 0), Some(6));
508        assert_eq!(Str::position("Hello World", "xyz", 0), None);
509    }
510
511    #[test]
512    fn test_position_with_offset() {
513        assert_eq!(Str::position("Hello World World", "World", 8), Some(12));
514    }
515
516    #[test]
517    fn test_length() {
518        assert_eq!(Str::length("Hello"), 5);
519        assert_eq!(Str::length(""), 0);
520        assert_eq!(Str::length("日本語"), 3);
521    }
522
523    #[test]
524    fn test_is_ascii() {
525        assert!(Str::is_ascii("Hello"));
526        assert!(!Str::is_ascii("日本語"));
527    }
528
529    #[test]
530    fn test_word_count() {
531        assert_eq!(Str::word_count("Hello World"), 2);
532        assert_eq!(Str::word_count(""), 0);
533        assert_eq!(Str::word_count("one"), 1);
534    }
535
536    #[test]
537    fn test_is_json() {
538        assert!(Str::is_json(r#"{"key": "value"}"#));
539        assert!(Str::is_json("[1, 2, 3]"));
540        assert!(!Str::is_json("not json"));
541    }
542
543    #[test]
544    fn test_pad_left() {
545        assert_eq!(Str::pad_left("Hello", 7, "*"), "**Hello");
546        assert_eq!(Str::pad_left("Hello", 3, "*"), "Hello");
547    }
548
549    #[test]
550    fn test_pad_right() {
551        assert_eq!(Str::pad_right("Hello", 7, "*"), "Hello**");
552    }
553
554    #[test]
555    fn test_pad_both() {
556        assert_eq!(Str::pad_both("Hello", 9, "*"), "**Hello**");
557    }
558
559    #[test]
560    fn test_replace() {
561        assert_eq!(Str::replace("Hello World", "World", "Moon"), "Hello Moon");
562    }
563
564    #[test]
565    fn test_replace_first() {
566        assert_eq!(
567            Str::replace_first("foo bar foo", "foo", "baz"),
568            "baz bar foo"
569        );
570    }
571
572    #[test]
573    fn test_random_length() {
574        let s = Str::random(10);
575        assert_eq!(s.len(), 10);
576        assert!(s.chars().all(|c| c.is_ascii_alphanumeric()));
577    }
578
579    #[test]
580    fn test_random_numeric() {
581        let s = Str::random_numeric(5);
582        assert_eq!(s.len(), 5);
583        assert!(s.chars().all(|c| c.is_ascii_digit()));
584    }
585
586    #[test]
587    fn test_random_unique() {
588        let a = Str::random(20);
589        let b = Str::random(20);
590        assert_ne!(a, b);
591    }
592
593    #[test]
594    fn test_mask() {
595        assert_eq!(Str::mask("1234-5678", "*", 0, 4), "****-5678");
596        assert_eq!(Str::mask("Hello World", "*", 6, 5), "Hello *****");
597    }
598
599    #[test]
600    fn test_ucfirst() {
601        assert_eq!(Str::ucfirst("hello"), "Hello");
602        assert_eq!(Str::ucfirst("Hello"), "Hello");
603        assert_eq!(Str::ucfirst(""), "");
604    }
605
606    #[test]
607    fn test_lcfirst() {
608        assert_eq!(Str::lcfirst("Hello"), "hello");
609        assert_eq!(Str::lcfirst("hello"), "hello");
610        assert_eq!(Str::lcfirst(""), "");
611    }
612
613    #[test]
614    fn test_repeat() {
615        assert_eq!(Str::repeat("ab", 3), "ababab");
616        assert_eq!(Str::repeat("", 5), "");
617    }
618
619    #[test]
620    fn test_trim() {
621        assert_eq!(Str::trim("  hello  "), "hello");
622        assert_eq!(Str::trim("hello"), "hello");
623    }
624
625    #[test]
626    fn test_trim_slashes() {
627        assert_eq!(Str::trim_slashes("/hello/"), "hello");
628        assert_eq!(Str::trim_slashes("hello"), "hello");
629    }
630
631    #[test]
632    fn test_finish() {
633        assert_eq!(Str::finish("hello", "/"), "hello/");
634        assert_eq!(Str::finish("hello/", "/"), "hello/");
635    }
636
637    #[test]
638    fn test_start() {
639        assert_eq!(Str::start("world", "hello "), "hello world");
640        assert_eq!(Str::start("hello world", "hello "), "hello world");
641    }
642
643    #[test]
644    fn test_is_url() {
645        assert!(Str::is_url("https://example.com"));
646        assert!(Str::is_url("http://example.com"));
647        assert!(!Str::is_url("ftp://example.com"));
648        assert!(!Str::is_url("not a url"));
649    }
650
651    #[test]
652    fn test_is_uuid() {
653        assert!(Str::is_uuid("550e8400-e29b-41d4-a716-446655440000"));
654        assert!(!Str::is_uuid("not-a-uuid"));
655        assert!(!Str::is_uuid("550e8400-e29b-41d4-a716-44665544000")); // too short
656    }
657
658    #[test]
659    fn test_studly_edge_cases() {
660        assert_eq!(Str::studly(""), "");
661        assert_eq!(Str::studly("a"), "A");
662    }
663
664    #[test]
665    fn test_camel_edge_cases() {
666        assert_eq!(Str::camel(""), "");
667        assert_eq!(Str::camel("a"), "a");
668    }
669
670    #[test]
671    fn test_snake_acronyms() {
672        assert_eq!(Str::snake("XMLParser"), "xml_parser");
673        assert_eq!(Str::snake("PDFExport"), "pdf_export");
674    }
675
676    #[test]
677    fn test_kebab_snake_mix() {
678        assert_eq!(Str::kebab("snake_case_text"), "snake-case-text");
679    }
680
681    #[test]
682    fn test_between_not_found() {
683        assert_eq!(Str::between("Hello", "[", "]"), "");
684        assert_eq!(Str::between("Hello [World", "[", "]"), "World");
685    }
686
687    #[test]
688    fn test_limit_exact_match() {
689        assert_eq!(Str::limit("Hello", 5, "..."), "Hello");
690    }
691
692    #[test]
693    fn test_limit_shorter_than_limit() {
694        assert_eq!(Str::limit("Hi", 10, "..."), "Hi");
695    }
696
697    #[test]
698    fn test_substr_out_of_bounds() {
699        assert_eq!(Str::substr("Hello", 10, None), "");
700    }
701
702    #[test]
703    fn test_position_offset_beyond_length() {
704        assert_eq!(Str::position("Hello", "H", 100), None);
705    }
706
707    #[test]
708    fn test_word_count_multi_space() {
709        assert_eq!(Str::word_count("Hello    World"), 2);
710    }
711
712    #[test]
713    fn test_mask_full_string() {
714        assert_eq!(Str::mask("secret", "*", 0, 6), "******");
715    }
716
717    #[test]
718    fn test_mask_empty() {
719        assert_eq!(Str::mask("", "*", 0, 5), "");
720    }
721}