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
//! **A utility macro for flexible slug genereation that handles unicode.**
//! 
//! The `slugify!` macro implements a flexible slug generator, allowing for stop words, custom separator
//! and maximum length options. The macro provides both a simple interface with sane default parameters
//! but also allows the parameters to be overriden when needed.
//! 
//! Features:
//!
//!* Unicode strings support (phonetic conversion).
//!* Support for custom slug separator.
//!* Stop words filtering.
//!* Slug maximum length support.
//!
//! 
//!# Usage
//! 
//! This crate is on crates.io and can be used by adding `slugify` to the dependencies in your project's
//! `Cargo.toml`
//! 
//! ```toml
//! [dependencies]
//! slugify = "0.1.0"
//! ```
//! 
//!  and this to your crate root:
//! 
//!```rust,ignore
//! #[macro_use] extern crate slugify;
//!use slugify::slugify;
//!```
//! 
//!# Examples
//!
//!## Basic slug generation
//! 
//!```rust
//! # #[macro_use] extern crate slugify;
//! # use slugify::slugify;
//! # fn main() {
//!assert_eq!(slugify!("hello world"), "hello-world");
//! # }
//!```
//! 
//!## Using a custom separator
//! 
//! ```rust
//! # #[macro_use] extern crate slugify;
//! # use slugify::slugify;
//! # fn main() {
//!assert_eq!(slugify!("hello world", separator = "."), "hello.world");
//!assert_eq!(slugify!("hello world", separator = " "), "hello world");
//! # }
//! ```
//! 
//!## Stop words filtering
//! 
//!```rust
//! # #[macro_use] extern crate slugify;
//! # use slugify::slugify;
//! # fn main() {
//!assert_eq!(slugify!("the quick brown fox jumps over the lazy dog", stop_words = "the,fox"), "quick-brown-jumps-over-lazy-dog");
//! # }
//!```
//! 
//!## Maximum length
//! 
//!```rust
//! # #[macro_use] extern crate slugify;
//! # use slugify::slugify;
//! # fn main() {
//!assert_eq!(slugify!("hello world", max_length = 5), "hello");
//!assert_eq!(slugify!("the hello world", stop_words = "the", max_length = 5), "hello");
//! # }
//!```
//! 
//!## Phonetic Conversion and accented text
//! 
//!```rust
//! # #[macro_use] extern crate slugify;
//! # use slugify::slugify;
//! # fn main() {
//!assert_eq!(slugify!("影師嗎"), "ying-shi-ma");
//!assert_eq!(slugify!("Æúű--cool?"), "aeuu-cool");
//!assert_eq!(slugify!("Nín hǎo. Wǒ shì zhōng guó rén"), "nin-hao-wo-shi-zhong-guo-ren");
//! # }
//!```
//! 
//!## Passing multiple optional parameters.
//!
//! **NOTE:** the order of optional parameters matters: **stop_words**, **separator**
//! and then **max_length**. All of them are optional, however when specifying more than one optional parameter, this
//! order must be adhered.
//! 
//!```rust
//! # #[macro_use] extern crate slugify;
//! # use slugify::slugify;
//! # fn main() {
//!assert_eq!(slugify!("the hello world", stop_words = "the", separator = "-"), "hello-world");
//!assert_eq!(slugify!("the hello world", separator = ".", max_length = 10), "the.hello");
//!assert_eq!(slugify!("the hello world", stop_words = "the", max_length = 5), "hello");
//!assert_eq!(slugify!("the hello world", stop_words = "the", separator = "-", max_length = 20), "hello-world");
//! # }
//!```
//!
extern crate unidecode;
use unidecode::unidecode;


#[macro_export]
macro_rules! slugify {
    ($text:expr) => (
        {
         slugify($text, "", "-", None)
        }
    );

    ($text:expr, stop_words=$stopwords:expr) => (
        {
         slugify($text, $stopwords, "-", None)
        }
    );

    ($text:expr, separator=$sep:expr) => (
        {
         slugify($text, "", $sep, None)
        }
    );

    ($text:expr, max_length=$len:expr) => (
        {
         slugify($text, "", "-", Some($len))
        }
    );

    ($text:expr, stop_words=$stopwords:expr, separator=$sep:expr) => (
        {
         slugify($text, $stopwords, $sep, None)
        }
    );

    ($text:expr, stop_words=$stopwords:expr, max_length=$len:expr) => (
        {
         slugify($text, $stopwords, "-", Some($len))
        }
    );

    ($text:expr, separator=$sep:expr, max_length=$len:expr) => (
        {
         slugify($text, "", $sep, Some($len))
        }
    );

    ($text:expr, stop_words=$stopwords:expr, separator=$sep:expr, max_length=$len:expr) => (
        {
         slugify($text, $stopwords, $sep, Some($len))
        }
    );


}

