1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
use std::fmt;
use std::iter::Peekable;

use memchr::memchr;
use memchr::memchr2;

use crate::email::EmailScanner;
use crate::scanner::Scanner;
use crate::url::UrlScanner;

/// A link found in the input text.
#[derive(Debug)]
pub struct Link<'t> {
    text: &'t str,
    start: usize,
    end: usize,
    kind: LinkKind,
}

impl<'t> Link<'t> {
    /// The start index of the link within the input text.
    #[inline]
    pub fn start(&self) -> usize {
        self.start
    }

    /// The end index of the link.
    #[inline]
    pub fn end(&self) -> usize {
        self.end
    }

    /// Get the link text as a `str`.
    #[inline]
    pub fn as_str(&self) -> &'t str {
        &self.text[self.start..self.end]
    }

    /// The type of the link.
    #[inline]
    pub fn kind(&self) -> &LinkKind {
        &self.kind
    }
}

/// The type of link that was found.
#[derive(Debug, Eq, PartialEq)]
pub enum LinkKind {
    /// URL links like "http://example.org".
    Url,
    /// E-mail links like "foo@example.org"
    Email,
    /// Users should not exhaustively match this enum, because more link types
    /// may be added in the future.
    #[doc(hidden)]
    __Nonexhaustive,
}

/// Span within the input text.
///
/// A span represents a substring of the input text,
/// which can either be a link, or plain text.
#[derive(Debug)]
pub struct Span<'t> {
    text: &'t str,
    start: usize,
    end: usize,
    kind: Option<LinkKind>,
}

impl<'t> Span<'t> {
    /// The start index of the span within the input text.
    #[inline]
    pub fn start(&self) -> usize {
        self.start
    }

    /// The end index of the span.
    #[inline]
    pub fn end(&self) -> usize {
        self.end
    }

    /// Get the span text as a `str`.
    #[inline]
    pub fn as_str(&self) -> &'t str {
        &self.text[self.start..self.end]
    }

    /// The type of link included in the span, if any.
    ///
    /// Returns `None` if the span represents plain text.
    #[inline]
    pub fn kind(&self) -> Option<&LinkKind> {
        self.kind.as_ref()
    }
}

/// A configured link finder.
#[derive(Debug)]
pub struct LinkFinder {
    email: bool,
    email_domain_must_have_dot: bool,
    url: bool,
}

/// Iterator for finding links.
pub struct Links<'t> {
    text: &'t str,
    rewind: usize,

    trigger_finder: Box<dyn Fn(&[u8]) -> Option<usize>>,
    email_scanner: EmailScanner,
    url_scanner: UrlScanner,
}

/// Iterator over spans.
pub struct Spans<'t> {
    text: &'t str,
    position: usize,
    links: Peekable<Links<'t>>,
}

impl LinkFinder {
    /// Create a new link finder with the default options for finding all kinds
    /// of links.
    ///
    /// If you only want to find a certain kind of links, use the `kinds` method.
    pub fn new() -> LinkFinder {
        LinkFinder {
            email: true,
            email_domain_must_have_dot: true,
            url: true,
        }
    }

    /// Require the domain parts of email addresses to have at least one dot.
    /// Use `false` to also find addresses such as `root@localhost`.
    pub fn email_domain_must_have_dot(&mut self, value: bool) -> &mut LinkFinder {
        self.email_domain_must_have_dot = value;
        self
    }

    /// Restrict the kinds of links that should be found to the specified ones.
    pub fn kinds(&mut self, kinds: &[LinkKind]) -> &mut LinkFinder {
        self.email = false;
        self.url = false;
        for kind in kinds {
            match *kind {
                LinkKind::Email => self.email = true,
                LinkKind::Url => self.url = true,
                _ => {}
            }
        }
        self
    }

    /// Find links in the specified input text.
    ///
    /// Returns an `Iterator` which only scans when `next` is called (lazy).
    pub fn links<'t>(&self, text: &'t str) -> Links<'t> {
        Links::new(text, self.url, self.email, self.email_domain_must_have_dot)
    }

    /// Iterate over spans in the specified input text.
    ///
    /// A span represents a substring of the input text,
    /// which can either be a link, or plain text.
    ///
    /// Returns an `Iterator` which only scans when `next` is called (lazy).
    ///
    /// The spans that are returned by the `Iterator` are consecutive,
    /// and when combined represent the input text in its entirety.
    pub fn spans<'t>(&self, text: &'t str) -> Spans<'t> {
        Spans {
            text,
            position: 0,
            links: self.links(text).peekable(),
        }
    }
}

impl Default for LinkFinder {
    fn default() -> Self {
        LinkFinder::new()
    }
}

impl<'t> Links<'t> {
    fn new(text: &'t str, url: bool, email: bool, email_domain_must_have_dot: bool) -> Links<'t> {
        let url_scanner = UrlScanner {};
        let email_scanner = EmailScanner {
            domain_must_have_dot: email_domain_must_have_dot,
        };
        let trigger_finder: Box<dyn Fn(&[u8]) -> Option<usize>> = match (url, email) {
            (true, true) => Box::new(|s| memchr2(b':', b'@', s)),
            (true, false) => Box::new(|s| memchr(b':', s)),
            (false, true) => Box::new(|s| memchr(b'@', s)),
            (false, false) => Box::new(|_| None),
        };
        Links {
            text,
            rewind: 0,
            trigger_finder,
            email_scanner,
            url_scanner,
        }
    }
}

impl<'t> Iterator for Links<'t> {
    type Item = Link<'t>;

    fn next(&mut self) -> Option<Link<'t>> {
        let slice = &self.text[self.rewind..];

        let mut find_from = 0;
        while let Some(i) = (self.trigger_finder)(slice[find_from..].as_bytes()) {
            let trigger = slice.as_bytes()[find_from + i];
            let (scanner, kind): (&dyn Scanner, LinkKind) = match trigger {
                b':' => (&self.url_scanner, LinkKind::Url),
                b'@' => (&self.email_scanner, LinkKind::Email),
                _ => unreachable!(),
            };
            if let Some(range) = scanner.scan(slice, find_from + i) {
                let start = self.rewind + range.start;
                let end = self.rewind + range.end;
                self.rewind = end;
                let link = Link {
                    text: &self.text,
                    start,
                    end,
                    kind,
                };
                return Some(link);
            } else {
                // The scanner didn't find anything. But there could be more
                // trigger characters later, so continue the search.
                find_from += i + 1;
            }
        }

        None
    }
}

impl<'t> fmt::Debug for Links<'t> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Links").field("text", &self.text).finish()
    }
}

impl<'t> Iterator for Spans<'t> {
    type Item = Span<'t>;

    fn next(&mut self) -> Option<Span<'t>> {
        match self.links.peek() {
            Some(ref link) => {
                if self.position < link.start {
                    let span = Span {
                        text: &self.text,
                        start: self.position,
                        end: link.start,
                        kind: None,
                    };
                    self.position = link.start;
                    return Some(span);
                }
            }
            None => {
                if self.position < self.text.len() {
                    let span = Span {
                        text: &self.text,
                        start: self.position,
                        end: self.text.len(),
                        kind: None,
                    };
                    self.position = self.text.len();
                    return Some(span);
                }
            }
        };
        self.links.next().map(|link| {
            self.position = link.end;
            Span {
                text: &self.text,
                start: link.start,
                end: link.end,
                kind: Some(link.kind),
            }
        })
    }
}

impl<'t> fmt::Debug for Spans<'t> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Spans").field("text", &self.text).finish()
    }
}