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