use std::borrow::Cow;
use std::collections::HashSet;
use unicode_categories::UnicodeCategories;
#[derive(Debug, Default)]
#[doc(hidden)]
pub struct Anchorizer(HashSet<String>);
impl Anchorizer {
pub fn new() -> Self {
Anchorizer(HashSet::new())
}
pub fn anchorize(&mut self, header: &str) -> String {
fn is_permitted_char(&c: &char) -> bool {
c == ' '
|| c == '-'
|| c.is_letter()
|| c.is_mark()
|| c.is_number()
|| c.is_punctuation_connector()
}
let mut id = header.to_lowercase();
id = id
.chars()
.filter(is_permitted_char)
.map(|c| if c == ' ' { '-' } else { c })
.collect();
let mut uniq = 0;
id = loop {
let anchor = if uniq == 0 {
Cow::from(&id)
} else {
Cow::from(format!("{}-{}", id, uniq))
};
if !self.0.contains(&*anchor) {
break anchor.into_owned();
}
uniq += 1;
};
self.0.insert(id.clone());
id
}
}