pub fn slugify(string: &str, stop_words: &str, sep: &str, max_length: Option<usize>) -> String {
    let char_vec: Vec<char> = sep.chars().collect();
    let mut string: String = unidecode(string.into())
        .to_lowercase()
        .trim()
        .trim_matches(char_vec[0])
        .replace(' ', &sep.to_string());

    // remove stop words
    for word in stop_words.split(",") {
        if !word.is_empty() {
            string = string.replace(word, &sep.to_string());
        }

    }

    let mut slug = Vec::with_capacity(string.len());

    let mut is_sep = true;

    for x in string.chars() {
        match x {
            'a'...'z' | '0'...'9' => {
                is_sep = false;
                slug.push(x as u8);
            }
            _ => {
                if !is_sep {
                    is_sep = true;
                    slug.push(char_vec[0] as u8);
                } else {
                }
            }
        }
    }

    if slug.last() == Some(&(char_vec[0] as u8)) {
        slug.pop();
    }

    let mut s = String::from_utf8(slug).unwrap();

    match max_length {
        Some(x) => {
            s.truncate(x);
            s = s.trim_right_matches(char_vec[0]).to_string();
        }
        None => {}
    }

    s

}



#[cfg(test)]
mod tests {
    use slugify;
    #[test]
    fn basic() {
        assert_eq!(slugify("hello world", "", "-", None), "hello-world");
        assert_eq!(slugify("hello world-", "", "-", None), "hello-world");
        assert_eq!(slugify("hello world ", "", "-", None), "hello-world");
    }

    #[test]
    fn test_email() {
        assert_eq!(slugify!("alice@bob.com"), "alice-bob-com");
    }

    #[test]
    fn test_starts_with_number() {
        assert_eq!(slugify!("10 amazing secrets"), "10-amazing-secrets");
    }

    #[test]
    fn test_contains_numbers() {
        assert_eq!(slugify!("the 101 dalmatians"), "the-101-dalmatians");
    }

    #[test]
    fn test_ends_with_number() {
        assert_eq!(slugify!("lucky number 7"), "lucky-number-7");
    }

    #[test]
    fn test_numbers_only() {
        assert_eq!(slugify!("101"), "101");
    }

    #[test]
    fn test_numbers_and_symbols() {
        assert_eq!(slugify!("1000 reasons you are #1"),
                   "1000-reasons-you-are-1");
    }

    #[test]
    fn test_stop_words() {
        assert_eq!(slugify("hello world", "world", "-", None), "hello");
        assert_eq!(slugify!("hello world", stop_words = "world"), "hello");
    }

    #[test]
    fn test_differently_cased_stopword_match() {
        assert_eq!(slugify("Foo A FOO B foo C", "foo", "-", None), "a-b-c");
    }

    #[test]
    fn test_multiple_stop_words() {
        assert_eq!(slugify("the quick brown fox jumps over the lazy dog",
                           "the",
                           "-",
                           None),
                   "quick-brown-fox-jumps-over-lazy-dog");
        assert_eq!(slugify("the quick brown fox jumps over the lazy dog",
                           "the,fox",
                           "-",
                           None),
                   "quick-brown-jumps-over-lazy-dog");
        assert_eq!(slugify!("the quick brown fox jumps over the lazy dog",
                            stop_words = "the,fox"),
                   "quick-brown-jumps-over-lazy-dog");
    }

    #[test]
    fn test_stopwords_with_different_separator() {
        assert_eq!(slugify("the quick brown fox jumps over the lazy dog",
                           "the",
                           " ",
                           None),
                   "quick brown fox jumps over lazy dog");
        assert_eq!(slugify!("the quick brown fox jumps over the lazy dog",
                            stop_words = "the",
                            separator = " "),
                   "quick brown fox jumps over lazy dog");
    }

    #[test]
    fn test_separator() {
        assert_eq!(slugify("hello world", "", ".", None), "hello.world");
        assert_eq!(slugify("hello world", "", "_", None), "hello_world");
        assert_eq!(slugify!("hello world", separator = "_"), "hello_world");
    }

    #[test]
    fn test_phonetic_conversion() {
        assert_eq!(slugify("影師嗎", "", "-", None), "ying-shi-ma");
    }

    #[test]
    fn test_accented_text() {
        assert_eq!(slugify("Æúű--cool?", "", "-", None), "aeuu-cool");
        assert_eq!(slugify("Nín hǎo. Wǒ shì zhōng guó rén", "", "-", None),
                   "nin-hao-wo-shi-zhong-guo-ren");
    }

    #[test]
    fn test_accented_text_non_word_chars() {
        assert_eq!(slugify!("jaja---lol-méméméoo--a"), "jaja-lol-mememeoo-a");
    }

    #[test]
    fn test_cyrillic_text() {
        assert_eq!(slugify!("Компьютер"), "komp-iuter");
    }

    #[test]
    fn test_macro() {
        assert_eq!(slugify!("Компьютер"), "komp-iuter");
        assert_eq!(slugify!("hello world", separator = "-"), "hello-world");
        assert_eq!(slugify!("hello world", separator = " "), "hello world");
        assert_eq!(slugify!("hello world", max_length = 5), "hello");
        assert_eq!(slugify!("hello world", max_length = 6), "hello");
        assert_eq!(slugify!("hello world", separator = " ", max_length = 8),
                   "hello wo");
        assert_eq!(slugify!("hello world", separator = "x", max_length = 8),
                   "helloxwo");
        assert_eq!(slugify!("the hello world", stop_words = "the", separator = "-"),
                   "hello-world");
        assert_eq!(slugify!("the hello world", stop_words = "the", max_length = 5),
                   "hello");
        assert_eq!(slugify!("the hello world",
                            stop_words = "the",
                            separator = "-",
                            max_length = 10),
                   "hello-worl");
        assert_eq!(slugify!("the hello world",
                            stop_words = "the",
                            separator = "-",
                            max_length = 20),
                   "hello-world");
    }
}