foxtive 0.25.6

Foxtive Framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
use crate::helpers::regex::{CaseSensitivity, RegexType};

/// A utility struct for cleaning text using regex patterns for username validation.
pub struct TextCleaner;

impl TextCleaner {
    /// Cleans a string according to the specified cleaning rules.
    ///
    /// # Parameters
    /// - `text`: A string slice (`&str`) representing the text to clean.
    /// - `cleaning_type`: The `RegexType` enum variant that defines how to clean the text.
    ///
    /// # Returns
    /// A `String` containing the cleaned text that conforms to the specified pattern.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use foxtive::helpers::regex::{CaseSensitivity, TextCleaner, RegexType};
    ///
    /// let dirty_text = "User@@Name123!!";
    /// let cleaned = TextCleaner::clean(dirty_text, RegexType::AlphaNumeric(CaseSensitivity::CaseInsensitive));
    /// assert_eq!(cleaned, "username123");
    ///
    /// let text_with_dots = "user..name..123";
    /// let cleaned = TextCleaner::clean(text_with_dots, RegexType::AlphaNumericDot(CaseSensitivity::CaseSensitive));
    /// assert_eq!(cleaned, "user.name.123");
    /// ```
    pub fn clean(text: &str, cleaning_type: RegexType) -> String {
        match cleaning_type {
            RegexType::Alphabetic(case_sensitivity) => {
                Self::clean_alphabetic(text, case_sensitivity)
            }
            RegexType::AlphaNumeric(case_sensitivity) => {
                Self::clean_alphanumeric(text, case_sensitivity)
            }
            RegexType::AlphaNumericLoose(case_sensitivity) => {
                Self::clean_alphanumeric_loose(text, case_sensitivity)
            }
            RegexType::AlphaNumericSpace(case_sensitivity) => {
                Self::clean_alphanumeric_space(text, case_sensitivity)
            }
            RegexType::AlphaNumericDash(case_sensitivity) => {
                Self::clean_alphanumeric_dash(text, case_sensitivity)
            }
            RegexType::AlphaNumericDot(case_sensitivity) => {
                Self::clean_alphanumeric_dot(text, case_sensitivity)
            }
            RegexType::AlphaNumericDashDot(case_sensitivity) => {
                Self::clean_alphanumeric_dash_dot(text, case_sensitivity)
            }
            RegexType::AlphaNumericUnderscore(case_sensitivity) => {
                Self::clean_alphanumeric_underscore(text, case_sensitivity)
            }
            RegexType::AlphaNumericDotUnderscore(case_sensitivity) => {
                Self::clean_alphanumeric_dot_underscore(text, case_sensitivity)
            }
            RegexType::Digits => Self::clean_digits(text),
            RegexType::Email => Self::clean_email(text),
            RegexType::Custom(allowed_chars, case_sensitivity, max_length) => Self::clean_custom(
                text,
                allowed_chars,
                case_sensitivity.unwrap_or(CaseSensitivity::CaseSensitive),
                max_length,
            ),
        }
    }

    /// Cleans text for username format (AlphaNumericDot with case sensitivity).
    ///
    /// # Parameters
    /// - `text`: A string slice (`&str`) representing the text to clean.
    ///
    /// # Returns
    /// A `String` containing the cleaned username.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use foxtive::helpers::regex::TextCleaner;
    ///
    /// let dirty_username = "User..First@@123";
    /// let cleaned = TextCleaner::clean_username(dirty_username);
    /// assert_eq!(cleaned, "user.first123");
    /// ```
    pub fn clean_username(text: &str) -> String {
        Self::clean(
            text,
            RegexType::AlphaNumericDot(CaseSensitivity::CaseSensitive),
        )
    }

    /// Cleans text to contain only alphabetic characters.
    fn clean_alphabetic(text: &str, case_sensitivity: CaseSensitivity) -> String {
        let mut result: String = text.chars().filter(|c| c.is_alphabetic()).collect();

        result = Self::apply_case_transformation(result, case_sensitivity);
        Self::truncate_to_length(result, 38)
    }

    /// Cleans text to contain only alphanumeric characters, ensuring it starts with a letter.
    fn clean_alphanumeric(text: &str, case_sensitivity: CaseSensitivity) -> String {
        let mut result: String = text.chars().filter(|c| c.is_alphanumeric()).collect();

        result = Self::apply_case_transformation(result, case_sensitivity);
        result = Self::ensure_starts_with_letter(result);
        Self::truncate_to_length(result, 38)
    }

