]> git.lizzy.rs Git - rust.git/blob - src/string.rs
rewrite_string: detect when a url is being split and place the new line
[rust.git] / src / string.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Format string literals.
12
13 use regex::Regex;
14 use unicode_segmentation::UnicodeSegmentation;
15
16 use config::Config;
17 use shape::Shape;
18 use utils::wrap_str;
19
20 const MIN_STRING: usize = 10;
21
22 /// Describes the layout of a piece of text.
23 pub struct StringFormat<'a> {
24     /// The opening sequence of characters for the piece of text
25     pub opener: &'a str,
26     /// The closing sequence of characters for the piece of text
27     pub closer: &'a str,
28     /// The opening sequence of characters for a line
29     pub line_start: &'a str,
30     /// The closing sequence of characters for a line
31     pub line_end: &'a str,
32     /// The allocated box to fit the text into
33     pub shape: Shape,
34     /// Trim trailing whitespaces
35     pub trim_end: bool,
36     pub config: &'a Config,
37 }
38
39 impl<'a> StringFormat<'a> {
40     pub fn new(shape: Shape, config: &'a Config) -> StringFormat<'a> {
41         StringFormat {
42             opener: "\"",
43             closer: "\"",
44             line_start: " ",
45             line_end: "\\",
46             shape,
47             trim_end: false,
48             config,
49         }
50     }
51
52     /// Returns the maximum number of graphemes that is possible on a line while taking the
53     /// indentation into account.
54     ///
55     /// If we cannot put at least a single character per line, the rewrite won't succeed.
56     fn max_chars_with_indent(&self) -> Option<usize> {
57         Some(
58             self.shape
59                 .width
60                 .checked_sub(self.opener.len() + self.line_end.len() + 1)?
61                 + 1,
62         )
63     }
64
65     /// Like max_chars_with_indent but the indentation is not substracted.
66     /// This allows to fit more graphemes from the string on a line when
67     /// SnippetState::EndWithLineFeed.
68     fn max_chars_without_indent(&self) -> Option<usize> {
69         Some(self.config.max_width().checked_sub(self.line_end.len())?)
70     }
71 }
72
73 pub fn rewrite_string<'a>(orig: &str, fmt: &StringFormat<'a>) -> Option<String> {
74     let max_chars_with_indent = fmt.max_chars_with_indent()?;
75     let max_chars_without_indent = fmt.max_chars_without_indent()?;
76     let indent_with_newline = fmt.shape.indent.to_string_with_newline(fmt.config);
77     let indent_without_newline = fmt.shape.indent.to_string(fmt.config);
78
79     // Strip line breaks.
80     // With this regex applied, all remaining whitespaces are significant
81     let strip_line_breaks_re = Regex::new(r"([^\\](\\\\)*)\\[\n\r][[:space:]]*").unwrap();
82     let stripped_str = strip_line_breaks_re.replace_all(orig, "$1");
83
84     let graphemes = UnicodeSegmentation::graphemes(&*stripped_str, false).collect::<Vec<&str>>();
85
86     // `cur_start` is the position in `orig` of the start of the current line.
87     let mut cur_start = 0;
88     let mut result = String::with_capacity(
89         stripped_str
90             .len()
91             .checked_next_power_of_two()
92             .unwrap_or(usize::max_value()),
93     );
94     result.push_str(fmt.opener);
95
96     // Snip a line at a time from `stripped_str` until it is used up. Push the snippet
97     // onto result.
98     let mut cur_max_chars = max_chars_with_indent;
99     let is_bareline_ok = fmt.line_start.is_empty() || is_whitespace(fmt.line_start);
100     loop {
101         // All the input starting at cur_start fits on the current line
102         if graphemes.len() - cur_start <= cur_max_chars {
103             for (i, grapheme) in graphemes[cur_start..].iter().enumerate() {
104                 if is_line_feed(grapheme) {
105                     // take care of blank lines
106                     result = trim_right_but_line_feed(fmt.trim_end, result);
107                     result.push_str("\n");
108                     if !is_bareline_ok && cur_start + i + 1 < graphemes.len() {
109                         result.push_str(&indent_without_newline);
110                         result.push_str(fmt.line_start);
111                     }
112                 } else {
113                     result.push_str(grapheme);
114                 }
115             }
116             result = trim_right_but_line_feed(fmt.trim_end, result);
117             break;
118         }
119
120         // The input starting at cur_start needs to be broken
121         match break_string(
122             cur_max_chars,
123             fmt.trim_end,
124             fmt.line_end,
125             &graphemes[cur_start..],
126         ) {
127             SnippetState::LineEnd(line, len) => {
128                 result.push_str(&line);
129                 result.push_str(fmt.line_end);
130                 result.push_str(&indent_with_newline);
131                 result.push_str(fmt.line_start);
132                 cur_max_chars = max_chars_with_indent;
133                 cur_start += len;
134             }
135             SnippetState::EndWithLineFeed(line, len) => {
136                 if line == "\n" && fmt.trim_end {
137                     result = result.trim_right().to_string();
138                 }
139                 result.push_str(&line);
140                 if is_bareline_ok {
141                     // the next line can benefit from the full width
142                     cur_max_chars = max_chars_without_indent;
143                 } else {
144                     result.push_str(&indent_without_newline);
145                     result.push_str(fmt.line_start);
146                     cur_max_chars = max_chars_with_indent;
147                 }
148                 cur_start += len;
149             }
150             SnippetState::EndOfInput(line) => {
151                 result.push_str(&line);
152                 break;
153             }
154         }
155     }
156
157     result.push_str(fmt.closer);
158     wrap_str(result, fmt.config.max_width(), fmt.shape)
159 }
160
161 /// Returns the index to the end of the url if the given string includes an
162 /// URL or alike. Otherwise, returns None;
163 fn detect_url(s: &[&str], index: usize) -> Option<usize> {
164     let start = match s[..=index].iter().rposition(|g| is_whitespace(g)) {
165         Some(pos) => pos + 1,
166         None => 0,
167     };
168     if s.len() < start + 8 {
169         return None;
170     }
171     let prefix = s[start..start + 8].join("");
172     if prefix.starts_with("https://")
173         || prefix.starts_with("http://")
174         || prefix.starts_with("ftp://")
175         || prefix.starts_with("file://")
176     {
177         match s[index..].iter().position(|g| is_whitespace(g)) {
178             Some(pos) => Some(index + pos - 1),
179             None => Some(s.len() - 1),
180         }
181     } else {
182         None
183     }
184 }
185
186 /// Trims whitespaces to the right except for the line feed character.
187 fn trim_right_but_line_feed(trim_end: bool, result: String) -> String {
188     let whitespace_except_line_feed = |c: char| c.is_whitespace() && c != '\n';
189     if trim_end && result.ends_with(whitespace_except_line_feed) {
190         result
191             .trim_right_matches(whitespace_except_line_feed)
192             .to_string()
193     } else {
194         result
195     }
196 }
197
198 /// Result of breaking a string so it fits in a line and the state it ended in.
199 /// The state informs about what to do with the snippet and how to continue the breaking process.
200 #[derive(Debug, PartialEq)]
201 enum SnippetState {
202     /// The input could not be broken and so rewriting the string is finished.
203     EndOfInput(String),
204     /// The input could be broken and the returned snippet should be ended with a
205     /// `[StringFormat::line_end]`. The next snippet needs to be indented.
206     ///
207     /// The returned string is the line to print out and the number is the length that got read in
208     /// the text being rewritten. That length may be greater than the returned string if trailing
209     /// whitespaces got trimmed.
210     LineEnd(String, usize),
211     /// The input could be broken but a newline is present that cannot be trimmed. The next snippet
212     /// to be rewritten *could* use more width than what is specified by the given shape. For
213     /// example with a multiline string, the next snippet does not need to be indented, allowing
214     /// more characters to be fit within a line.
215     ///
216     /// The returned string is the line to print out and the number is the length that got read in
217     /// the text being rewritten.
218     EndWithLineFeed(String, usize),
219 }
220
221 fn not_whitespace_except_line_feed(g: &str) -> bool {
222     is_line_feed(g) || !is_whitespace(g)
223 }
224
225 /// Break the input string at a boundary character around the offset `max_chars`. A boundary
226 /// character is either a punctuation or a whitespace.
227 fn break_string(max_chars: usize, trim_end: bool, line_end: &str, input: &[&str]) -> SnippetState {
228     let break_at = |index /* grapheme at index is included */| {
229         // Take in any whitespaces to the left/right of `input[index]` while
230         // preserving line feeds
231         let index_minus_ws = input[0..=index]
232             .iter()
233             .rposition(|grapheme| not_whitespace_except_line_feed(grapheme))
234             .unwrap_or(index);
235         // Take into account newlines occuring in input[0..=index], i.e., the possible next new
236         // line. If there is one, then text after it could be rewritten in a way that the available
237         // space is fully used.
238         for (i, grapheme) in input[0..=index].iter().enumerate() {
239             if is_line_feed(grapheme) {
240                 if i <= index_minus_ws {
241                     let mut line = input[0..i].join("");
242                     if trim_end {
243                         line = line.trim_right().to_string();
244                     }
245                     return SnippetState::EndWithLineFeed(format!("{}\n", line), i + 1);
246                 }
247                 break;
248             }
249         }
250
251         let mut index_plus_ws = index;
252         for (i, grapheme) in input[index + 1..].iter().enumerate() {
253             if !trim_end && is_line_feed(grapheme) {
254                 return SnippetState::EndWithLineFeed(
255                     input[0..=index + 1 + i].join("").to_string(),
256                     index + 2 + i,
257                 );
258             } else if not_whitespace_except_line_feed(grapheme) {
259                 index_plus_ws = index + i;
260                 break;
261             }
262         }
263
264         if trim_end {
265             SnippetState::LineEnd(
266                 input[0..=index_minus_ws].join("").to_string(),
267                 index_plus_ws + 1,
268             )
269         } else {
270             SnippetState::LineEnd(
271                 input[0..=index_plus_ws].join("").to_string(),
272                 index_plus_ws + 1,
273             )
274         }
275     };
276
277     // Find the position in input for breaking the string
278     if line_end.is_empty()
279         && trim_end
280         && !is_whitespace(input[max_chars - 1])
281         && is_whitespace(input[max_chars])
282     {
283         // At a breaking point already
284         // The line won't invalidate the rewriting because:
285         // - no extra space needed for the line_end character
286         // - extra whitespaces to the right can be trimmed
287         return break_at(max_chars - 1);
288     }
289     if let Some(url_index_end) = detect_url(input, max_chars) {
290         let index_plus_ws = url_index_end + input[url_index_end..]
291             .iter()
292             .skip(1)
293             .position(|grapheme| not_whitespace_except_line_feed(grapheme))
294             .unwrap_or(0);
295         return if trim_end {
296             SnippetState::LineEnd(
297                 input[..=url_index_end].join("").to_string(),
298                 index_plus_ws + 1,
299             )
300         } else {
301             return SnippetState::LineEnd(
302                 input[..=index_plus_ws].join("").to_string(),
303                 index_plus_ws + 1,
304             );
305         };
306     }
307     match input[0..max_chars]
308         .iter()
309         .rposition(|grapheme| is_whitespace(grapheme))
310     {
311         // Found a whitespace and what is on its left side is big enough.
312         Some(index) if index >= MIN_STRING => break_at(index),
313         // No whitespace found, try looking for a punctuation instead
314         _ => match input[0..max_chars]
315             .iter()
316             .rposition(|grapheme| is_punctuation(grapheme))
317         {
318             // Found a punctuation and what is on its left side is big enough.
319             Some(index) if index >= MIN_STRING => break_at(index),
320             // Either no boundary character was found to the left of `input[max_chars]`, or the line
321             // got too small. We try searching for a boundary character to the right.
322             _ => match input[max_chars..]
323                 .iter()
324                 .position(|grapheme| is_whitespace(grapheme) || is_punctuation(grapheme))
325             {
326                 // A boundary was found after the line limit
327                 Some(index) => break_at(max_chars + index),
328                 // No boundary to the right, the input cannot be broken
329                 None => SnippetState::EndOfInput(input.join("").to_string()),
330             },
331         },
332     }
333 }
334
335 fn is_line_feed(grapheme: &str) -> bool {
336     grapheme.as_bytes()[0] == b'\n'
337 }
338
339 fn is_whitespace(grapheme: &str) -> bool {
340     grapheme.chars().all(|c| c.is_whitespace())
341 }
342
343 fn is_punctuation(grapheme: &str) -> bool {
344     match grapheme.as_bytes()[0] {
345         b':' | b',' | b';' | b'.' => true,
346         _ => false,
347     }
348 }
349
350 #[cfg(test)]
351 mod test {
352     use super::{break_string, detect_url, rewrite_string, SnippetState, StringFormat};
353     use config::Config;
354     use shape::{Indent, Shape};
355     use unicode_segmentation::UnicodeSegmentation;
356
357     #[test]
358     fn issue343() {
359         let config = Default::default();
360         let fmt = StringFormat::new(Shape::legacy(2, Indent::empty()), &config);
361         rewrite_string("eq_", &fmt);
362     }
363
364     #[test]
365     fn should_break_on_whitespace() {
366         let string = "Placerat felis. Mauris porta ante sagittis purus.";
367         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
368         assert_eq!(
369             break_string(20, false, "", &graphemes[..]),
370             SnippetState::LineEnd("Placerat felis. ".to_string(), 16)
371         );
372         assert_eq!(
373             break_string(20, true, "", &graphemes[..]),
374             SnippetState::LineEnd("Placerat felis.".to_string(), 16)
375         );
376     }
377
378     #[test]
379     fn should_break_on_punctuation() {
380         let string = "Placerat_felis._Mauris_porta_ante_sagittis_purus.";
381         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
382         assert_eq!(
383             break_string(20, false, "", &graphemes[..]),
384             SnippetState::LineEnd("Placerat_felis.".to_string(), 15)
385         );
386     }
387
388     #[test]
389     fn should_break_forward() {
390         let string = "Venenatis_tellus_vel_tellus. Aliquam aliquam dolor at justo.";
391         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
392         assert_eq!(
393             break_string(20, false, "", &graphemes[..]),
394             SnippetState::LineEnd("Venenatis_tellus_vel_tellus. ".to_string(), 29)
395         );
396         assert_eq!(
397             break_string(20, true, "", &graphemes[..]),
398             SnippetState::LineEnd("Venenatis_tellus_vel_tellus.".to_string(), 29)
399         );
400     }
401
402     #[test]
403     fn nothing_to_break() {
404         let string = "Venenatis_tellus_vel_tellus";
405         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
406         assert_eq!(
407             break_string(20, false, "", &graphemes[..]),
408             SnippetState::EndOfInput("Venenatis_tellus_vel_tellus".to_string())
409         );
410     }
411
412     #[test]
413     fn significant_whitespaces() {
414         let string = "Neque in sem.      \n      Pellentesque tellus augue.";
415         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
416         assert_eq!(
417             break_string(15, false, "", &graphemes[..]),
418             SnippetState::EndWithLineFeed("Neque in sem.      \n".to_string(), 20)
419         );
420         assert_eq!(
421             break_string(25, false, "", &graphemes[..]),
422             SnippetState::EndWithLineFeed("Neque in sem.      \n".to_string(), 20)
423         );
424
425         assert_eq!(
426             break_string(15, true, "", &graphemes[..]),
427             SnippetState::LineEnd("Neque in sem.".to_string(), 19)
428         );
429         assert_eq!(
430             break_string(25, true, "", &graphemes[..]),
431             SnippetState::EndWithLineFeed("Neque in sem.\n".to_string(), 20)
432         );
433     }
434
435     #[test]
436     fn big_whitespace() {
437         let string = "Neque in sem.            Pellentesque tellus augue.";
438         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
439         assert_eq!(
440             break_string(20, false, "", &graphemes[..]),
441             SnippetState::LineEnd("Neque in sem.            ".to_string(), 25)
442         );
443         assert_eq!(
444             break_string(20, true, "", &graphemes[..]),
445             SnippetState::LineEnd("Neque in sem.".to_string(), 25)
446         );
447     }
448
449     #[test]
450     fn newline_in_candidate_line() {
451         let string = "Nulla\nconsequat erat at massa. Vivamus id mi.";
452
453         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
454         assert_eq!(
455             break_string(25, false, "", &graphemes[..]),
456             SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
457         );
458         assert_eq!(
459             break_string(25, true, "", &graphemes[..]),
460             SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
461         );
462
463         let mut config: Config = Default::default();
464         config.set().max_width(27);
465         let fmt = StringFormat::new(Shape::legacy(25, Indent::empty()), &config);
466         let rewritten_string = rewrite_string(string, &fmt);
467         assert_eq!(
468             rewritten_string,
469             Some("\"Nulla\nconsequat erat at massa. \\\n Vivamus id mi.\"".to_string())
470         );
471     }
472
473     #[test]
474     fn last_line_fit_with_trailing_whitespaces() {
475         let string = "Vivamus id mi.  ";
476         let config: Config = Default::default();
477         let mut fmt = StringFormat::new(Shape::legacy(25, Indent::empty()), &config);
478
479         fmt.trim_end = true;
480         let rewritten_string = rewrite_string(string, &fmt);
481         assert_eq!(rewritten_string, Some("\"Vivamus id mi.\"".to_string()));
482
483         fmt.trim_end = false; // default value of trim_end
484         let rewritten_string = rewrite_string(string, &fmt);
485         assert_eq!(rewritten_string, Some("\"Vivamus id mi.  \"".to_string()));
486     }
487
488     #[test]
489     fn last_line_fit_with_newline() {
490         let string = "Vivamus id mi.\nVivamus id mi.";
491         let config: Config = Default::default();
492         let fmt = StringFormat {
493             opener: "",
494             closer: "",
495             line_start: "// ",
496             line_end: "",
497             shape: Shape::legacy(100, Indent::from_width(&config, 4)),
498             trim_end: true,
499             config: &config,
500         };
501
502         let rewritten_string = rewrite_string(string, &fmt);
503         assert_eq!(
504             rewritten_string,
505             Some("Vivamus id mi.\n    // Vivamus id mi.".to_string())
506         );
507     }
508
509     #[test]
510     fn overflow_in_non_string_content() {
511         let comment = "Aenean metus.\nVestibulum ac lacus. Vivamus porttitor";
512         let config: Config = Default::default();
513         let fmt = StringFormat {
514             opener: "",
515             closer: "",
516             line_start: "// ",
517             line_end: "",
518             shape: Shape::legacy(30, Indent::from_width(&config, 8)),
519             trim_end: true,
520             config: &config,
521         };
522
523         assert_eq!(
524             rewrite_string(comment, &fmt),
525             Some(
526                 "Aenean metus.\n        // Vestibulum ac lacus. Vivamus\n        // porttitor"
527                     .to_string()
528             )
529         );
530     }
531
532     #[test]
533     fn overflow_in_non_string_content_with_line_end() {
534         let comment = "Aenean metus.\nVestibulum ac lacus. Vivamus porttitor";
535         let config: Config = Default::default();
536         let fmt = StringFormat {
537             opener: "",
538             closer: "",
539             line_start: "// ",
540             line_end: "@",
541             shape: Shape::legacy(30, Indent::from_width(&config, 8)),
542             trim_end: true,
543             config: &config,
544         };
545
546         assert_eq!(
547             rewrite_string(comment, &fmt),
548             Some(
549                 "Aenean metus.\n        // Vestibulum ac lacus. Vivamus@\n        // porttitor"
550                     .to_string()
551             )
552         );
553     }
554
555     #[test]
556     fn blank_line_with_non_empty_line_start() {
557         let config: Config = Default::default();
558         let mut fmt = StringFormat {
559             opener: "",
560             closer: "",
561             line_start: "// ",
562             line_end: "",
563             shape: Shape::legacy(30, Indent::from_width(&config, 4)),
564             trim_end: true,
565             config: &config,
566         };
567
568         let comment = "Aenean metus. Vestibulum\n\nac lacus. Vivamus porttitor";
569         assert_eq!(
570             rewrite_string(comment, &fmt),
571             Some(
572                 "Aenean metus. Vestibulum\n    //\n    // ac lacus. Vivamus porttitor".to_string()
573             )
574         );
575
576         fmt.shape = Shape::legacy(15, Indent::from_width(&config, 4));
577         let comment = "Aenean\n\nmetus. Vestibulum ac lacus. Vivamus porttitor";
578         assert_eq!(
579             rewrite_string(comment, &fmt),
580             Some(
581                 r#"Aenean
582     //
583     // metus. Vestibulum
584     // ac lacus. Vivamus
585     // porttitor"#
586                     .to_string()
587             )
588         );
589     }
590
591     #[test]
592     fn retain_blank_lines() {
593         let config: Config = Default::default();
594         let fmt = StringFormat {
595             opener: "",
596             closer: "",
597             line_start: "// ",
598             line_end: "",
599             shape: Shape::legacy(20, Indent::from_width(&config, 4)),
600             trim_end: true,
601             config: &config,
602         };
603
604         let comment = "Aenean\n\nmetus. Vestibulum ac lacus.\n\n";
605         assert_eq!(
606             rewrite_string(comment, &fmt),
607             Some(
608                 "Aenean\n    //\n    // metus. Vestibulum ac\n    // lacus.\n    //\n".to_string()
609             )
610         );
611
612         let comment = "Aenean\n\nmetus. Vestibulum ac lacus.\n";
613         assert_eq!(
614             rewrite_string(comment, &fmt),
615             Some("Aenean\n    //\n    // metus. Vestibulum ac\n    // lacus.\n".to_string())
616         );
617
618         let comment = "Aenean\n        \nmetus. Vestibulum ac lacus.";
619         assert_eq!(
620             rewrite_string(comment, &fmt),
621             Some("Aenean\n    //\n    // metus. Vestibulum ac\n    // lacus.".to_string())
622         );
623     }
624
625     #[test]
626     fn boundary_on_edge() {
627         let config: Config = Default::default();
628         let mut fmt = StringFormat {
629             opener: "",
630             closer: "",
631             line_start: "// ",
632             line_end: "",
633             shape: Shape::legacy(13, Indent::from_width(&config, 4)),
634             trim_end: true,
635             config: &config,
636         };
637
638         let comment = "Aenean metus. Vestibulum ac lacus.";
639         assert_eq!(
640             rewrite_string(comment, &fmt),
641             Some("Aenean metus.\n    // Vestibulum ac\n    // lacus.".to_string())
642         );
643
644         fmt.trim_end = false;
645         let comment = "Vestibulum ac lacus.";
646         assert_eq!(
647             rewrite_string(comment, &fmt),
648             Some("Vestibulum \n    // ac lacus.".to_string())
649         );
650
651         fmt.trim_end = true;
652         fmt.line_end = "\\";
653         let comment = "Vestibulum ac lacus.";
654         assert_eq!(
655             rewrite_string(comment, &fmt),
656             Some("Vestibulum\\\n    // ac lacus.".to_string())
657         );
658     }
659
660     #[test]
661     fn detect_urls() {
662         let string = "aaa http://example.org something";
663         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
664         assert_eq!(detect_url(&graphemes, 8), Some(21));
665
666         let string = "https://example.org something";
667         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
668         assert_eq!(detect_url(&graphemes, 0), Some(18));
669
670         let string = "aaa ftp://example.org something";
671         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
672         assert_eq!(detect_url(&graphemes, 8), Some(20));
673
674         let string = "aaa file://example.org something";
675         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
676         assert_eq!(detect_url(&graphemes, 8), Some(21));
677
678         let string = "aaa http not an url";
679         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
680         assert_eq!(detect_url(&graphemes, 6), None);
681
682         let string = "aaa file://example.org";
683         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
684         assert_eq!(detect_url(&graphemes, 8), Some(21));
685     }
686 }