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