    /// Cleans text to contain only alphanumeric characters, without a starting character restriction.
    fn clean_alphanumeric_loose(text: &str, case_sensitivity: CaseSensitivity) -> String {
        let mut result: String = text.chars().filter(|c| c.is_alphanumeric()).collect();

        result = Self::apply_case_transformation(result, case_sensitivity);
        Self::truncate_to_length(result, 38)
    }

    /// Cleans text for alphanumeric + space pattern, normalizing whitespace.
    fn clean_alphanumeric_space(text: &str, case_sensitivity: CaseSensitivity) -> String {
        let mut result: String = text
            .chars()
            .filter(|c| c.is_alphanumeric() || c.is_whitespace())
            .collect();

        result = Self::apply_case_transformation(result, case_sensitivity);
        result = Self::ensure_starts_with_letter(result);
        result = Self::normalize_whitespace(result);
        result = Self::remove_trailing_whitespace(result);
        Self::truncate_to_length(result, 38)
    }

    /// Cleans text for alphanumeric + dash pattern.
    fn clean_alphanumeric_dash(text: &str, case_sensitivity: CaseSensitivity) -> String {
        let mut result: String = text
            .chars()
            .filter(|c| c.is_alphanumeric() || *c == '-')
            .collect();

        result = Self::apply_case_transformation(result, case_sensitivity);
        result = Self::ensure_starts_with_letter(result);
        result = Self::remove_consecutive_chars(result, '-');
        result = Self::remove_trailing_char(result, '-');
        Self::truncate_to_length(result, 38)
    }

    /// Cleans text for alphanumeric + dot pattern.
    fn clean_alphanumeric_dot(text: &str, case_sensitivity: CaseSensitivity) -> String {
        let mut result: String = text
            .chars()
            .filter(|c| c.is_alphanumeric() || *c == '.')
            .collect();

        result = Self::apply_case_transformation(result, case_sensitivity);
        result = Self::ensure_starts_with_letter(result);
        result = Self::remove_consecutive_chars(result, '.');
        result = Self::remove_trailing_char(result, '.');
        Self::truncate_to_length(result, 38)
    }

    /// Cleans text for alphanumeric + dash + dot pattern.
    fn clean_alphanumeric_dash_dot(text: &str, case_sensitivity: CaseSensitivity) -> String {
        let mut result: String = text
            .chars()
            .filter(|c| c.is_alphanumeric() || *c == '-' || *c == '.' || *c == '_')
            .collect();

        result = Self::apply_case_transformation(result, case_sensitivity);
        result = Self::ensure_starts_with_letter(result);
        result = Self::remove_consecutive_chars(result, '.');
        result = Self::remove_consecutive_chars(result, '-');
        result = Self::remove_trailing_char(result, '.');
        result = Self::remove_trailing_char(result, '-');
        Self::truncate_to_length(result, 38)
    }

    /// Cleans text for alphanumeric + underscore pattern.
    fn clean_alphanumeric_underscore(text: &str, case_sensitivity: CaseSensitivity) -> String {
        let mut result: String = text
            .chars()
            .filter(|c| c.is_alphanumeric() || *c == '_')
            .collect();

        result = Self::apply_case_transformation(result, case_sensitivity);
        result = Self::ensure_starts_with_letter(result);
        result = Self::remove_consecutive_chars(result, '_');
        result = Self::remove_trailing_char(result, '_');
        Self::truncate_to_length(result, 38)
    }

    /// Cleans text for alphanumeric + dot + underscore pattern.
    fn clean_alphanumeric_dot_underscore(text: &str, case_sensitivity: CaseSensitivity) -> String {
        let mut result: String = text
            .chars()
            .filter(|c| c.is_alphanumeric() || *c == '.' || *c == '_')
            .collect();

        result = Self::apply_case_transformation(result, case_sensitivity);
        result = Self::ensure_starts_with_letter(result);
        result = Self::remove_consecutive_chars(result, '.');
        result = Self::remove_consecutive_chars(result, '_');
        result = Self::remove_trailing_char(result, '.');
        result = Self::remove_trailing_char(result, '_');
        Self::truncate_to_length(result, 38)
    }

    /// Cleans text to contain only ascii digits.
    fn clean_digits(text: &str) -> String {
        text.chars().filter(|c| c.is_ascii_digit()).collect()
    }

    /// Cleans an email address by removing invalid characters.
    fn clean_email(text: &str) -> String {
        // A very basic email cleaner. A proper implementation would be more complex.
        text.chars()
            .filter(|c| c.is_alphanumeric() || *c == '.' || *c == '@' || *c == '-' || *c == '_')
            .collect::<String>()
            .to_lowercase()
    }

