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
use deunicode::deunicode_char;

pub struct StrSlug {
    pub use_hash: bool,

    /// if its set to false the hash will be prepended
    pub append_hash: bool,

    /// use full hash if `hash_len` = 0
    pub hash_len: usize,

    /// separator to use to separate slug and hash
    pub hash_separator: char,

    pub separator: char,
    pub remove_duplicate_separators: bool,

    /// Trim leading and trailing separators after slugifying the given string.
    pub trim_separator: bool,
    pub trim_separator_start: bool,
    pub trim_separator_end: bool,
}

impl StrSlug {
    pub fn new() -> Self {
        Self {
            use_hash: false,
            append_hash: true,
            hash_len: 6,
            hash_separator: '_',

            separator: '-',
            remove_duplicate_separators: true,

            trim_separator: true,
            trim_separator_start: false,
            trim_separator_end: false,
        }
    }

    #[inline]
    fn _slug_ascii_char(&self, c: char) -> char {
        match c {
            'a'..='z' | '0'..='9' => c,
            'A'..='Z' => c.to_ascii_lowercase(),
            _ => self.separator,
        }
    }

    #[inline]
    fn _push(&self, slug: &mut String, c: char, is_separator: bool) -> bool {
        if c == self.separator {
            if !self.remove_duplicate_separators {
                slug.push(self.separator);
            } else if self.remove_duplicate_separators && !is_separator {
                slug.push(self.separator);
            }

            return true
        } else  {
            slug.push(c);
        }

        false
    }

    /// Generate a slug for the given value by applying user options.
    ///
    /// # Examples
    ///
    /// **Normal usage**
    ///
    /// ```rust
    /// use str_slug::StrSlug;
    ///
    /// let str_slug = StrSlug::new();
    /// let slug = str_slug::slug("Hello, World!");
    /// assert_eq!(slug, "hello-world");
    /// ```
    ///
    /// **Hashed slug**
    ///
    /// ```rust
    /// use str_slug::StrSlug;
    ///
    /// let mut str_slug = StrSlug::new();
    /// str_slug.use_hash = true;
    ///
    /// let slug = str_slug.slug("Hello, World!");
    /// assert_eq!(slug, "hello-world_288a86");
    /// ```
    pub fn slug<T: AsRef<str>>(&self, value: T) -> String {
        let value = value.as_ref();
        let mut slug = String::new();
        let mut is_separator = false;

        for c in value.chars() {
            if c.is_ascii() {
                let c = self._slug_ascii_char(c);
                is_separator = self._push(&mut slug, c, is_separator);
            } else {
                if let Some(output) = deunicode_char(c) {
                    for c in output.chars() {
                        let c = self._slug_ascii_char(c);
                        is_separator = self._push(&mut slug, c, is_separator);
                    }
                } else {
                    is_separator = self._push(&mut slug, self.separator, is_separator);
                }
            }
        }

        if self.trim_separator {
            slug = slug.trim_end_matches(|c| c == self.separator)
                .trim_start_matches(|c| c == self.separator)
                .to_string();
        } else {
            if self.trim_separator_start {
                slug = slug.trim_start_matches(|c| c == self.separator).to_string();
            }

            if self.trim_separator_end {
                slug = slug.trim_end_matches(|c| c == self.separator).to_string();
            }
        }

        #[cfg(feature = "hash")]
        {
            if self.use_hash && cfg!(feature = "hash") {
                let hash = blake3::hash(value.as_bytes()).to_hex();
                let hash_len = if self.hash_len == 0 || self.hash_len > hash.len() {
                    hash.len()
                } else {
                    self.hash_len
                };

                if self.append_hash {
                    slug.push_str(&format!("{}{}", self.hash_separator, &hash[..hash_len]));
                } else {
                    slug = format!("{}{}{}", &hash[..hash_len], self.hash_separator, slug);
                }
            }
        }

        slug
    }
}

/// Generate URL friendly slug of the given string.
///
/// # Examples
///
/// ```
/// use str_slug::slug;
///
/// let slug = slug("Hello, World ;-)");
/// assert_eq!("hello-world", slug);
/// ```
pub fn slug<T: AsRef<str>>(value: T) -> String {
    let str_slug = StrSlug::new();
    str_slug.slug(value)
}

/// Generate URL friendly slug of the given string, and append a hash to it.
///
/// # Features
/// - hash
///
/// # Examples
///
/// ```
/// use str_slug::slug_hash;
///
/// let slug = slug_hash("don’t let your life clubbed into dank submission. be on the watch, there are ways out.");
/// assert_eq!(slug, "don-t-let-your-life-clubbed-into-dank-submission-be-on-the-watch-there-are-ways-out_a2f4f4");
///
/// ```
pub fn slug_hash<T: AsRef<str>>(value: T) -> String {
    let mut str_slug = StrSlug::new();
    str_slug.use_hash = true;
    str_slug.slug(value)
}

/// Slugify the given string and append the hash of the given value (trimed)
///
/// # Examples
///
/// ```
/// use str_slug::slug_hash_len;
///
/// let slug = slug_hash_len("Hello, world ;-)", 6);
/// assert_eq!("hello-world_ea1ac5", slug);
/// ```
pub fn slug_hash_len<T: AsRef<str>>(value: T, hash_len: usize) -> String {
    let mut str_slug = StrSlug::new();
    str_slug.use_hash = true;
    str_slug.hash_len = hash_len;
    str_slug.slug(value)
}

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

    #[test]
    fn trim_whitespaces() {
        let slug = slug("   Hello, world!");
        assert_eq!("hello-world", slug);
    }

    #[test]
    fn trim_whitespace_start() {
        let mut slug = StrSlug::new();
        slug.remove_duplicate_separators = false;
        slug.trim_separator = false;
        slug.trim_separator_end = false;
        slug.trim_separator_start = true;
        let slug = slug.slug("   Hello, world!  ");
        assert_eq!("hello--world---", slug);
    }

    #[test]
    fn hello_hash() {
        let slug = slug_hash("oussama");
        assert_eq!("oussama_407ad6", slug);
    }

    #[test]
    fn hello_ascii() {
        let slug = super::slug("Hello, ascii");
        assert_eq!(slug, "hello-ascii");
    }

    #[test]
    fn hello_unicode() {
        let slug = super::slug("Æ, ☣");
        assert_eq!(slug, "ae-biohazard");
    }

    #[test]
    fn hello_ascii_unicode() {
        let slug = super::slug("Hello, Æ, ☣");
        assert_eq!(slug, "hello-ae-biohazard");
    }

    #[test]
    fn hello_empty_unicode() {
        let slug = super::slug("Hello, ❤ ;-)");
        assert_eq!(slug, "hello");
    }

    #[test]
    fn hello_empty_unicode_allow_duplicates_no_trimming() {
        let mut slug = StrSlug::new();
        slug.remove_duplicate_separators = false;
        slug.trim_separator = false;
        let slug = slug.slug("Hello, ❤ ;-)");
        assert_eq!("hello------", slug);
    }

    #[test]
    fn unicode_allow_duplicates_trim() {
        let mut slug = StrSlug::new();
        slug.remove_duplicate_separators = false;
        slug.trim_separator = true;
        let slug = slug.slug("Hello ‟Oussama‟ Æ, «☣» with ❤");
        assert_eq!("hello--oussama--ae----biohazard----with", slug);
    }
}