Debian Codegraph @

src/html/anchorizer.rs

raw
1 use finl_unicode::categories::CharacterCategories;
2 use std::borrow::Cow;
3 use std::collections::HashSet;
4
5 /// Converts header strings to canonical, unique, but still human-readable,
6 /// anchors.
7 ///
8 /// To guarantee uniqueness, an anchorizer keeps track of the anchors it has
9 /// returned; use one per output file.
10 ///
11 /// ## Example
12 ///
13 /// ```rust
14 /// # use comrak::Anchorizer;
15 /// let mut anchorizer = Anchorizer::new();
16 /// // First "stuff" is unsuffixed.
17 /// assert_eq!("stuff", anchorizer.anchorize("Stuff"));
18 /// // Second "stuff" has "-1" appended to make it unique.
19 /// assert_eq!("stuff-1", anchorizer.anchorize("Stuff"));
20 /// ```
21 #[derive(Debug, Default)]
22 #[doc(hidden)]
23 pub struct Anchorizer(HashSet<String>);
24
25 impl Anchorizer {
26 /// Construct a new anchorizer.
27 pub fn new() -> Self {
28 Anchorizer(HashSet::new())
29 }
30
31 /// Returns a String that has been converted into an anchor using the
32 /// GFM algorithm, which involves changing spaces to dashes, removing
33 /// problem characters and, if needed, adding a suffix to make the
34 /// resultant anchor unique.
35 ///
36 /// ```rust
37 /// # use comrak::Anchorizer;
38 /// let mut anchorizer = Anchorizer::new();
39 /// let source = "Ticks aren't in";
40 /// assert_eq!("ticks-arent-in", anchorizer.anchorize(source));
41 /// ```
42 pub fn anchorize(&mut self, header: &str) -> String {
43 fn is_permitted_char(&c: &char) -> bool {
44 c == ' '
45 || c == '-'
46 || c.is_letter()
47 || c.is_mark()
48 || c.is_number()
49 || c.is_punctuation_connector()
50 }
51
52 let mut id = header.to_lowercase();
53 id = id
54 .chars()
55 .filter(is_permitted_char)
56 .map(|c| if c == ' ' { '-' } else { c })
57 .collect();
58
59 let mut uniq = 0;
60 id = loop {
61 let anchor = if uniq == 0 {
62 Cow::from(&id)
63 } else {
64 Cow::from(format!("{}-{}", id, uniq))
65 };
66
67 if !self.0.contains(&*anchor) {
68 break anchor.into_owned();
69 }
70
71 uniq += 1;
72 };
73 self.0.insert(id.clone());
74 id
75 }
76 }