    /// Cleans text using custom allowed characters.
    fn clean_custom(
        text: &str,
        allowed_chars: &str,
        case_sensitivity: CaseSensitivity,
        max_length: usize,
    ) -> String {
        let allowed_set: std::collections::HashSet<char> = allowed_chars.chars().collect();

        let mut result: String = text
            .chars()
            .filter(|c| allowed_set.contains(c) || c.is_alphanumeric())
            .collect();

        result = Self::apply_case_transformation(result, case_sensitivity);
        Self::truncate_to_length(result, max_length)
    }

    /// Applies case transformation based on sensitivity setting.
    fn apply_case_transformation(text: String, case_sensitivity: CaseSensitivity) -> String {
        match case_sensitivity {
            CaseSensitivity::CaseSensitive => text.to_lowercase(),
            CaseSensitivity::CaseInsensitive => text.to_lowercase(),
        }
    }

    /// Ensures the string starts with a letter, removing leading non-letters.
    fn ensure_starts_with_letter(text: String) -> String {
        text.chars().skip_while(|c| !c.is_alphabetic()).collect()
    }

    /// Removes consecutive occurrences of a specific character.
    fn remove_consecutive_chars(text: String, target_char: char) -> String {
        let mut result = String::new();
        let mut prev_char = None;

        for ch in text.chars() {
            if ch == target_char && prev_char == Some(target_char) {
                continue; // Skip consecutive target characters
            }
            result.push(ch);
            prev_char = Some(ch);
        }

        result
    }

    /// Removes trailing occurrences of a specific character.
    fn remove_trailing_char(text: String, target_char: char) -> String {
        text.trim_end_matches(target_char).to_string()
    }

    /// Normalizes whitespace by replacing multiple consecutive whitespace characters with single spaces.
    fn normalize_whitespace(text: String) -> String {
        let mut result = String::new();
        let mut prev_was_space = false;

        for ch in text.chars() {
            if ch.is_whitespace() {
                if !prev_was_space {
                    result.push(' '); // Convert all whitespace to regular space
                    prev_was_space = true;
                }
            } else {
                result.push(ch);
                prev_was_space = false;
            }
        }

        result
    }

    /// Removes trailing whitespace.
    fn remove_trailing_whitespace(text: String) -> String {
        text.trim_end().to_string()
    }

