Skip to main content

illuminate_str/
lib.rs

1use base64::{Engine as _, engine::general_purpose};
2use time::OffsetDateTime;
3
4use memchr::memmem::Finder;
5use pulldown_cmark::{Options, Parser, html};
6use rand::{RngExt};
7use regex::Regex;
8use std::collections::HashMap;
9use std::sync::LazyLock;
10use std::sync::{Arc, Mutex, OnceLock};
11
12use ulid::Ulid;
13use unicode_segmentation::UnicodeSegmentation;
14use unidecode::unidecode;
15use uuid::Uuid;
16
17// Type aliases for complex types
18type UuidSequence = Arc<Mutex<Option<(Vec<Uuid>, usize)>>>;
19type UlidSequence = Arc<Mutex<Option<(Vec<Ulid>, usize)>>>;
20type RandomSequence = Arc<Mutex<Option<(Vec<String>, usize)>>>;
21
22// Global caches for performance
23static SNAKE_CACHE: LazyLock<Arc<Mutex<HashMap<String, String>>>> =
24    LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));
25static CAMEL_CACHE: LazyLock<Arc<Mutex<HashMap<String, String>>>> =
26    LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));
27static STUDLY_CACHE: LazyLock<Arc<Mutex<HashMap<String, String>>>> =
28    LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));
29
30// Factory functions
31static UUID_FACTORY: OnceLock<Box<dyn Fn() -> Uuid + Send + Sync>> = OnceLock::new();
32static ULID_FACTORY: OnceLock<Box<dyn Fn() -> Ulid + Send + Sync>> = OnceLock::new();
33static RANDOM_STRING_FACTORY: OnceLock<Box<dyn Fn(usize) -> String + Send + Sync>> =
34    OnceLock::new();
35
36// Sequence factories
37static UUID_SEQUENCE: LazyLock<UuidSequence> = LazyLock::new(|| Arc::new(Mutex::new(None)));
38static ULID_SEQUENCE: LazyLock<UlidSequence> = LazyLock::new(|| Arc::new(Mutex::new(None)));
39static RANDOM_SEQUENCE: LazyLock<RandomSequence> = LazyLock::new(|| Arc::new(Mutex::new(None)));
40
41// Invisible characters constant
42const INVISIBLE_CHARACTERS: &str = "\u{0009}\u{0020}\u{00A0}\u{00AD}\u{034F}\u{061C}\u{115F}\u{1160}\u{17B4}\u{17B5}\u{180E}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{200B}\u{200C}\u{200D}\u{200E}\u{200F}\u{202F}\u{205F}\u{2060}\u{2061}\u{2062}\u{2063}\u{2064}\u{2065}\u{206A}\u{206B}\u{206C}\u{206D}\u{206E}\u{206F}\u{3000}\u{2800}\u{3164}\u{FEFF}\u{FFA0}\u{1D159}\u{1D173}\u{1D174}\u{1D175}\u{1D176}\u{1D177}\u{1D178}\u{1D179}\u{1D17A}\u{E0020}";
43
44// Pluralization rules (simplified English rules)
45static PLURAL_RULES: LazyLock<Vec<(Regex, &'static str)>> = LazyLock::new(|| {
46    vec![
47        // Most specific / irregular first
48        (Regex::new(r"(?i)^(child)$").unwrap(), "children"),
49        (Regex::new(r"(?i)^(man)$").unwrap(), "men"),
50        (Regex::new(r"(?i)^(woman)$").unwrap(), "women"),
51        (Regex::new(r"(?i)^(person)$").unwrap(), "people"),
52        (Regex::new(r"(?i)^(foot)$").unwrap(), "feet"),
53        (Regex::new(r"(?i)^(tooth)$").unwrap(), "teeth"),
54        (Regex::new(r"(?i)^(medium)$").unwrap(), "media"),
55        (Regex::new(r"(?i)^(niveau)$").unwrap(), "niveaux"),
56        (Regex::new(r"(?i)^(hippopotamus)$").unwrap(), "hippopotami"),
57        (Regex::new(r"(?i)^(die)$").unwrap(), "dice"),
58        (Regex::new(r"(?i)^(axis)$").unwrap(), "axes"),
59        (Regex::new(r"(?i)^(appendix)$").unwrap(), "appendices"),
60        (Regex::new(r"(?i)^(phenomenon)$").unwrap(), "phenomena"),
61        // ox → oxen
62        (Regex::new(r"(?i)^(ox)$").unwrap(), "${1}en"),
63        // virus, stimulus, ...
64        (Regex::new(r"(?i)(alumn|bacill|cact|foc|fung|nucle|radi|stimul|syllab|termin|vir)us$").unwrap(), "${1}i"),
65        (Regex::new(r"(?i)(octop|vir)us$").unwrap(), "${1}i"), // octopus, virus (also covered above)
66        // matrix, index, vertex → -ices
67        (Regex::new(r"(?i)(matr|vert|ind)(ix|ex)$").unwrap(), "${1}ices"),
68        // analysis, basis, crisis → -ses
69        (Regex::new(r"(?i)(analys|ax|cris|test|thes)is$").unwrap(), "${1}es"),
70        (Regex::new(r"(?i)^(analy)sis$").unwrap(), "${1}ses"),
71        // criteria, phenomena
72        (Regex::new(r"(?i)(criteri|phenomen)on$").unwrap(), "${1}a"),
73        (Regex::new(r"(?i)(curricul|memorand)um$").unwrap(), "${1}a"),
74        // tomato, potato, hero, ...
75        (Regex::new(r"(?i)(buffal|her|potat|tomat|volcan|ech|torped|vet)o$").unwrap(), "${1}oes"),
76        // quiz → quizzes
77        (Regex::new(r"(?i)(quiz)$").unwrap(), "${1}zes"),
78        // leaf, loaf, thief → -ves
79        (Regex::new(r"(?i)(?:([^f])fe|([lr])f)$").unwrap(), "${1}${2}ves"),
80        (Regex::new(r"(?i)(shea|loa|lea|thie)f$").unwrap(), "${1}ves"),
81        // knife → knives (but safe → safes)
82        (Regex::new(r"(?i)([^s])fe$").unwrap(), "${1}ves"),
83        // mouse → mice, louse → lice
84        (Regex::new(r"(?i)([ml])ouse$").unwrap(), "${1}ice"),
85        // Ends in x, ch, ss, sh → +es
86        (Regex::new(r"(?i)(x|ch|ss|sh)$").unwrap(), "${1}es"),
87        // Words ending in consonant + y → ies
88        (Regex::new(r"(?i)([^aeiouy]|qu)y$").unwrap(), "${1}ies"),
89        // status → statuses
90        (Regex::new(r"(?i)(status)$").unwrap(), "${1}es"),
91        (Regex::new(r"(?i)(alias)$").unwrap(), "${1}es"),
92        // bus → buses
93        (Regex::new(r"(?i)(bu)s$").unwrap(), "${1}ses"),
94        // Most generic plural rules (last)
95        (Regex::new(r"(?i)s$").unwrap(), "s"),     // glasses, buses (already handled), etc.
96        (Regex::new(r"(?i)$").unwrap(), "s"),      // default add -s
97    ]
98});
99
100static SINGULAR_RULES: LazyLock<Vec<(Regex, &'static str)>> = LazyLock::new(|| {
101    vec![
102        // Most specific first — reverse order philosophy
103        (Regex::new(r"(?i)children$").unwrap(), "child"),
104        (Regex::new(r"(?i)men$").unwrap(), "man"),
105        (Regex::new(r"(?i)people$").unwrap(), "person"),
106        (Regex::new(r"(?i)feet$").unwrap(), "foot"),
107        (Regex::new(r"(?i)teeth$").unwrap(), "tooth"),
108        (Regex::new(r"(?i)geese$").unwrap(), "goose"),
109        (Regex::new(r"(?i)oxen$").unwrap(), "ox"),
110        (Regex::new(r"(?i)^(media)$").unwrap(), "medium"),
111        (Regex::new(r"(?i)^(niveaux)$").unwrap(), "niveau"),
112        (Regex::new(r"(?i)^(hippopotami)$").unwrap(), "hippopotamus"),
113        (Regex::new(r"(?i)^(dice)$").unwrap(), "die"),
114        (Regex::new(r"(?i)^(axes)$").unwrap(), "axis"),
115        (Regex::new(r"(?i)^(appendices)$").unwrap(), "appendix"),
116        (Regex::new(r"(?i)^(phenomena)$").unwrap(), "phenomenon"),
117        // ox → oxen
118        // -i → -us
119        (Regex::new(r"(?i)(alumn|bacill|cact|foc|fung|nucle|radi|stimul|syllab|termin|vir)i$").unwrap(), "${1}us"),
120        (Regex::new(r"(?i)(octop|vir)i$").unwrap(), "${1}us"),
121        // -ices → -ix / -ex
122        (Regex::new(r"(?i)(matr)ices$").unwrap(), "${1}ix"),
123        (Regex::new(r"(?i)(vert|ind)ices$").unwrap(), "${1}ex"),
124        // -ses → -sis
125        (Regex::new(r"(?i)(analy|ba|diagno|parenthe|progno|synop|the)ses$").unwrap(), "${1}sis"),
126        (Regex::new(r"(?i)(cris|test|ax|thes)es$").unwrap(), "${1}is"),
127        // -a → -um / -on
128        (Regex::new(r"(?i)(criteri|phenomen)a$").unwrap(), "${1}on"),
129        (Regex::new(r"(?i)([ti])a$").unwrap(), "${1}um"),
130        // -oes → -o
131        (Regex::new(r"(?i)(buffal|her|potat|tomat|volcan|ech|torped|vet)oes$").unwrap(), "${1}o"),
132        // quizzes → quiz
133        (Regex::new(r"(?i)(quiz)zes$").unwrap(), "${1}"),
134        // -ves → -f / -fe
135        (Regex::new(r"(?i)([^f])ves$").unwrap(), "${1}fe"),
136        (Regex::new(r"(?i)([lr])ves$").unwrap(), "${1}f"),
137        (Regex::new(r"(?i)(shea|loa|lea|thie)ves$").unwrap(), "${1}f"),
138        // mice, lice
139        (Regex::new(r"(?i)([ml])ice$").unwrap(), "${1}ouse"),
140        // -xes, -ches, -shes, -sses
141        (Regex::new(r"(?i)(x|ch|ss|sh)es$").unwrap(), "${1}"),
142        // consonant + ies → y
143        (Regex::new(r"(?i)([^aeiouy]|qu)ies$").unwrap(), "${1}y"),
144        // statuses, aliases
145        (Regex::new(r"(?i)(status|alias)es$").unwrap(), "${1}"),
146        (Regex::new(r"(?i)(bu)ses$").unwrap(), "${1}s"),
147        // Most generic
148        (Regex::new(r"(?i)(.*)s$").unwrap(), "${1}"), // remove final s (fallback)
149    ]
150});
151
152pub struct Str;
153
154impl Str {
155    /// Return the remainder of a string after the first occurrence of a given value
156    pub fn after(subject: &str, search: &str) -> String {
157        if search.is_empty() {
158            return subject.to_string();
159        }
160
161        if let Some(pos) = subject.find(search) {
162            subject[(pos + search.len())..].to_string()
163        } else {
164            subject.to_string()
165        }
166    }
167
168    /// Return the remainder of a string after the last occurrence of a given value
169    pub fn after_last(subject: &str, search: &str) -> String {
170        if search.is_empty() {
171            return subject.to_string();
172        }
173
174        if let Some(pos) = subject.rfind(search) {
175            subject[(pos + search.len())..].to_string()
176        } else {
177            subject.to_string()
178        }
179    }
180
181    /// Transliterate a UTF-8 value to ASCII
182    pub fn ascii(value: &str) -> String {
183        unidecode(value)
184    }
185
186    /// Transliterate a string to its closest ASCII representation
187    pub fn transliterate(string: &str, unknown: Option<&str>, strict: Option<bool>) -> String {
188        let unknown = unknown.unwrap_or("?");
189        let strict = strict.unwrap_or(false);
190
191        string
192            .chars()
193            .map(|c| {
194                if c.is_ascii() {
195                    c.to_string()
196                } else {
197                    let transliterated = unidecode(&c.to_string());
198                    if transliterated.is_empty()
199                        || (strict && !transliterated.chars().all(|ch| ch.is_ascii_alphanumeric()))
200                    {
201                        unknown.to_string()
202                    } else {
203                        transliterated
204                    }
205                }
206            })
207            .collect()
208    }
209
210    /// Get the portion of a string before the first occurrence of a given value
211    pub fn before(subject: &str, search: &str) -> String {
212        if search.is_empty() {
213            return subject.to_string();
214        }
215
216        if let Some(pos) = subject.find(search) {
217            subject[..pos].to_string()
218        } else {
219            subject.to_string()
220        }
221    }
222
223    /// Get the portion of a string before the last occurrence of a given value
224    pub fn before_last(subject: &str, search: &str) -> String {
225        if search.is_empty() {
226            return subject.to_string();
227        }
228
229        if let Some(pos) = subject.rfind(search) {
230            subject[..pos].to_string()
231        } else {
232            subject.to_string()
233        }
234    }
235
236    /// Get the portion of a string between two given values
237    pub fn between(subject: &str, from: &str, to: &str) -> String {
238        if from.is_empty() || to.is_empty() {
239            return subject.to_string();
240        }
241
242        let after_from = Self::after(subject, from);
243        Self::before_last(&after_from, to)
244    }
245
246    /// Get the smallest possible portion of a string between two given values
247    pub fn between_first(subject: &str, from: &str, to: &str) -> String {
248        if from.is_empty() || to.is_empty() {
249            return subject.to_string();
250        }
251
252        let after_from = Self::after(subject, from);
253        Self::before(&after_from, to)
254    }
255
256    /// Convert a value to camel case
257    pub fn camel(value: &str) -> String {
258        let cache = CAMEL_CACHE.lock().unwrap();
259        if let Some(cached) = cache.get(value) {
260            return cached.clone();
261        }
262        drop(cache);
263
264        let studly = Self::studly(value);
265        let result = Self::lcfirst(&studly);
266
267        let mut cache = CAMEL_CACHE.lock().unwrap();
268        cache.insert(value.to_string(), result.clone());
269        result
270    }
271
272    /// Get the character at the specified index
273    pub fn char_at(subject: &str, index: isize) -> Option<char> {
274        let chars: Vec<char> = subject.chars().collect();
275        let length = chars.len() as isize;
276
277        let actual_index = if index < 0 {
278            if index < -length {
279                return None;
280            }
281            (length + index) as usize
282        } else {
283            if index >= length {
284                return None;
285            }
286            index as usize
287        };
288
289        chars.get(actual_index).copied()
290    }
291
292    /// Remove the given string(s) if it exists at the start of the haystack
293    pub fn chop_start(subject: &str, needles: &[&str]) -> String {
294        for needle in needles {
295            if let Some(stripped) = subject.strip_prefix(needle) {
296                return stripped.to_string();
297            }
298        }
299        subject.to_string()
300    }
301
302    /// Remove the given string(s) if it exists at the end of the haystack
303    pub fn chop_end(subject: &str, needles: &[&str]) -> String {
304        for needle in needles {
305            if let Some(stripped) = subject.strip_suffix(needle) {
306                return stripped.to_string();
307            }
308        }
309        subject.to_string()
310    }
311
312    /// Determine if a given string contains a given substring
313    pub fn contains(haystack: &str, needles: &[&str], ignore_case: bool) -> bool {
314        let haystack_check = if ignore_case {
315            &haystack.to_lowercase()
316        } else {
317            haystack
318        };
319
320        for needle in needles.iter() {
321            if needle.is_empty() {
322                continue;
323            }
324
325            let needle_check = if ignore_case {
326                &needle.to_lowercase()
327            } else {
328                *needle
329            };
330
331            let finder = Finder::new(&needle_check);
332            if finder.find(haystack_check.as_bytes()).is_some() {
333                return true;
334            }
335        }
336        false
337    }
338
339    /// Determine if a given string contains all array values
340    pub fn contains_all(haystack: &str, needles: &[&str], ignore_case: bool) -> bool {
341        for needle in needles {
342            if !Self::contains(haystack, &[needle], ignore_case) {
343                return false;
344            }
345        }
346        true
347    }
348
349    /// Determine if a given string doesn't contain a given substring
350    pub fn doesnt_contain(haystack: &str, needles: &[&str], ignore_case: bool) -> bool {
351        !Self::contains(haystack, needles, ignore_case)
352    }
353
354    /// Convert the case of a string
355    pub fn convert_case(string: &str, mode: CaseMode) -> String {
356        match mode {
357            CaseMode::Upper => string.to_uppercase(),
358            CaseMode::Lower => string.to_lowercase(),
359            CaseMode::Title => Self::title(string),
360            CaseMode::Fold => string.to_lowercase(), // Case folding approximation
361        }
362    }
363
364    /// Replace consecutive instances of a given character with a single character
365    pub fn deduplicate(string: &str, characters: &[char]) -> String {
366        let mut result = string.to_string();
367
368        for &character in characters {
369            let pattern = format!("{}{{2,}}", regex::escape(&character.to_string()));
370            let re = Regex::new(&pattern).unwrap();
371            result = re.replace_all(&result, &character.to_string()).to_string();
372        }
373
374        result
375    }
376
377    /// Determine if a given string ends with a given substring
378    pub fn ends_with(haystack: &str, needles: &[&str]) -> bool {
379        for needle in needles {
380            if !needle.is_empty() && haystack.ends_with(needle) {
381                return true;
382            }
383        }
384        false
385    }
386
387    /// Determine if a given string doesn't end with a given substring
388    pub fn doesnt_end_with(haystack: &str, needles: &[&str]) -> bool {
389        !Self::ends_with(haystack, needles)
390    }
391
392    /// Extracts an excerpt from text that matches the first instance of a phrase
393    pub fn excerpt(text: &str, phrase: &str, options: ExcerptOptions) -> Option<String> {
394        if phrase.is_empty() {
395            return None;
396        }
397
398        let re = Regex::new(&format!(r"(?i)^(.*?)({})(.*)$", regex::escape(phrase))).ok()?;
399        let caps = re.captures(text)?;
400
401        let before = caps.get(1)?.as_str().trim_start();
402        let matched = caps.get(2)?.as_str();
403        let after = caps.get(3)?.as_str().trim_end();
404
405        let start_chars: Vec<char> = before.chars().collect();
406        let start_len = start_chars.len();
407        let start_excerpt = if start_len > options.radius {
408            let excerpt_start = start_len - options.radius;
409            let excerpt: String = start_chars.iter().skip(excerpt_start).collect();
410            format!("{}{}", options.omission, excerpt.trim_start())
411        } else {
412            before.to_string()
413        };
414
415        let end_chars: Vec<char> = after.chars().collect();
416        let end_excerpt = if end_chars.len() > options.radius {
417            let excerpt: String = end_chars.iter().take(options.radius).collect();
418            format!("{}{}", excerpt.trim_end(), options.omission)
419        } else {
420            after.to_string()
421        };
422
423        Some(format!("{}{}{}", start_excerpt, matched, end_excerpt))
424    }
425
426    /// Cap a string with a single instance of a given value
427    pub fn finish(value: &str, cap: &str) -> String {
428        let pattern = format!("({})+$", regex::escape(cap));
429        let re = Regex::new(&pattern).unwrap();
430        let trimmed = re.replace_all(value, "");
431        format!("{}{}", trimmed, cap)
432    }
433
434    /// Wrap the string with the given strings
435    pub fn wrap(value: &str, before: &str, after: Option<&str>) -> String {
436        let after = after.unwrap_or(before);
437        format!("{}{}{}", before, value, after)
438    }
439
440    /// Unwrap the string with the given strings
441    pub fn unwrap(value: &str, before: &str, after: Option<&str>) -> String {
442        let after = after.unwrap_or(before);
443        let mut result = value.to_string();
444
445        if result.starts_with(before) {
446            result = result[before.len()..].to_string();
447        }
448
449        if result.ends_with(after) {
450            result = result[..result.len() - after.len()].to_string();
451        }
452
453        result
454    }
455
456    /// Determine if a given string matches a given pattern (with wildcards)
457    pub fn is_pattern(patterns: &[&str], value: &str, ignore_case: bool) -> bool {
458        for pattern in patterns {
459            if *pattern == "*" || *pattern == value {
460                return true;
461            }
462
463            if ignore_case && pattern.to_lowercase() == value.to_lowercase() {
464                return true;
465            }
466
467            let escaped = regex::escape(pattern);
468            let pattern_regex = escaped.replace("\\*", ".*");
469            let flags = if ignore_case { "(?i)" } else { "" };
470            let full_pattern = format!("{}^{}$", flags, pattern_regex);
471
472            if let Ok(re) = Regex::new(&full_pattern)
473                && re.is_match(value)
474            {
475                return true;
476            }
477        }
478        false
479    }
480
481    /// Determine if a given string is 7 bit ASCII
482    pub fn is_ascii(value: &str) -> bool {
483        value.is_ascii()
484    }
485
486    /// Determine if a given value is valid JSON
487    pub fn is_json(value: &str) -> bool {
488        serde_json::from_str::<serde_json::Value>(value).is_ok()
489    }
490
491    /// Determine if a given value is a valid URL
492    pub fn is_url(value: &str, protocols: Option<&[&str]>) -> bool {
493        if let Ok(parsed) = url::Url::parse(value) {
494            if let Some(allowed_protocols) = protocols {
495                allowed_protocols.contains(&parsed.scheme())
496            } else {
497                true
498            }
499        } else {
500            false
501        }
502    }
503
504    /// Determine if a given value is a valid UUID
505    pub fn is_uuid(value: &str, version: Option<UuidVersion>) -> bool {
506        if let Ok(uuid) = Uuid::parse_str(value) {
507            match version {
508                Some(UuidVersion::Nil) => uuid.is_nil(),
509                Some(UuidVersion::V1) => uuid.get_version() == Some(uuid::Version::Mac),
510                Some(UuidVersion::V3) => uuid.get_version() == Some(uuid::Version::Md5),
511                Some(UuidVersion::V4) => uuid.get_version() == Some(uuid::Version::Random),
512                Some(UuidVersion::V5) => uuid.get_version() == Some(uuid::Version::Sha1),
513                Some(UuidVersion::Max) => uuid.is_max(),
514                None => true,
515            }
516        } else {
517            false
518        }
519    }
520
521    /// Determine if a given value is a valid ULID
522    pub fn is_ulid(value: &str) -> bool {
523        Ulid::from_string(value).is_ok()
524    }
525
526    /// Convert a string to kebab case
527    pub fn kebab(value: &str) -> String {
528        Self::snake(value, "-")
529    }
530
531    /// Return the length of the given string
532    pub fn length(value: &str) -> usize {
533        value.graphemes(true).count()
534    }
535
536    /// Limit the number of characters in a string
537    pub fn limit(value: &str, limit: usize, end: &str, preserve_words: bool) -> String {
538        let graphemes: Vec<&str> = value.graphemes(true).collect();
539
540        if graphemes.len() <= limit {
541            return value.to_string();
542        }
543
544        if !preserve_words {
545            let truncated: String = graphemes.iter().take(limit).copied().collect();
546            return format!("{}{}", truncated, end);
547        }
548
549        // For word preservation, we need to work with the actual string
550        let truncated: String = graphemes.iter().take(limit).copied().collect();
551        let trimmed = truncated.trim_end();
552
553        // Find the last space and truncate there
554        if let Some(last_space) = trimmed.rfind(' ') {
555            format!("{}{}", &trimmed[..last_space], end)
556        } else {
557            format!("{}{}", trimmed, end)
558        }
559    }
560
561    /// Convert the given string to lower-case
562    pub fn lower(value: &str) -> String {
563        value.to_lowercase()
564    }
565
566    /// Limit the number of words in a string
567    pub fn words(value: &str, words: usize, end: &str) -> String {
568        let word_vec: Vec<&str> = value.split_whitespace().collect();
569
570        if word_vec.len() <= words {
571            return value.to_string();
572        }
573
574        let truncated: Vec<&str> = word_vec.iter().take(words).copied().collect();
575        format!("{}{}", truncated.join(" "), end)
576    }
577
578    /// Converts GitHub flavored Markdown into HTML
579    pub fn markdown(string: &str, options: MarkdownOptions) -> String {
580        let mut md_options = Options::empty();
581        if options.tables {
582            md_options.insert(Options::ENABLE_TABLES);
583        }
584        if options.footnotes {
585            md_options.insert(Options::ENABLE_FOOTNOTES);
586        }
587        if options.strikethrough {
588            md_options.insert(Options::ENABLE_STRIKETHROUGH);
589        }
590        if options.tasklists {
591            md_options.insert(Options::ENABLE_TASKLISTS);
592        }
593
594        let parser = Parser::new_ext(string, md_options);
595        let mut html_output = String::new();
596        html::push_html(&mut html_output, parser);
597        html_output
598    }
599
600    /// Converts inline Markdown into HTML
601    pub fn inline_markdown(string: &str, options: MarkdownOptions) -> String {
602        // For inline markdown, we strip block elements
603        let html = Self::markdown(string, options);
604        let re = Regex::new(r"</?(?:p|div|h[1-6]|blockquote|pre|ul|ol|li)[^>]*>").unwrap();
605        re.replace_all(&html, "").to_string()
606    }
607
608    /// Masks a portion of a string with a repeated character
609    pub fn mask(string: &str, character: char, index: isize, length: Option<usize>) -> String {
610        if character == '\0' {
611            return string.to_string();
612        }
613
614        let chars: Vec<char> = string.chars().collect();
615        let str_len = chars.len() as isize;
616
617        let start_index = if index < 0 {
618            if index < -str_len {
619                0
620            } else {
621                (str_len + index) as usize
622            }
623        } else {
624            if index >= str_len {
625                return string.to_string();
626            }
627            index as usize
628        };
629
630        let mask_length = length.unwrap_or(chars.len() - start_index);
631        let end_index = std::cmp::min(start_index + mask_length, chars.len());
632
633        let start: String = chars.iter().take(start_index).collect();
634        let mask: String = character.to_string().repeat(end_index - start_index);
635        let end: String = chars.iter().skip(end_index).collect();
636
637        format!("{}{}{}", start, mask, end)
638    }
639
640    /// Get the string matching the given pattern
641    pub fn match_pattern(pattern: &str, subject: &str) -> String {
642        if let Ok(re) = Regex::new(pattern) {
643            if let Some(caps) = re.captures(subject) {
644                if let Some(group1) = caps.get(1) {
645                    group1.as_str().to_string()
646                } else if let Some(group0) = caps.get(0) {
647                    group0.as_str().to_string()
648                } else {
649                    String::new()
650                }
651            } else {
652                String::new()
653            }
654        } else {
655            String::new()
656        }
657    }
658
659    /// Determine if a given string matches a given pattern
660    pub fn is_match(patterns: &[&str], value: &str) -> bool {
661        for pattern in patterns {
662            if let Ok(re) = Regex::new(pattern)
663                && re.is_match(value)
664            {
665                return true;
666            }
667        }
668        false
669    }
670
671    /// Get all strings matching the given pattern
672    pub fn match_all(pattern: &str, subject: &str) -> Vec<String> {
673        if let Ok(re) = Regex::new(pattern) {
674            re.find_iter(subject)
675                .map(|m| m.as_str().to_string())
676                .collect()
677        } else {
678            Vec::new()
679        }
680    }
681
682    /// Remove all non-numeric characters from a string
683    pub fn numbers(value: &str) -> String {
684        value.chars().filter(|c| c.is_numeric()).collect()
685    }
686
687    /// Pad both sides of a string with another
688    pub fn pad_both(value: &str, length: usize, pad: &str) -> String {
689        let current_len = Self::length(value);
690        if current_len >= length {
691            return value.to_string();
692        }
693
694        let total_padding = length - current_len;
695        let left_padding = total_padding / 2;
696        let right_padding = total_padding - left_padding;
697
698        let left_pad = pad.repeat(left_padding.div_ceil(pad.len()));
699        let right_pad = pad.repeat(right_padding.div_ceil(pad.len()));
700
701        format!(
702            "{}{}{}",
703            &left_pad[..left_padding.min(left_pad.len())],
704            value,
705            &right_pad[..right_padding.min(right_pad.len())]
706        )
707    }
708
709    /// Pad the left side of a string with another
710    pub fn pad_left(value: &str, length: usize, pad: &str) -> String {
711        let current_len = Self::length(value);
712        if current_len >= length {
713            return value.to_string();
714        }
715
716        let padding_needed = length - current_len;
717        let pad_string = pad.repeat(padding_needed.div_ceil(pad.len()));
718
719        format!(
720            "{}{}",
721            &pad_string[..padding_needed.min(pad_string.len())],
722            value
723        )
724    }
725
726    /// Pad the right side of a string with another
727    pub fn pad_right(value: &str, length: usize, pad: &str) -> String {
728        let current_len = Self::length(value);
729        if current_len >= length {
730            return value.to_string();
731        }
732
733        let padding_needed = length - current_len;
734        let pad_string = pad.repeat(padding_needed.div_ceil(pad.len()));
735
736        format!(
737            "{}{}",
738            value,
739            &pad_string[..padding_needed.min(pad_string.len())]
740        )
741    }
742
743    /// Parse a Class[@]method style callback into class and method
744    pub fn parse_callback(callback: &str, default: Option<&str>) -> (String, Option<String>) {
745        if callback.contains("@anonymous") {
746            let at_count = callback.matches('@').count();
747            if at_count > 1 {
748                let parts: Vec<&str> = callback.rsplitn(2, '@').collect();
749                return (parts[1].to_string(), Some(parts[0].to_string()));
750            }
751            return (callback.to_string(), default.map(|s| s.to_string()));
752        }
753
754        if callback.contains('@') {
755            let parts: Vec<&str> = callback.splitn(2, '@').collect();
756            (parts[0].to_string(), Some(parts[1].to_string()))
757        } else {
758            (callback.to_string(), default.map(|s| s.to_string()))
759        }
760    }
761
762    /// Get the plural form of an English word
763    pub fn plural(value: &str, count: i32, prepend_count: bool) -> String {
764        let plural_form = if count == 1 {
765            value.to_string()
766        } else {
767            for (rule, replacement) in PLURAL_RULES.iter() {
768                if rule.is_match(value) {
769                    return if prepend_count {
770                        format!("{} {}", count, rule.replace(value, *replacement))
771                    } else {
772                        rule.replace(value, *replacement).to_string()
773                    };
774                }
775            }
776            format!("{}s", value) // fallback
777        };
778
779        if prepend_count {
780            format!("{} {}", count, plural_form)
781        } else {
782            plural_form
783        }
784    }
785
786    /// Pluralize the last word of an English, studly caps case string
787    pub fn plural_studly(value: &str, count: i32) -> String {
788        let re = Regex::new(r"([a-z])([A-Z])").unwrap();
789        let with_spaces = re.replace_all(value, "$1 $2");
790        let parts: Vec<&str> = with_spaces.split_whitespace().collect();
791
792        if let Some(last_word) = parts.last() {
793            let mut result = parts[..parts.len() - 1].join("");
794            result.push_str(&Self::plural(last_word, count, false));
795            result
796        } else {
797            Self::plural(value, count, false)
798        }
799    }
800
801    /// Pluralize the last word of an English, Pascal caps case string
802    pub fn plural_pascal(value: &str, count: i32) -> String {
803        Self::plural_studly(value, count)
804    }
805
806    /// Generate a random, secure password
807    pub fn password(
808        length: usize,
809        letters: bool,
810        numbers: bool,
811        symbols: bool,
812        spaces: bool,
813    ) -> String {
814        let mut chars = Vec::new();
815
816        if letters {
817            chars.extend_from_slice(&[
818                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
819                'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F',
820                'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
821                'W', 'X', 'Y', 'Z',
822            ]);
823        }
824
825        if numbers {
826            chars.extend_from_slice(&['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']);
827        }
828
829        if symbols {
830            chars.extend_from_slice(&[
831                '~', '!', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '.', ',', '<', '>',
832                '?', '/', '\\', '{', '}', '[', ']', '|', ':', ';',
833            ]);
834        }
835
836        if spaces {
837            chars.push(' ');
838        }
839
840        if chars.is_empty() {
841            return String::new();
842        }
843
844        let mut rng = rand::rng();
845        (0..length)
846            .map(|_| chars[rng.random_range(0..chars.len())])
847            .collect()
848    }
849
850    /// Find the multi-byte safe position of the first occurrence of a given substring
851    pub fn position(haystack: &str, needle: &str, offset: usize) -> Option<usize> {
852        let chars: Vec<char> = haystack.chars().collect();
853        if offset >= chars.len() {
854            return None;
855        }
856
857        let search_slice: String = chars.iter().skip(offset).collect();
858        if let Some(pos) = search_slice.find(needle) {
859            let chars_before_match: String = chars.iter().take(offset).collect();
860            Some(chars_before_match.len() + pos)
861        } else {
862            None
863        }
864    }
865
866    /// Generate a more truly "random" alpha-numeric string
867    pub fn random(length: usize) -> String {
868        // Check for sequence first
869        {
870            let mut sequence = RANDOM_SEQUENCE.lock().unwrap();
871            if let Some((seq, index)) = sequence.as_mut()
872                && *index < seq.len()
873            {
874                let result = seq[*index].clone();
875                *index += 1;
876                return result;
877            }
878        }
879
880        if let Some(factory) = RANDOM_STRING_FACTORY.get() {
881            return factory(length);
882        }
883
884        let charset: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
885        let mut rng = rand::rng();
886
887        (0..length)
888            .map(|_| {
889                let idx = rng.random_range(0..charset.len());
890                charset[idx] as char
891            })
892            .collect()
893    }
894
895    /// Set the callable that will be used to generate random strings
896    pub fn create_random_strings_using<F>(factory: F)
897    where
898        F: Fn(usize) -> String + Send + Sync + 'static,
899    {
900        let _ = RANDOM_STRING_FACTORY.set(Box::new(factory));
901    }
902
903    /// Set the sequence that will be used to generate random strings
904    pub fn create_random_strings_using_sequence(sequence: Vec<String>) {
905        let mut seq_guard = RANDOM_SEQUENCE.lock().unwrap();
906        *seq_guard = Some((sequence, 0));
907    }
908
909    /// Indicate that random strings should be created normally
910    pub fn create_random_strings_normally() {
911        // Clear the factory and sequence
912        // Note: OnceLock doesn't have a clear method, so we'd need to restructure
913        // For now, we'll clear the sequence
914        let mut seq_guard = RANDOM_SEQUENCE.lock().unwrap();
915        *seq_guard = None;
916    }
917
918    /// Repeat the given string
919    pub fn repeat(string: &str, times: usize) -> String {
920        string.repeat(times)
921    }
922
923    /// Replace a given value in the string sequentially with an array
924    pub fn replace_array(search: &str, replace: &[&str], subject: &str) -> String {
925        let segments: Vec<&str> = subject.split(search).collect();
926        let mut result = segments[0].to_string();
927
928        for (i, segment) in segments.iter().skip(1).enumerate() {
929            let replacement = replace.get(i).unwrap_or(&search);
930            result.push_str(replacement);
931            result.push_str(segment);
932        }
933
934        result
935    }
936
937    /// Replace the given value in the given string
938    pub fn replace(
939        search: &[&str],
940        replace: &[&str],
941        subject: &str,
942        case_sensitive: bool,
943    ) -> String {
944        let mut result = subject.to_string();
945
946        // Use a unique placeholder to avoid double replacement
947        let mut placeholders = Vec::new();
948
949        for (i, &search_term) in search.iter().enumerate() {
950            let placeholder = format!("__PLACEHOLDER_{}__", i);
951            placeholders.push(placeholder.clone());
952
953            if case_sensitive {
954                result = result.replace(search_term, &placeholder);
955            } else {
956                let re = Regex::new(&format!("(?i){}", regex::escape(search_term))).unwrap();
957                result = re.replace_all(&result, placeholder.as_str()).to_string();
958            }
959        }
960
961        // Replace placeholders with actual replacements
962        for (i, placeholder) in placeholders.iter().enumerate() {
963            let replacement = replace.get(i).unwrap_or(&"");
964            result = result.replace(placeholder, replacement);
965        }
966
967        result
968    }
969
970    /// Replace the first occurrence of a given value in the string
971    pub fn replace_first(search: &str, replace: &str, subject: &str) -> String {
972        if search.is_empty() {
973            return subject.to_string();
974        }
975
976        if let Some(pos) = subject.find(search) {
977            let mut result = String::new();
978            result.push_str(&subject[..pos]);
979            result.push_str(replace);
980            result.push_str(&subject[pos + search.len()..]);
981            result
982        } else {
983            subject.to_string()
984        }
985    }
986
987    /// Replace the first occurrence of the given value if it appears at the start
988    pub fn replace_start(search: &str, replace: &str, subject: &str) -> String {
989        if search.is_empty() {
990            return subject.to_string();
991        }
992
993        if subject.starts_with(search) {
994            Self::replace_first(search, replace, subject)
995        } else {
996            subject.to_string()
997        }
998    }
999
1000    /// Replace the last occurrence of a given value in the string
1001    pub fn replace_last(search: &str, replace: &str, subject: &str) -> String {
1002        if search.is_empty() {
1003            return subject.to_string();
1004        }
1005
1006        if let Some(pos) = subject.rfind(search) {
1007            let mut result = String::new();
1008            result.push_str(&subject[..pos]);
1009            result.push_str(replace);
1010            result.push_str(&subject[pos + search.len()..]);
1011            result
1012        } else {
1013            subject.to_string()
1014        }
1015    }
1016
1017    /// Replace the last occurrence of a given value if it appears at the end
1018    pub fn replace_end(search: &str, replace: &str, subject: &str) -> String {
1019        if search.is_empty() {
1020            return subject.to_string();
1021        }
1022
1023        if subject.ends_with(search) {
1024            Self::replace_last(search, replace, subject)
1025        } else {
1026            subject.to_string()
1027        }
1028    }
1029
1030    /// Replace the patterns matching the given regular expression
1031    pub fn replace_matches(
1032        pattern: &str,
1033        replace: &str,
1034        subject: &str,
1035        limit: Option<usize>,
1036    ) -> String {
1037        if let Ok(re) = Regex::new(pattern) {
1038            match limit {
1039                Some(n) => re.replacen(subject, n, replace).to_string(),
1040                None => re.replace_all(subject, replace).to_string(),
1041            }
1042        } else {
1043            subject.to_string()
1044        }
1045    }
1046
1047    /// Remove any occurrence of the given string in the subject
1048    pub fn remove(search: &[&str], subject: &str, case_sensitive: bool) -> String {
1049        let empty_replace: Vec<&str> = search.iter().map(|_| "").collect();
1050        Self::replace(search, &empty_replace, subject, case_sensitive)
1051    }
1052
1053    /// Reverse the given string
1054    pub fn reverse(value: &str) -> String {
1055        value.chars().rev().collect()
1056    }
1057
1058    /// Begin a string with a single instance of a given value
1059    pub fn start(value: &str, prefix: &str) -> String {
1060        let pattern = format!("^({})+", regex::escape(prefix));
1061        let re = Regex::new(&pattern).unwrap();
1062        let trimmed = re.replace_all(value, "");
1063        format!("{}{}", prefix, trimmed)
1064    }
1065
1066    /// Convert the given string to upper-case
1067    pub fn upper(value: &str) -> String {
1068        value.to_uppercase()
1069    }
1070
1071    /// Convert the given string to title case
1072    pub fn title(value: &str) -> String {
1073        value
1074            .split_whitespace()
1075            .map(Self::ucfirst)
1076            .collect::<Vec<_>>()
1077            .join(" ")
1078    }
1079
1080    /// Convert the given string to headline case
1081    pub fn headline(value: &str) -> String {
1082        let re = Regex::new(r"\s+").unwrap();
1083        let words: Vec<&str> = re.split(value).collect();
1084
1085        let processed: Vec<String> = if words.len() > 1 {
1086            words.iter().map(|word| Self::title(word)).collect()
1087        } else {
1088            Self::uc_split(value)
1089                .iter()
1090                .map(|word| Self::title(word))
1091                .collect()
1092        };
1093
1094        let collapsed = Self::replace(
1095            &["-", "_", " "],
1096            &["_", "_", "_"],
1097            &processed.join("_"),
1098            true,
1099        );
1100        let parts: Vec<&str> = collapsed.split('_').filter(|s| !s.is_empty()).collect();
1101        parts.join(" ")
1102    }
1103
1104    /// Convert the given string to APA-style title case
1105    pub fn apa(value: &str) -> String {
1106        if value.trim().is_empty() {
1107            return value.to_string();
1108        }
1109
1110        let minor_words = [
1111            "and", "as", "but", "for", "if", "nor", "or", "so", "yet", "a", "an", "the", "at",
1112            "by", "for", "in", "of", "off", "on", "per", "to", "up", "via",
1113        ];
1114
1115        let end_punctuation = ['.', '!', '?', ':', '—', ','];
1116        let words: Vec<&str> = value.split_whitespace().collect();
1117
1118        let mut result = Vec::new();
1119
1120        for (i, word) in words.iter().enumerate() {
1121            let lowercase_word = word.to_lowercase();
1122
1123            if word.contains('-') {
1124                let hyphenated: Vec<&str> = word.split('-').collect();
1125                let processed: Vec<String> = hyphenated
1126                    .iter()
1127                    .map(|part| {
1128                        let lower_part = part.to_lowercase();
1129                        if minor_words.contains(&lower_part.as_str()) && part.len() <= 3 {
1130                            lower_part
1131                        } else {
1132                            Self::ucfirst(part)
1133                        }
1134                    })
1135                    .collect();
1136                result.push(processed.join("-"));
1137            } else if minor_words.contains(&lowercase_word.as_str())
1138                && word.len() <= 3
1139                && i > 0
1140                && !end_punctuation.contains(&words[i - 1].chars().last().unwrap_or(' '))
1141            {
1142                result.push(lowercase_word);
1143            } else {
1144                result.push(Self::ucfirst(word));
1145            }
1146        }
1147
1148        result.join(" ")
1149    }
1150
1151    /// Get the singular form of an English word
1152    pub fn singular(value: &str) -> String {
1153        for (rule, replacement) in SINGULAR_RULES.iter() {
1154            if rule.is_match(value) {
1155                return rule.replace(value, *replacement).to_string();
1156            }
1157        }
1158        value.to_string()
1159    }
1160
1161    /// Generate a URL friendly "slug" from a given string
1162    pub fn slug(
1163        title: &str,
1164        separator: &str,
1165        language: Option<&str>,
1166        dictionary: Option<HashMap<String, String>>,
1167    ) -> String {
1168        let mut title = if language.is_some() {
1169            Self::ascii(title)
1170        } else {
1171            title.to_string()
1172        };
1173
1174        // Convert all dashes/underscores into separator
1175        let flip = if separator == "-" { "_" } else { "-" };
1176        let pattern = format!("[{}]+", regex::escape(flip));
1177        let re = Regex::new(&pattern).unwrap();
1178        title = re.replace_all(&title, separator).to_string();
1179
1180        // Replace dictionary words
1181        if let Some(dict) = dictionary {
1182            for (key, value) in dict {
1183                let replacement = format!("{}{}{}", separator, value, separator);
1184                title = title.replace(&key, &replacement);
1185            }
1186        } else {
1187            // Default dictionary
1188            let replacement = format!("{}at{}", separator, separator);
1189            title = title.replace("@", &replacement);
1190        }
1191
1192        // Remove all characters that are not the separator, letters, numbers, or whitespace
1193        let pattern = format!("[^{}\\p{{L}}\\p{{N}}\\s]+", regex::escape(separator));
1194        let re = Regex::new(&pattern).unwrap();
1195        title = re.replace_all(&Self::lower(&title), "").to_string();
1196
1197        // Replace all separator characters and whitespace by a single separator
1198        let pattern = format!("[{}\\s]+", regex::escape(separator));
1199        let re = Regex::new(&pattern).unwrap();
1200        title = re.replace_all(&title, separator).to_string();
1201
1202        title
1203            .trim_matches(separator.chars().next().unwrap_or('-'))
1204            .to_string()
1205    }
1206
1207    /// Convert a string to snake case
1208    pub fn snake(value: &str, delimiter: &str) -> String {
1209        let cache_key = format!("{}:{}", value, delimiter);
1210        let cache = SNAKE_CACHE.lock().unwrap();
1211        if let Some(cached) = cache.get(&cache_key) {
1212            return cached.clone();
1213        }
1214        drop(cache);
1215
1216        if value
1217            .chars()
1218            .all(|c| c.is_lowercase() || !c.is_alphabetic())
1219        {
1220            let mut cache = SNAKE_CACHE.lock().unwrap();
1221            cache.insert(cache_key, value.to_string());
1222            return value.to_string();
1223        }
1224
1225        // Replace spaces with delimiter, then handle camelCase
1226        let no_spaces = value.replace(' ', delimiter);
1227
1228        let re = Regex::new(r"([a-z])([A-Z])").unwrap();
1229        let with_delim = re.replace_all(&no_spaces, |caps: &regex::Captures| {
1230            let first = &caps[1];
1231            let second = &caps[2];
1232
1233            format!("{}{}{}", first, delimiter, second)
1234        });
1235
1236        let result = with_delim.to_lowercase();
1237
1238        let mut cache = SNAKE_CACHE.lock().unwrap();
1239        cache.insert(cache_key, result.clone());
1240        result
1241    }
1242
1243    /// Remove all whitespace from both ends of a string
1244    pub fn trim(value: &str) -> String {
1245        Self::trim_custom(value, None)
1246    }
1247
1248    /// Remove all whitespace from both ends of a string with custom character list
1249    pub fn trim_custom(value: &str, charlist: Option<&str>) -> String {
1250        match charlist {
1251            Some(chars) => value.trim_matches(|c| chars.contains(c)).to_string(),
1252            None => {
1253                let invisible_chars: Vec<char> = INVISIBLE_CHARACTERS.chars().collect();
1254                let mut result = value.to_string();
1255
1256                // Trim from start
1257                while let Some(ch) = result.chars().next() {
1258                    if ch.is_whitespace() || invisible_chars.contains(&ch) {
1259                        result = result[ch.len_utf8()..].to_string();
1260                    } else {
1261                        break;
1262                    }
1263                }
1264
1265                // Trim from end
1266                while let Some(ch) = result.chars().last() {
1267                    if ch.is_whitespace() || invisible_chars.contains(&ch) {
1268                        let mut chars = result.chars();
1269                        chars.next_back();
1270                        result = chars.as_str().to_string();
1271                    } else {
1272                        break;
1273                    }
1274                }
1275
1276                result
1277            }
1278        }
1279    }
1280
1281    /// Remove all whitespace from the beginning of a string
1282    pub fn ltrim(value: &str, charlist: Option<&str>) -> String {
1283        match charlist {
1284            Some(chars) => value.trim_start_matches(|c| chars.contains(c)).to_string(),
1285            None => {
1286                let invisible_chars: Vec<char> = INVISIBLE_CHARACTERS.chars().collect();
1287                let mut result = value.to_string();
1288
1289                while let Some(ch) = result.chars().next() {
1290                    if ch.is_whitespace() || invisible_chars.contains(&ch) {
1291                        result = result[ch.len_utf8()..].to_string();
1292                    } else {
1293                        break;
1294                    }
1295                }
1296
1297                result
1298            }
1299        }
1300    }
1301
1302    /// Remove all whitespace from the end of a string
1303    pub fn rtrim(value: &str, charlist: Option<&str>) -> String {
1304        match charlist {
1305            Some(chars) => value.trim_end_matches(|c| chars.contains(c)).to_string(),
1306            None => {
1307                let invisible_chars: Vec<char> = INVISIBLE_CHARACTERS.chars().collect();
1308                let mut result = value.to_string();
1309
1310                while let Some(ch) = result.chars().last() {
1311                    if ch.is_whitespace() || invisible_chars.contains(&ch) {
1312                        let mut chars = result.chars();
1313                        chars.next_back();
1314                        result = chars.as_str().to_string();
1315                    } else {
1316                        break;
1317                    }
1318                }
1319
1320                result
1321            }
1322        }
1323    }
1324
1325    /// Remove all "extra" blank space from the given string
1326    pub fn squish(value: &str) -> String {
1327        let trimmed = Self::trim(value);
1328        let re = Regex::new(r"\s+").unwrap();
1329        re.replace_all(&trimmed, " ").to_string()
1330    }
1331
1332    /// Determine if a given string starts with a given substring
1333    pub fn starts_with(haystack: &str, needles: &[&str]) -> bool {
1334        for needle in needles {
1335            if !needle.is_empty() && haystack.starts_with(needle) {
1336                return true;
1337            }
1338        }
1339        false
1340    }
1341
1342    /// Determine if a given string doesn't start with a given substring
1343    pub fn doesnt_start_with(haystack: &str, needles: &[&str]) -> bool {
1344        !Self::starts_with(haystack, needles)
1345    }
1346
1347    /// Convert a value to studly caps case
1348    pub fn studly(value: &str) -> String {
1349        let cache = STUDLY_CACHE.lock().unwrap();
1350        if let Some(cached) = cache.get(value) {
1351            return cached.clone();
1352        }
1353        drop(cache);
1354
1355        let cleaned = value.replace(['-', '_'], " ");
1356        let words: Vec<&str> = cleaned.split_whitespace().collect();
1357        let result: String = words.iter().map(|word| Self::ucfirst(word)).collect();
1358
1359        let mut cache = STUDLY_CACHE.lock().unwrap();
1360        cache.insert(value.to_string(), result.clone());
1361        result
1362    }
1363
1364    /// Convert a value to Pascal case (alias for studly)
1365    pub fn pascal(value: &str) -> String {
1366        Self::studly(value)
1367    }
1368
1369    /// Returns the portion of the string specified by the start and length parameters
1370    pub fn substr(string: &str, start: isize, length: Option<usize>) -> String {
1371        let chars: Vec<char> = string.chars().collect();
1372        let str_len = chars.len() as isize;
1373
1374        let start_index = if start < 0 {
1375            if start < -str_len {
1376                0
1377            } else {
1378                (str_len + start) as usize
1379            }
1380        } else {
1381            if start >= str_len {
1382                return String::new();
1383            }
1384            start as usize
1385        };
1386
1387        match length {
1388            Some(len) => {
1389                let end_index = std::cmp::min(start_index + len, chars.len());
1390                chars
1391                    .iter()
1392                    .skip(start_index)
1393                    .take(end_index - start_index)
1394                    .collect()
1395            }
1396            None => chars.iter().skip(start_index).collect(),
1397        }
1398    }
1399
1400    /// Returns the number of substring occurrences
1401    pub fn substr_count(
1402        haystack: &str,
1403        needle: &str,
1404        offset: usize,
1405        length: Option<usize>,
1406    ) -> usize {
1407        let search_slice: String = match length {
1408            Some(len) => {
1409                let chars: Vec<char> = haystack.chars().collect();
1410                let end_index = std::cmp::min(offset + len, chars.len());
1411                if offset >= chars.len() {
1412                    return 0;
1413                }
1414                chars.iter().skip(offset).take(end_index - offset).collect()
1415            }
1416            None => {
1417                let chars: Vec<char> = haystack.chars().collect();
1418                if offset >= chars.len() {
1419                    return 0;
1420                }
1421                chars.iter().skip(offset).collect()
1422            }
1423        };
1424
1425        search_slice.matches(needle).count()
1426    }
1427
1428    /// Replace text within a portion of a string
1429    pub fn substr_replace(
1430        string: &str,
1431        replace: &str,
1432        offset: isize,
1433        length: Option<usize>,
1434    ) -> String {
1435        let chars: Vec<char> = string.chars().collect();
1436        let str_len = chars.len() as isize;
1437
1438        let start_index = if offset < 0 {
1439            if offset < -str_len {
1440                0
1441            } else {
1442                (str_len + offset) as usize
1443            }
1444        } else {
1445            if offset >= str_len {
1446                return format!("{}{}", string, replace);
1447            }
1448            offset as usize
1449        };
1450
1451        let replace_length = length.unwrap_or(chars.len() - start_index);
1452        let end_index = std::cmp::min(start_index + replace_length, chars.len());
1453
1454        let start: String = chars.iter().take(start_index).collect();
1455        let end: String = chars.iter().skip(end_index).collect();
1456
1457        format!("{}{}{}", start, replace, end)
1458    }
1459
1460    /// Swap multiple keywords in a string with other keywords
1461    pub fn swap(map: HashMap<String, String>, subject: &str) -> String {
1462        let mut result = subject.to_string();
1463        for (search, replace) in map {
1464            result = result.replace(&search, &replace);
1465        }
1466        result
1467    }
1468
1469    /// Take the first or last {$limit} characters of a string
1470    pub fn take(string: &str, limit: isize) -> String {
1471        if limit < 0 {
1472            Self::substr(string, limit, None)
1473        } else {
1474            Self::substr(string, 0, Some(limit as usize))
1475        }
1476    }
1477
1478    /// Convert the given string to Base64 encoding
1479    pub fn to_base64(string: &str) -> String {
1480        general_purpose::STANDARD.encode(string.as_bytes())
1481    }
1482
1483    /// Decode the given Base64 encoded string
1484    pub fn from_base64(string: &str, strict: bool) -> Result<String, base64::DecodeError> {
1485        let engine = if strict {
1486            general_purpose::STANDARD_NO_PAD
1487        } else {
1488            general_purpose::STANDARD
1489        };
1490
1491        let bytes = engine.decode(string)?;
1492        Ok(String::from_utf8_lossy(&bytes).to_string())
1493    }
1494
1495    /// Make a string's first character lowercase
1496    pub fn lcfirst(string: &str) -> String {
1497        let mut chars = string.chars();
1498        match chars.next() {
1499            None => String::new(),
1500            Some(first) => first.to_lowercase().collect::<String>() + chars.as_str(),
1501        }
1502    }
1503
1504    /// Make a string's first character uppercase
1505    pub fn ucfirst(string: &str) -> String {
1506        let mut chars = string.chars();
1507        match chars.next() {
1508            None => String::new(),
1509            Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
1510        }
1511    }
1512
1513    /// Split a string into pieces by uppercase characters
1514    pub fn uc_split(string: &str) -> Vec<String> {
1515        let mut result = Vec::new();
1516        let mut current = String::new();
1517
1518        for ch in string.chars() {
1519            if ch.is_uppercase() && !current.is_empty() {
1520                result.push(current);
1521                current = String::new();
1522            }
1523            current.push(ch);
1524        }
1525
1526        if !current.is_empty() {
1527            result.push(current);
1528        }
1529
1530        result
1531    }
1532
1533    /// Get the number of words a string contains
1534    pub fn word_count(string: &str, characters: Option<&str>) -> usize {
1535        if let Some(chars) = characters {
1536            // Custom word character definition
1537            let pattern = format!("[{}\\s]+", regex::escape(chars));
1538            let re = Regex::new(&pattern).unwrap();
1539            re.split(string).filter(|s| !s.is_empty()).count()
1540        } else {
1541            string.split_whitespace().count()
1542        }
1543    }
1544
1545    /// Wrap a string to a given number of characters
1546    pub fn word_wrap(
1547        string: &str,
1548        characters: usize,
1549        break_str: &str,
1550        cut_long_words: bool,
1551    ) -> String {
1552        if cut_long_words {
1553            textwrap::fill(string, characters)
1554        } else {
1555            let options = textwrap::Options::new(characters).break_words(false);
1556            textwrap::fill(string, options)
1557        }
1558        .replace('\n', break_str)
1559    }
1560
1561    /// Generate a UUID (version 4)
1562    pub fn uuid() -> Uuid {
1563        // Check for sequence first
1564        {
1565            let mut sequence = UUID_SEQUENCE.lock().unwrap();
1566            if let Some((seq, index)) = sequence.as_mut()
1567                && *index < seq.len()
1568            {
1569                let result = seq[*index];
1570                *index += 1;
1571                return result;
1572            }
1573        }
1574
1575        if let Some(factory) = UUID_FACTORY.get() {
1576            return factory();
1577        }
1578        Uuid::new_v4()
1579    }
1580
1581    /// Generate a UUID (version 7)
1582    pub fn uuid7(time: Option<OffsetDateTime>) -> Uuid {
1583        if let Some(factory) = UUID_FACTORY.get() {
1584            return factory();
1585        }
1586
1587        match time {
1588            Some(_) => {
1589                Uuid::new_v4()
1590            }
1591            None => Uuid::new_v4(),
1592        }
1593    }
1594
1595    /// Generate a time-ordered UUID
1596    pub fn ordered_uuid() -> Uuid {
1597        if let Some(factory) = UUID_FACTORY.get() {
1598            return factory();
1599        }
1600
1601        // Simplified implementation - in reality would use COMB UUID
1602        Uuid::new_v4()
1603    }
1604
1605    /// Set the callable that will be used to generate UUIDs
1606    pub fn create_uuids_using<F>(factory: F)
1607    where
1608        F: Fn() -> Uuid + Send + Sync + 'static,
1609    {
1610        let _ = UUID_FACTORY.set(Box::new(factory));
1611    }
1612
1613    /// Set the sequence that will be used to generate UUIDs
1614    pub fn create_uuids_using_sequence(sequence: Vec<Uuid>) {
1615        let mut seq_guard = UUID_SEQUENCE.lock().unwrap();
1616        *seq_guard = Some((sequence, 0));
1617    }
1618
1619    /// Always return the same UUID when generating new UUIDs
1620    pub fn freeze_uuids<F>(callback: Option<F>) -> Uuid
1621    where
1622        F: FnOnce(Uuid),
1623    {
1624        let uuid = Uuid::new_v4();
1625        Self::create_uuids_using(move || uuid);
1626
1627        if let Some(cb) = callback {
1628            cb(uuid);
1629            Self::create_uuids_normally();
1630        }
1631
1632        uuid
1633    }
1634
1635    /// Indicate that UUIDs should be created normally and not using a custom factory
1636    pub fn create_uuids_normally() {
1637        // Clear the sequence
1638        let mut seq_guard = UUID_SEQUENCE.lock().unwrap();
1639        *seq_guard = None;
1640    }
1641
1642    /// Generate a ULID
1643    pub fn ulid(time: Option<OffsetDateTime>) -> Ulid {
1644        // Check for sequence first
1645        {
1646            let mut sequence = ULID_SEQUENCE.lock().unwrap();
1647
1648            if let Some((seq, index)) = sequence.as_mut()
1649                && *index < seq.len()
1650            {
1651                let result = seq[*index];
1652                *index += 1;
1653                return result;
1654            }
1655        }
1656
1657        if let Some(factory) = ULID_FACTORY.get() {
1658            return factory();
1659        }
1660
1661        match time {
1662            Some(_) => {
1663                Ulid::new()
1664            }
1665            None => Ulid::new(),
1666        }
1667    }
1668
1669    /// Indicate that ULIDs should be created normally and not using a custom factory
1670    pub fn create_ulids_normally() {
1671        let mut seq_guard = ULID_SEQUENCE.lock().unwrap();
1672        *seq_guard = None;
1673    }
1674
1675    /// Set the callable that will be used to generate ULIDs
1676    pub fn create_ulids_using<F>(factory: F)
1677    where
1678        F: Fn() -> Ulid + Send + Sync + 'static,
1679    {
1680        let _ = ULID_FACTORY.set(Box::new(factory));
1681    }
1682
1683    /// Set the sequence that will be used to generate ULIDs
1684    pub fn create_ulids_using_sequence(sequence: Vec<Ulid>) {
1685        let mut seq_guard = ULID_SEQUENCE.lock().unwrap();
1686        *seq_guard = Some((sequence, 0));
1687    }
1688
1689    /// Always return the same ULID when generating new ULIDs
1690    pub fn freeze_ulids<F>(callback: Option<F>) -> Ulid
1691    where
1692        F: FnOnce(Ulid),
1693    {
1694        let ulid = Ulid::new();
1695        Self::create_ulids_using(move || ulid);
1696
1697        if let Some(cb) = callback {
1698            cb(ulid);
1699            Self::create_ulids_normally();
1700        }
1701
1702        ulid
1703    }
1704
1705    /// Remove all strings from the casing caches
1706    pub fn flush_cache() {
1707        let mut snake_cache = SNAKE_CACHE.lock().unwrap();
1708        let mut camel_cache = CAMEL_CACHE.lock().unwrap();
1709        let mut studly_cache = STUDLY_CACHE.lock().unwrap();
1710
1711        snake_cache.clear();
1712        camel_cache.clear();
1713        studly_cache.clear();
1714    }
1715
1716    /// Split a string by the given delimiter.
1717    ///
1718    /// Behaves like PHP's `explode`:
1719    /// - Empty parts are preserved
1720    /// - If delimiter is empty, splits into Unicode scalar values
1721    ///
1722    /// # Example
1723    /// ```rust
1724    /// use illuminate_str::Str;
1725    /// let v = Str::explode("a,,b", ",");
1726    /// assert_eq!(v, vec!["a", "", "b"]);
1727    /// ```
1728    pub fn explode(s: &str, delimiter: &str) -> Vec<String> {
1729        if delimiter.is_empty() {
1730            return s.chars().map(|c| c.to_string()).collect();
1731        }
1732
1733        // split preserves empty segments => same behavior
1734        s.split(delimiter).map(String::from).collect()
1735    }
1736
1737    /// Join string parts using the given delimiter.
1738    ///
1739    /// Accepts any iterator of string-like values.
1740    ///
1741    /// # Example
1742    /// ```rust
1743    /// use illuminate_str::Str;
1744    /// let s = Str::implode("-", ["a", "b", "c"]);
1745    /// assert_eq!(s, "a-b-c");
1746    /// ```
1747    pub fn implode<I, S>(delimiter: &str, parts: I) -> String
1748    where
1749        I: IntoIterator<Item = S>,
1750        S: AsRef<str>,
1751    {
1752        let mut iter = parts.into_iter();
1753
1754        let first = match iter.next() {
1755            Some(v) => v,
1756            None => return String::new(),
1757        };
1758
1759        let first_ref = first.as_ref();
1760        let remaining_lower = iter.size_hint().0;
1761        let capacity = first_ref.len().saturating_add(remaining_lower.saturating_mul(delimiter.len()));
1762        let mut out = String::with_capacity(capacity);
1763        out.push_str(first_ref);
1764
1765        for part in iter {
1766            out.push_str(delimiter);
1767            out.push_str(part.as_ref());
1768        }
1769
1770        out
1771    }
1772
1773    /// Limit a string by number of words.
1774    ///
1775    /// Words are detected using Unicode whitespace.
1776    /// If the string exceeds the limit, `end` is appended.
1777    ///
1778    /// # Example
1779    /// ```rust
1780    /// use illuminate_str::Str;
1781    /// let s = Str::limit_words("hello world from rust", 2, "...");
1782    /// assert_eq!(s, "hello world...");
1783    /// ```
1784    pub fn limit_words(s: &str, count: usize, end: &str) -> String {
1785        if count == 0 {
1786            return end.to_owned();
1787        }
1788
1789        let mut iter = s.split_whitespace();
1790        let mut out = String::new();
1791
1792        for i in 0..count {
1793            match iter.next() {
1794                Some(word) => {
1795                    if i > 0 {
1796                        out.push(' ');
1797                    }
1798                    out.push_str(word);
1799                }
1800                None => {
1801                    // Fewer words than the limit, so we are done.
1802                    break;
1803                }
1804            }
1805        }
1806
1807        if iter.next().is_some() {
1808            out.push_str(end);
1809        }
1810
1811        out
1812    }
1813}
1814
1815// Enums and structs for various options
1816
1817#[derive(Debug, Clone, Copy)]
1818pub enum CaseMode {
1819    Upper,
1820    Lower,
1821    Title,
1822    Fold,
1823}
1824
1825#[derive(Debug, Clone)]
1826pub struct ExcerptOptions {
1827    pub radius: usize,
1828    pub omission: String,
1829}
1830
1831impl Default for ExcerptOptions {
1832    fn default() -> Self {
1833        Self {
1834            radius: 100,
1835            omission: "...".to_string(),
1836        }
1837    }
1838}
1839
1840#[derive(Debug, Clone)]
1841pub struct MarkdownOptions {
1842    pub tables: bool,
1843    pub footnotes: bool,
1844    pub strikethrough: bool,
1845    pub tasklists: bool,
1846}
1847
1848impl Default for MarkdownOptions {
1849    fn default() -> Self {
1850        Self {
1851            tables: true,
1852            footnotes: true,
1853            strikethrough: true,
1854            tasklists: true,
1855        }
1856    }
1857}
1858
1859#[derive(Debug, Clone, Copy)]
1860pub enum UuidVersion {
1861    Nil,
1862    V1,
1863    V3,
1864    V4,
1865    V5,
1866    Max,
1867}
1868
1869#[cfg(test)]
1870mod tests {
1871    use super::*;
1872
1873    #[test]
1874    fn test_after() {
1875        assert_eq!(Str::after("This is my name", "This is"), " my name");
1876        assert_eq!(Str::after("App\\Class@method", "@"), "method");
1877    }
1878
1879    #[test]
1880    fn test_after_last() {
1881        assert_eq!(Str::after_last("yvette@yvette@gmail.com", "@"), "gmail.com");
1882    }
1883
1884    #[test]
1885    fn test_ascii() {
1886        assert_eq!(Str::ascii("ñ"), "n");
1887        assert_eq!(Str::ascii("üñíçødé"), "unicode");
1888    }
1889
1890    #[test]
1891    fn test_before() {
1892        assert_eq!(Str::before("This is my name", "my name"), "This is ");
1893        assert_eq!(Str::before("App\\Class@method", "@"), "App\\Class");
1894    }
1895
1896    #[test]
1897    fn test_before_last() {
1898        assert_eq!(
1899            Str::before_last("yvette@yvette@gmail.com", "@"),
1900            "yvette@yvette"
1901        );
1902    }
1903
1904    #[test]
1905    fn test_between() {
1906        assert_eq!(Str::between("This is my name", "This", "name"), " is my ");
1907        assert_eq!(Str::between("App\\Class@method", "\\", "@"), "Class");
1908    }
1909
1910    #[test]
1911    fn test_between_first() {
1912        assert_eq!(Str::between_first("[a] bc [d]", "[", "]"), "a");
1913    }
1914
1915    #[test]
1916    fn test_camel() {
1917        assert_eq!(Str::camel("foo_bar"), "fooBar");
1918        assert_eq!(Str::camel("foo-bar"), "fooBar");
1919        assert_eq!(Str::camel("FooBar"), "fooBar");
1920    }
1921
1922    #[test]
1923    fn test_char_at() {
1924        assert_eq!(Str::char_at("This is my name", 6), Some('s'));
1925        assert_eq!(Str::char_at("This is my name", -1), Some('e'));
1926        assert_eq!(Str::char_at("This is my name", 100), None);
1927    }
1928
1929    #[test]
1930    fn test_contains() {
1931        assert!(Str::contains("This is my name", &["my"], false));
1932        assert!(!Str::contains("This is my name", &["hello"], false));
1933        assert!(Str::contains("This is my name", &["MY"], true));
1934    }
1935
1936    #[test]
1937    fn test_contains_large() {
1938        let lorem_ipsum = include_str!("../lorem_ipsum.txt");
1939        assert!(Str::contains(
1940            lorem_ipsum,
1941            &[
1942                "Cras lobortis lorem ac efficitur egestas. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Mauris lacinia volutpat velit, pharetra tincidunt tortor vestibulum eu. Phasellus consectetur molestie nibh vitae ornare. Vivamus fringilla nunc facilisis velit commodo finibus."
1943            ],
1944            false
1945        ));
1946        assert!(Str::contains(
1947            lorem_ipsum,
1948            &[
1949                "Nulla facilisi. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae;"
1950            ],
1951            false
1952        ));
1953        assert!(Str::contains(
1954            lorem_ipsum,
1955            &[
1956                "Quisque in lectus dapibus, rhoncus massa non, sodales velit. Quisque laoreet leo sit amet lectus efficitur, ac facilisis sem ultrices. Praesent ullamcorper lectus et ultrices pulvinar. Praesent ac fringilla enim. Sed eu hendrerit lectus. Aenean maximus nulla ut faucibus rhoncus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent metus mauris, fringilla et vestibulum eget, tempus vitae erat. Fusce pulvinar bibendum urna sit amet tempus. Vivamus luctus facilisis faucibus. Sed pharetra, elit nec porttitor bibendum, nulla nibh dictum lectus, quis elementum purus arcu vel magna. Vestibulum at neque justo. Morbi scelerisque tortor a elementum hendrerit. Cras dapibus sit amet libero consequat tincidunt."
1957            ],
1958            false
1959        ));
1960        assert!(Str::contains(lorem_ipsum, &[
1961            "Ut tellus risus, elementum sed mauris at, consequat luctus sapien. Suspendisse accumsan, nulla ut tristique ullamcorper, nisi lectus egestas nibh, efficitur imperdiet sem nisl ac nisi. In lacinia in mauris sed hendrerit. Praesent maximus imperdiet sem ut malesuada. Sed quis congue purus, vel condimentum odio. Aliquam erat volutpat. Integer vel nibh non ipsum gravida dignissim. Proin luctus, turpis ac aliquam ultricies, ligula arcu fermentum neque, in facilisis felis lectus sed libero. Mauris lobortis, nulla at convallis efficitur, mi quam finibus metus, eu tempus nisi magna ac ex. Nunc eget sapien aliquam, vestibulum nisl non, dictum tortor.
1962
1963Vestibulum sollicitudin nisi sed metus vehicula, eu pulvinar enim faucibus. Praesent feugiat vulputate orci non ultrices. Maecenas scelerisque mauris eu purus cursus, ut sollicitudin eros tincidunt. Morbi eget libero tellus. Sed pulvinar in quam sit amet sagittis. Nam malesuada congue odio vel sagittis. Curabitur rhoncus mollis ante a elementum. Aliquam volutpat tempor turpis, at dapibus lectus auctor sit amet. Aliquam venenatis a elit quis euismod. Ut faucibus lacinia ante ac porttitor. Nullam malesuada ex purus, in convallis risus pulvinar id. Etiam ut dolor neque. Pellentesque sed orci ultricies, iaculis velit eu, molestie sapien."
1964        ], false))
1965    }
1966
1967    #[test]
1968    fn test_contains_all() {
1969        assert!(Str::contains_all("This is my name", &["This", "my"], false));
1970        assert!(!Str::contains_all(
1971            "This is my name",
1972            &["This", "hello"],
1973            false
1974        ));
1975    }
1976
1977    #[test]
1978    fn test_deduplicate() {
1979        assert_eq!(Str::deduplicate("Hello    World", &[' ']), "Hello World");
1980        assert_eq!(Str::deduplicate("aabbcc", &['a', 'b']), "abcc");
1981    }
1982
1983    #[test]
1984    fn test_ends_with() {
1985        assert!(Str::ends_with("Hello World", &["World"]));
1986        assert!(!Str::ends_with("Hello World", &["Hello"]));
1987    }
1988
1989    #[test]
1990    fn test_excerpt() {
1991        let options = ExcerptOptions::default();
1992        let result = Str::excerpt(
1993            "This is a very long string that contains the word Laravel somewhere in the middle",
1994            "Laravel",
1995            options,
1996        );
1997        assert!(result.is_some());
1998        assert!(result.unwrap().contains("Laravel"));
1999    }
2000
2001    #[test]
2002    fn test_finish() {
2003        assert_eq!(Str::finish("this/string", "/"), "this/string/");
2004        assert_eq!(Str::finish("this/string/", "/"), "this/string/");
2005    }
2006
2007    #[test]
2008    fn test_is_ascii() {
2009        assert!(Str::is_ascii("Taylor"));
2010        assert!(!Str::is_ascii("ñ"));
2011    }
2012
2013    #[test]
2014    fn test_is_json() {
2015        assert!(Str::is_json(r#"{"name":"John","age":30}"#));
2016        assert!(!Str::is_json("not json"));
2017    }
2018
2019    #[test]
2020    fn test_is_url() {
2021        assert!(Str::is_url("https://laravel.com", None));
2022        assert!(!Str::is_url("not a url", None));
2023    }
2024
2025    #[test]
2026    fn test_is_uuid() {
2027        assert!(Str::is_uuid("a0a2a2d2-0b87-4a18-83f2-2529882be2de", None));
2028        assert!(!Str::is_uuid("not a uuid", None));
2029    }
2030
2031    #[test]
2032    fn test_kebab() {
2033        assert_eq!(Str::kebab("fooBar"), "foo-bar");
2034    }
2035
2036    #[test]
2037    fn test_length() {
2038        assert_eq!(Str::length("Laravel"), 7);
2039        assert_eq!(Str::length("😀😃😄😁"), 4);
2040    }
2041
2042    #[test]
2043    fn test_limit() {
2044        assert_eq!(
2045            Str::limit(
2046                "The quick brown fox jumps over the lazy dog",
2047                20,
2048                "...",
2049                false
2050            ),
2051            "The quick brown fox ..."
2052        );
2053    }
2054
2055    #[test]
2056    fn test_lower() {
2057        assert_eq!(Str::lower("LARAVEL"), "laravel");
2058    }
2059
2060    #[test]
2061    fn test_mask() {
2062        assert_eq!(
2063            Str::mask("taylor@example.com", '*', 3, Some(10)),
2064            "tay**********e.com"
2065        );
2066    }
2067
2068    #[test]
2069    fn test_numbers() {
2070        assert_eq!(Str::numbers("Laravel 9.0"), "90");
2071    }
2072
2073    #[test]
2074    fn test_pad_left() {
2075        assert_eq!(Str::pad_left("James", 10, " "), "     James");
2076    }
2077
2078    #[test]
2079    fn test_pad_right() {
2080        assert_eq!(Str::pad_right("James", 10, "-"), "James-----");
2081    }
2082
2083    #[test]
2084    fn test_plural() {
2085        assert_eq!(Str::plural("car", 1, false), "car");
2086        assert_eq!(Str::plural("car", 2, false), "cars");
2087        assert_eq!(Str::plural("child", 2, false), "children");
2088        assert_eq!(Str::plural("man", 2, false), "men");
2089        assert_eq!(Str::plural("woman", 2, false), "women");
2090        assert_eq!(Str::plural("person", 2, false), "people");
2091        assert_eq!(Str::plural("thief", 2, false), "thieves");
2092        assert_eq!(Str::plural("foot", 2, false), "feet");
2093        assert_eq!(Str::plural("foot", 2, false), "feet");
2094        assert_eq!(Str::plural("medium", 2, false), "media");
2095        assert_eq!(Str::plural("hoax", 2, false), "hoaxes");
2096    }
2097
2098    #[test]
2099    fn test_random() {
2100        let random1 = Str::random(10);
2101        let random2 = Str::random(10);
2102        assert_eq!(random1.len(), 10);
2103        assert_eq!(random2.len(), 10);
2104        assert_ne!(random1, random2);
2105    }
2106
2107    #[test]
2108    fn test_remove() {
2109        assert_eq!(
2110            Str::remove(
2111                &["e"],
2112                "Peter Piper picked a peck of pickled peppers.",
2113                true
2114            ),
2115            "Ptr Pipr pickd a pck of pickld ppprs."
2116        );
2117    }
2118
2119    #[test]
2120    fn test_replace() {
2121        assert_eq!(
2122            Str::replace(&["9.x", "10.x"], &["10.x", "11.x"], "Laravel 9.x", true),
2123            "Laravel 10.x"
2124        );
2125    }
2126
2127    #[test]
2128    fn test_replace_first() {
2129        assert_eq!(
2130            Str::replace_first("the", "a", "the quick brown fox jumps over the lazy dog"),
2131            "a quick brown fox jumps over the lazy dog"
2132        );
2133    }
2134
2135    #[test]
2136    fn test_replace_last() {
2137        assert_eq!(
2138            Str::replace_last("the", "a", "the quick brown fox jumps over the lazy dog"),
2139            "the quick brown fox jumps over a lazy dog"
2140        );
2141    }
2142
2143    #[test]
2144    fn test_reverse() {
2145        assert_eq!(Str::reverse("Hello World"), "dlroW olleH");
2146    }
2147
2148    #[test]
2149    fn test_singular() {
2150        assert_eq!(Str::singular("cars"), "car");
2151        assert_eq!(Str::singular("children"), "child");
2152    }
2153
2154    #[test]
2155    fn test_slug() {
2156        assert_eq!(
2157            Str::slug("Laravel 5 Framework", "-", None, None),
2158            "laravel-5-framework"
2159        );
2160    }
2161
2162    #[test]
2163    fn test_snake() {
2164        assert_eq!(Str::snake("fooBar", "_"), "foo_bar");
2165        assert_eq!(Str::snake("FooBar", "_"), "foo_bar");
2166    }
2167
2168    #[test]
2169    fn test_start() {
2170        assert_eq!(Str::start("this/string", "/"), "/this/string");
2171        assert_eq!(Str::start("/this/string", "/"), "/this/string");
2172    }
2173
2174    #[test]
2175    fn test_starts_with() {
2176        assert!(Str::starts_with("Hello World", &["Hello"]));
2177        assert!(!Str::starts_with("Hello World", &["World"]));
2178    }
2179
2180    #[test]
2181    fn test_studly() {
2182        assert_eq!(Str::studly("foo_bar"), "FooBar");
2183        assert_eq!(Str::studly("foo-bar"), "FooBar");
2184    }
2185
2186    #[test]
2187    fn test_substr() {
2188        assert_eq!(Str::substr("The Laravel Framework", 4, Some(7)), "Laravel");
2189        assert_eq!(
2190            Str::substr("The Laravel Framework", -9, Some(9)),
2191            "Framework"
2192        );
2193    }
2194
2195    #[test]
2196    fn test_title() {
2197        assert_eq!(
2198            Str::title("a nice title uses the correct case"),
2199            "A Nice Title Uses The Correct Case"
2200        );
2201    }
2202
2203    #[test]
2204    fn test_ucfirst() {
2205        assert_eq!(Str::ucfirst("foo bar"), "Foo bar");
2206    }
2207
2208    #[test]
2209    fn test_upper() {
2210        assert_eq!(Str::upper("laravel"), "LARAVEL");
2211    }
2212
2213    #[test]
2214    fn test_uuid() {
2215        let uuid1 = Str::uuid();
2216        let uuid2 = Str::uuid();
2217        assert_ne!(uuid1, uuid2);
2218        assert!(Str::is_uuid(&uuid1.to_string(), None));
2219    }
2220
2221    #[test]
2222    fn test_word_count() {
2223        assert_eq!(Str::word_count("Hello, how are you?", None), 4);
2224    }
2225
2226    #[test]
2227    fn test_words() {
2228        assert_eq!(
2229            Str::words("Perfectly balanced, as all things should be.", 3, ">>>"),
2230            "Perfectly balanced, as>>>"
2231        );
2232    }
2233
2234    #[test]
2235    fn test_explode_basic() {
2236        let parts = Str::explode("a,b,,c", ",");
2237        assert_eq!(parts, vec!["a", "b", "", "c"]);
2238    }
2239
2240    #[test]
2241    fn test_explode_empty_delim() {
2242        let parts = Str::explode("abč", "");
2243        // splits by chars (UTF-8 codepoints), not grapheme clusters
2244        assert_eq!(parts, vec!["a", "b", "č"]);
2245    }
2246
2247    #[test]
2248    fn test_implode_basic() {
2249        let vec = vec!["a", "b", "c"];
2250        let s = Str::implode("-", vec);
2251        assert_eq!(s, "a-b-c");
2252    }
2253
2254    #[test]
2255    fn test_limit_words_trim() {
2256        let s = "This   is  a   test string";
2257        let out = Str::limit_words(s, 3, "...");
2258        assert_eq!(out, "This is a...");
2259    }
2260
2261    #[test]
2262    fn test_limit_words_no_trim() {
2263        let s = "Short text";
2264        let out = Str::limit_words(s, 5, "...");
2265        assert_eq!(out, s);
2266    }
2267
2268    #[test]
2269    fn test_limit_zero() {
2270        let s = "Anything";
2271        let out = Str::limit_words(s, 0, "...");
2272        assert_eq!(out, "...");
2273    }
2274
2275}