sea-orm-sluggable 0.1.0

Unique, transliterated slugs for SeaORM entities
Documentation
use crate::config::SlugOptions;

/// Builds a slug from `text`, without checking the database.
///
/// Transliterates to ASCII, lowercases, keeps letters and digits, joins the
/// rest with the separator and cuts to `max_length`. Apostrophes are dropped,
/// so "don't" becomes "dont", as in Laravel's `Str::slug`.
///
/// ```
/// use sea_orm_sluggable::{slugify, SlugOptions};
///
/// assert_eq!(slugify("Hello, World!", &SlugOptions::default()), "hello-world");
/// ```
#[must_use]
pub fn slugify(text: &str, options: &SlugOptions) -> String {
    let ascii = options.to_ascii(text);
    let separator = options.separator_str();

    let mut slug = String::with_capacity(ascii.len());
    let mut needs_separator = false;
    for ch in ascii.chars() {
        if ch.is_ascii_alphanumeric() {
            if needs_separator && !slug.is_empty() {
                slug.push_str(separator);
            }
            needs_separator = false;
            slug.push(ch.to_ascii_lowercase());
        } else if ch != '\'' {
            needs_separator = true;
        }
    }

    cut(slug, options.max_len(), separator)
}

/// Shortens `slug` to at most `max_length` bytes without leaving a dangling separator.
fn cut(mut slug: String, max_length: usize, separator: &str) -> String {
    if slug.len() <= max_length {
        return slug;
    }

    let mut end = max_length;
    while !slug.is_char_boundary(end) {
        end -= 1;
    }
    slug.truncate(end);

    while !separator.is_empty() && slug.ends_with(separator) {
        slug.truncate(slug.len() - separator.len());
    }
    slug
}

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

    fn slug(text: &str) -> String {
        slugify(text, &SlugOptions::default())
    }

    #[test]
    fn lowercases_and_joins_words() {
        assert_eq!(slug("Rust for PHP Developers"), "rust-for-php-developers");
    }

    #[test]
    fn collapses_punctuation_and_spaces() {
        assert_eq!(slug("  Hello,   World!!  "), "hello-world");
    }

    #[test]
    fn drops_apostrophes() {
        assert_eq!(slug("Don't panic"), "dont-panic");
    }

    #[test]
    fn transliterates_any_script() {
        assert_eq!(slug("Straße & Café"), "strasse-cafe");
    }

    #[test]
    fn uses_custom_separator() {
        let options = SlugOptions::default().separator("_");
        assert_eq!(slugify("Hello World", &options), "hello_world");
    }

    #[test]
    fn cuts_without_trailing_separator() {
        let options = SlugOptions::default().max_length(6);
        assert_eq!(slugify("hello world", &options), "hello");
    }

    #[test]
    fn returns_empty_when_nothing_is_left() {
        assert_eq!(slug("!!! ???"), "");
    }
}