use crate::transliterate::{AnyAscii, Transliterator};
type SuffixFn = Box<dyn Fn(&str, u32) -> String + Send + Sync>;
pub struct SlugOptions {
separator: String,
max_length: usize,
suffix_start: u32,
suffix_on_first: bool,
suffix: Option<SuffixFn>,
reserved: Vec<String>,
transliterator: Box<dyn Transliterator>,
}
impl Default for SlugOptions {
fn default() -> Self {
Self {
separator: "-".to_string(),
max_length: 250,
suffix_start: 1,
suffix_on_first: false,
suffix: None,
reserved: Vec::new(),
transliterator: Box::new(AnyAscii),
}
}
}
impl SlugOptions {
#[must_use]
pub fn separator(mut self, separator: &str) -> Self {
self.separator = separator.to_string();
self
}
#[must_use]
pub const fn max_length(mut self, max_length: usize) -> Self {
self.max_length = max_length;
self
}
#[must_use]
pub const fn suffix_start(mut self, suffix_start: u32) -> Self {
self.suffix_start = suffix_start;
self
}
#[must_use]
pub const fn suffix_on_first(mut self, suffix_on_first: bool) -> Self {
self.suffix_on_first = suffix_on_first;
self
}
#[must_use]
pub fn suffix_with(
mut self,
suffix: impl Fn(&str, u32) -> String + Send + Sync + 'static,
) -> Self {
self.suffix = Some(Box::new(suffix));
self
}
#[must_use]
pub fn reserved<I, S>(mut self, words: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
self.reserved = words
.into_iter()
.map(|word| word.as_ref().to_lowercase())
.collect();
self
}
#[must_use]
pub fn transliterator(mut self, transliterator: impl Transliterator + 'static) -> Self {
self.transliterator = Box::new(transliterator);
self
}
pub(crate) fn separator_str(&self) -> &str {
&self.separator
}
pub(crate) const fn max_len(&self) -> usize {
self.max_length
}
pub(crate) const fn first_suffix(&self) -> u32 {
self.suffix_start
}
pub(crate) const fn always_suffix(&self) -> bool {
self.suffix_on_first
}
pub(crate) fn is_reserved(&self, slug: &str) -> bool {
self.reserved
.iter()
.any(|word| word.eq_ignore_ascii_case(slug))
}
pub(crate) fn to_ascii(&self, text: &str) -> String {
self.transliterator.transliterate(text)
}
pub(crate) fn with_suffix(&self, base: &str, attempt: u32) -> String {
let suffix = self
.suffix
.as_ref()
.map_or_else(|| attempt.to_string(), |make| make(base, attempt));
let room = self
.max_length
.saturating_sub(self.separator.len() + suffix.len());
let short = crate::text::cut(base.to_string(), room, &self.separator);
let base = if short.is_empty() {
base
} else {
short.as_str()
};
format!("{base}{}{suffix}", self.separator)
}
pub(crate) const fn has_default_suffix(&self) -> bool {
self.suffix.is_none()
}
}