]> git.lizzy.rs Git - rust.git/blob - src/string.rs
Merge pull request #1973 from topecongiro/issue-1972
[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 Shape;
17 use config::Config;
18 use utils::wrap_str;
19
20 const MIN_STRING: usize = 10;
21
22 pub struct StringFormat<'a> {
23     pub opener: &'a str,
24     pub closer: &'a str,
25     pub line_start: &'a str,
26     pub line_end: &'a str,
27     pub shape: Shape,
28     pub trim_end: bool,
29     pub config: &'a Config,
30 }
31
32 // FIXME: simplify this!
33 pub fn rewrite_string<'a>(orig: &str, fmt: &StringFormat<'a>) -> Option<String> {
34     // Strip line breaks.
35     let re = Regex::new(r"([^\\](\\\\)*)\\[\n\r][[:space:]]*").unwrap();
36     let stripped_str = re.replace_all(orig, "$1");
37
38     let graphemes = UnicodeSegmentation::graphemes(&*stripped_str, false).collect::<Vec<&str>>();
39     let shape = fmt.shape.visual_indent(0);
40     let indent = shape.indent.to_string(fmt.config);
41     let punctuation = ":,;.";
42
43     // `cur_start` is the position in `orig` of the start of the current line.
44     let mut cur_start = 0;
45     let mut result = String::with_capacity(
46         stripped_str
47             .len()
48             .checked_next_power_of_two()
49             .unwrap_or(usize::max_value()),
50     );
51     result.push_str(fmt.opener);
52
53     let ender_length = fmt.line_end.len();
54     // If we cannot put at least a single character per line, the rewrite won't
55     // succeed.
56     let max_chars = try_opt!(shape.width.checked_sub(fmt.opener.len() + ender_length + 1)) + 1;
57
58     // Snip a line at a time from `orig` until it is used up. Push the snippet
59     // onto result.
60     'outer: loop {
61         // `cur_end` will be where we break the line, as an offset into `orig`.
62         // Initialised to the maximum it could be (which may be beyond `orig`).
63         let mut cur_end = cur_start + max_chars;
64
65         // We can fit the rest of the string on this line, so we're done.
66         if cur_end >= graphemes.len() {
67             let line = &graphemes[cur_start..].join("");
68             result.push_str(line);
69             break 'outer;
70         }
71
72         // Push cur_end left until we reach whitespace (or the line is too small).
73         while !graphemes[cur_end - 1].trim().is_empty() {
74             cur_end -= 1;
75             if cur_end < cur_start + MIN_STRING {
76                 // We couldn't find whitespace before the string got too small.
77                 // So start again at the max length and look for punctuation.
78                 cur_end = cur_start + max_chars;
79                 while !punctuation.contains(graphemes[cur_end - 1]) {
80                     cur_end -= 1;
81
82                     // If we can't break at whitespace or punctuation, grow the string instead.
83                     if cur_end < cur_start + MIN_STRING {
84                         cur_end = cur_start + max_chars;
85                         while !(punctuation.contains(graphemes[cur_end - 1])
86                             || graphemes[cur_end - 1].trim().is_empty())
87                         {
88                             if cur_end >= graphemes.len() {
89                                 let line = &graphemes[cur_start..].join("");
90                                 result.push_str(line);
91                                 break 'outer;
92                             }
93                             cur_end += 1;
94                         }
95                         break;
96                     }
97                 }
98                 break;
99             }
100         }
101         // Make sure there is no whitespace to the right of the break.
102         while cur_end < stripped_str.len() && graphemes[cur_end].trim().is_empty() {
103             cur_end += 1;
104         }
105
106         // Make the current line and add it on to result.
107         let raw_line = graphemes[cur_start..cur_end].join("");
108         let line = if fmt.trim_end {
109             raw_line.trim()
110         } else {
111             raw_line.as_str()
112         };
113
114         result.push_str(line);
115         result.push_str(fmt.line_end);
116         result.push('\n');
117         result.push_str(&indent);
118         result.push_str(fmt.line_start);
119
120         // The next line starts where the current line ends.
121         cur_start = cur_end;
122     }
123
124     result.push_str(fmt.closer);
125     wrap_str(result, fmt.config.max_width(), fmt.shape)
126 }
127
128 #[cfg(test)]
129 mod test {
130     use super::{rewrite_string, StringFormat};
131
132     #[test]
133     fn issue343() {
134         let config = Default::default();
135         let fmt = StringFormat {
136             opener: "\"",
137             closer: "\"",
138             line_start: " ",
139             line_end: "\\",
140             shape: ::Shape::legacy(2, ::Indent::empty()),
141             trim_end: false,
142             config: &config,
143         };
144
145         rewrite_string("eq_", &fmt);
146     }
147 }