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