Skip to main content

larastvel_core/support/
stringable.rs

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