use std::collections::HashMap;
use std::sync::{Arc, OnceLock};
use regex::Regex;
use crate::rules::RULESETS;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SlugifyOptions {
pub regexp: String,
pub separator: String,
pub lowercase: bool,
pub lowercase_after_regexp: bool,
pub trim: bool,
pub strip_tags: bool,
pub rulesets: Vec<String>,
pub ruleset: Option<String>,
}
impl Default for SlugifyOptions {
fn default() -> Self {
Self {
regexp: "/[^A-Za-z0-9]+/".to_owned(),
separator: "-".to_owned(),
lowercase: true,
lowercase_after_regexp: false,
trim: true,
strip_tags: false,
rulesets: [
"default",
"yiddish",
"armenian",
"azerbaijani",
"burmese",
"hindi",
"georgian",
"norwegian",
"vietnamese",
"ukrainian",
"latvian",
"finnish",
"greek",
"czech",
"arabic",
"slovak",
"turkish",
"polish",
"german",
"russian",
"romanian",
]
.map(str::to_owned)
.to_vec(),
ruleset: None,
}
}
}
#[derive(Debug, Clone)]
pub struct Slugify {
options: SlugifyOptions,
rules: HashMap<String, String>,
}
impl Default for Slugify {
fn default() -> Self {
Self::new(SlugifyOptions::default())
}
}
impl Slugify {
#[must_use]
pub fn new(options: SlugifyOptions) -> Self {
let mut engine = Self {
rules: HashMap::new(),
options,
};
for ruleset in engine.options.rulesets.clone() {
engine = engine.activate_rule_set(&ruleset);
}
engine
}
#[must_use]
pub fn options(&self) -> &SlugifyOptions {
&self.options
}
#[must_use]
pub fn add_rule(mut self, character: impl Into<String>, replacement: impl Into<String>) -> Self {
self.rules.insert(character.into(), replacement.into());
self
}
#[must_use]
pub fn add_rules<K: Into<String>, V: Into<String>>(mut self, rules: impl IntoIterator<Item = (K, V)>) -> Self {
for (character, replacement) in rules {
self = self.add_rule(character, replacement);
}
self
}
#[must_use]
pub fn activate_rule_set(self, ruleset: &str) -> Self {
let rules = ruleset_rules(ruleset);
self.add_rules(rules.iter().map(|(key, value)| (key.clone(), value.clone())))
}
#[must_use]
pub fn slugify(&self, text: &str) -> String {
self.slugify_with(text, &self.options)
}
#[must_use]
pub fn slugify_separator(&self, text: &str, separator: &str) -> String {
let options = SlugifyOptions {
separator: separator.to_owned(),
..self.options.clone()
};
self.slugify_with(text, &options)
}
fn slugify_with(&self, text: &str, options: &SlugifyOptions) -> String {
let mut extra;
let rules = match &options.ruleset {
Some(ruleset) => {
extra = self.rules.clone();
extra.extend(
ruleset_rules(ruleset)
.iter()
.map(|(key, value)| (key.clone(), value.clone())),
);
&extra
}
None => &self.rules,
};
let mut string = if options.strip_tags {
strip_tags(text)
} else {
text.to_owned()
};
string = strtr(&string, rules);
if options.lowercase && !options.lowercase_after_regexp {
string = string.to_lowercase();
}
string = php_regex(&options.regexp)
.replace_all(&string, regex::NoExpand(&options.separator))
.into_owned();
if options.lowercase && options.lowercase_after_regexp {
string = string.to_lowercase();
}
if options.trim && !options.separator.is_empty() {
while let Some(rest) = string.strip_prefix(options.separator.as_str()) {
string = rest.to_owned();
}
while let Some(rest) = string.strip_suffix(options.separator.as_str()) {
string = rest.to_owned();
}
}
string
}
}
fn ruleset_rules(name: &str) -> Arc<HashMap<String, String>> {
static PARSED: OnceLock<HashMap<&'static str, Arc<HashMap<String, String>>>> = OnceLock::new();
PARSED
.get_or_init(|| {
RULESETS
.iter()
.map(|(name, json)| {
(
*name,
Arc::new(serde_json::from_str(json).expect("a cocur/slugify ruleset")),
)
})
.collect()
})
.get(name)
.cloned()
.unwrap_or_default()
}
fn strtr(text: &str, rules: &HashMap<String, String>) -> String {
let longest = rules.keys().map(|key| key.chars().count()).max().unwrap_or(0);
if longest == 0 {
return text.to_owned();
}
let chars: Vec<(usize, char)> = text.char_indices().collect();
let mut out = String::with_capacity(text.len());
let mut index = 0;
'outer: while index < chars.len() {
let start = chars[index].0;
for length in (1..=longest.min(chars.len() - index)).rev() {
let end = chars.get(index + length).map_or(text.len(), |(offset, _)| *offset);
if let Some(replacement) = rules.get(&text[start..end]) {
out.push_str(replacement);
index += length;
continue 'outer;
}
}
out.push(chars[index].1);
index += 1;
}
out
}
fn php_regex(pattern: &str) -> Regex {
let mut chars = pattern.chars();
let compiled = chars.next().and_then(|delimiter| {
let closing = match delimiter {
'(' => ')',
'{' => '}',
'[' => ']',
'<' => '>',
other => other,
};
let body = &pattern[delimiter.len_utf8()..];
let end = body.rfind(closing)?;
let flags: String = body[end + closing.len_utf8()..]
.chars()
.filter(|flag| matches!(flag, 'i' | 'm' | 's' | 'x'))
.collect();
let expression = if flags.is_empty() {
body[..end].to_owned()
} else {
format!("(?{flags}){}", &body[..end])
};
Regex::new(&expression).ok()
});
compiled.unwrap_or_else(|| Regex::new("[^A-Za-z0-9]+").expect("the default pattern"))
}
fn strip_tags(text: &str) -> String {
static TAGS: OnceLock<Regex> = OnceLock::new();
TAGS.get_or_init(|| Regex::new(r"<[^>]*>").expect("the tag pattern"))
.replace_all(text, "")
.into_owned()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slugifies_like_cocur() {
let engine = Slugify::default();
assert_eq!(engine.slugify("Hello World"), "hello-world");
assert_eq!(engine.slugify("Müller straße"), "mueller-strasse");
assert_eq!(engine.slugify("Привет мир"), "privet-mir");
assert_eq!(engine.slugify(" --Café au lait!-- "), "cafe-au-lait");
assert_eq!(engine.slugify_separator("Hello World", "_"), "hello_world");
assert_eq!(engine.slugify_separator("Hello World", ""), "helloworld");
}
#[test]
fn custom_rules_and_options() {
let engine = Slugify::default().add_rule("&", "and");
assert_eq!(engine.slugify("Tom & Jerry"), "tom-and-jerry");
let engine = Slugify::new(SlugifyOptions {
lowercase: false,
..SlugifyOptions::default()
});
assert_eq!(engine.slugify("Hello World"), "Hello-World");
let engine = Slugify::new(SlugifyOptions {
regexp: "/[^a-z]+/i".to_owned(),
..SlugifyOptions::default()
});
assert_eq!(engine.slugify("Abc 123 Def"), "abc-def");
}
}