    /// Truncates string to specified maximum length.
    fn truncate_to_length(text: String, max_length: usize) -> String {
        text.chars().take(max_length).collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_clean_alphabetic() {
        let dirty_text = "User123Name!!!";
        let cleaned = TextCleaner::clean(
            dirty_text,
            RegexType::Alphabetic(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned, "username");

        let mixed_case = "UserNAME";
        let cleaned = TextCleaner::clean(
            mixed_case,
            RegexType::Alphabetic(CaseSensitivity::CaseInsensitive),
        );
        assert_eq!(cleaned, "username");
    }

    #[test]
    fn test_clean_alphanumeric() {
        let dirty_text = "123User@@Name456";
        let cleaned = TextCleaner::clean(
            dirty_text,
            RegexType::AlphaNumeric(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned, "username456");

        let starts_with_number = "123username";
        let cleaned = TextCleaner::clean(
            starts_with_number,
            RegexType::AlphaNumeric(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned, "username");
    }

    #[test]
    fn test_clean_alphanumeric_loose() {
        let dirty_text = "123User@@Name456";
        let cleaned = TextCleaner::clean(
            dirty_text,
            RegexType::AlphaNumericLoose(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned, "123username456");
    }

    #[test]
    fn test_clean_email() {
        let dirty_email = " User..Email@Example.com!! ";
        let cleaned = TextCleaner::clean(dirty_email, RegexType::Email);
        assert_eq!(cleaned, "user..email@example.com");
    }

    #[test]
    fn test_clean_alphanumeric_space() {
        let dirty_text = "User   Name  123!!!";
        let cleaned = TextCleaner::clean(
            dirty_text,
            RegexType::AlphaNumericSpace(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned, "user name 123");

        let mixed_whitespace = "User\t\nName\r123";
        let cleaned = TextCleaner::clean(
            mixed_whitespace,
            RegexType::AlphaNumericSpace(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned, "user name 123");

        let trailing_spaces = "username   ";
        let cleaned = TextCleaner::clean(
            trailing_spaces,
            RegexType::AlphaNumericSpace(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned, "username");

        let leading_spaces = "   123username";
        let cleaned = TextCleaner::clean(
            leading_spaces,
            RegexType::AlphaNumericSpace(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned, "username");
    }

    #[test]
    fn test_clean_alphanumeric_space_case_insensitive() {
        let mixed_case = "User  NAME  123";
        let cleaned = TextCleaner::clean(
            mixed_case,
            RegexType::AlphaNumericSpace(CaseSensitivity::CaseInsensitive),
        );
        assert_eq!(cleaned, "user name 123");
    }

    #[test]
    fn test_clean_alphanumeric_dash() {
        let dirty_text = "user--name@@123";
        let cleaned = TextCleaner::clean(
            dirty_text,
            RegexType::AlphaNumericDash(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned, "user-name123");

        let trailing_dash = "username-";
        let cleaned = TextCleaner::clean(
            trailing_dash,
            RegexType::AlphaNumericDash(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned, "username");
    }

    #[test]
    fn test_clean_alphanumeric_dot() {
        let dirty_text = "user..name@@123";
        let cleaned = TextCleaner::clean(
            dirty_text,
            RegexType::AlphaNumericDot(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned, "user.name123");

        let trailing_dot = "username.";
        let cleaned = TextCleaner::clean(
            trailing_dot,
            RegexType::AlphaNumericDot(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned, "username");
    }

    #[test]
    fn test_clean_alphanumeric_underscore() {
        let dirty_text = "user__name@@123";
        let cleaned = TextCleaner::clean(
            dirty_text,
            RegexType::AlphaNumericUnderscore(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned, "user_name123");

        let trailing_underscore = "username_";
        let cleaned = TextCleaner::clean(
            trailing_underscore,
            RegexType::AlphaNumericUnderscore(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned, "username");
    }

    #[test]
    fn test_clean_username() {
        let dirty_username = "User..First@@123";
        let cleaned = TextCleaner::clean_username(dirty_username);
        assert_eq!(cleaned, "user.first123");

        let complex_username = "!!!User123..Name456...";
        let cleaned = TextCleaner::clean_username(complex_username);
        assert_eq!(cleaned, "user123.name456");
    }

    #[test]
    fn test_clean_digits() {
        let dirty_text = "User123Name!!!";
        let cleaned = TextCleaner::clean(dirty_text, RegexType::Digits);
        assert_eq!(cleaned, "123");
    }

    #[test]
    fn test_clean_custom() {
        let dirty_text = "user@domain.com";
        let cleaned = TextCleaner::clean(
            dirty_text,
            RegexType::Custom("@.", Some(CaseSensitivity::CaseSensitive), 20),
        );
        assert_eq!(cleaned, "user@domain.com");

        let long_text = "a".repeat(50);
        let cleaned = TextCleaner::clean(
            &long_text,
            RegexType::Custom("", Some(CaseSensitivity::CaseSensitive), 10),
        );
        assert_eq!(cleaned.len(), 10);
    }

    #[test]
    fn test_length_truncation() {
        let long_text = "a".repeat(50);
        let cleaned = TextCleaner::clean(
            &long_text,
            RegexType::Alphabetic(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned.len(), 38);
    }

    #[test]
    fn test_ensure_starts_with_letter() {
        let starts_with_number = "123abc";
        let cleaned = TextCleaner::clean(
            starts_with_number,
            RegexType::AlphaNumeric(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned, "abc");

        let starts_with_symbol = "___abc123";
        let cleaned = TextCleaner::clean(
            starts_with_symbol,
            RegexType::AlphaNumericUnderscore(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned, "abc123");
    }

    #[test]
    fn test_consecutive_character_removal() {
        let multiple_dots = "user...name";
        let cleaned = TextCleaner::clean(
            multiple_dots,
            RegexType::AlphaNumericDot(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned, "user.name");

        let multiple_underscores = "user___name";
        let cleaned = TextCleaner::clean(
            multiple_underscores,
            RegexType::AlphaNumericUnderscore(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned, "user_name");
    }

    #[test]
    fn test_normalize_whitespace() {
        let multiple_spaces = "user    name";
        let cleaned = TextCleaner::clean(
            multiple_spaces,
            RegexType::AlphaNumericSpace(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned, "user name");

        let mixed_whitespace_types = "user\t\t\nname";
        let cleaned = TextCleaner::clean(
            mixed_whitespace_types,
            RegexType::AlphaNumericSpace(CaseSensitivity::CaseSensitive),
        );
        assert_eq!(cleaned, "user name");
    }
}