]> git.lizzy.rs Git - rust.git/blob - src/lists.rs
Merge branch 'single-import' of https://github.com/mattyhall/rustfmt into mattyhall...
[rust.git] / src / lists.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 use utils::make_indent;
12
13 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
14 pub enum ListTactic {
15     // One item per row.
16     Vertical,
17     // All items on one row.
18     Horizontal,
19     // Try Horizontal layout, if that fails then vertical
20     HorizontalVertical,
21     // Pack as many items as possible per row over (possibly) many rows.
22     Mixed,
23 }
24
25 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
26 pub enum SeparatorTactic {
27     Always,
28     Never,
29     Vertical,
30 }
31
32 // TODO having some helpful ctors for ListFormatting would be nice.
33 pub struct ListFormatting<'a> {
34     pub tactic: ListTactic,
35     pub separator: &'a str,
36     pub trailing_separator: SeparatorTactic,
37     pub indent: usize,
38     // Available width if we layout horizontally.
39     pub h_width: usize,
40     // Available width if we layout vertically
41     pub v_width: usize,
42 }
43
44 // Format a list of strings into a string.
45 // Precondition: all strings in items are trimmed.
46 pub fn write_list<'b>(items: &[(String, String)], formatting: &ListFormatting<'b>) -> String {
47     if items.len() == 0 {
48         return String::new();
49     }
50
51     let mut tactic = formatting.tactic;
52
53     // Conservatively overestimates because of the changing separator tactic.
54     let sep_count = if formatting.trailing_separator != SeparatorTactic::Never {
55         items.len()
56     } else {
57         items.len() - 1
58     };
59     let sep_len = formatting.separator.len();
60     let total_sep_len = (sep_len + 1) * sep_count;
61     let total_width = calculate_width(items);
62     let fits_single = total_width + total_sep_len <= formatting.h_width;
63
64     // Check if we need to fallback from horizontal listing, if possible.
65     if tactic == ListTactic::HorizontalVertical {
66         debug!("write_list: total_width: {}, total_sep_len: {}, h_width: {}",
67                total_width, total_sep_len, formatting.h_width);
68         tactic = if fits_single {
69             ListTactic::Horizontal
70         } else {
71             ListTactic::Vertical
72         };
73     }
74
75     // Check if we can fit everything on a single line in mixed mode.
76     // The horizontal tactic does not break after v_width columns.
77     if tactic == ListTactic::Mixed && fits_single {
78         tactic = ListTactic::Horizontal;
79     }
80
81     // Now that we know how we will layout, we can decide for sure if there
82     // will be a trailing separator.
83     let trailing_separator = needs_trailing_separator(formatting.trailing_separator, tactic);
84
85     // Create a buffer for the result.
86     // TODO could use a StringBuffer or rope for this
87     let alloc_width = if tactic == ListTactic::Horizontal {
88         total_width + total_sep_len
89     } else {
90         total_width + items.len() * (formatting.indent + 1)
91     };
92     let mut result = String::with_capacity(alloc_width);
93
94     let mut line_len = 0;
95     let indent_str = &make_indent(formatting.indent);
96     for (i, &(ref item, ref comment)) in items.iter().enumerate() {
97         let first = i == 0;
98         let separate = i != items.len() - 1 || trailing_separator;
99
100         match tactic {
101             ListTactic::Horizontal if !first => {
102                 result.push(' ');
103             }
104             ListTactic::Vertical if !first => {
105                 result.push('\n');
106                 result.push_str(indent_str);
107             }
108             ListTactic::Mixed => {
109                 let mut item_width = item.len();
110                 if separate {
111                     item_width += sep_len;
112                 }
113
114                 if line_len > 0 && line_len + item_width > formatting.v_width {
115                     result.push('\n');
116                     result.push_str(indent_str);
117                     line_len = 0;
118                 }
119
120                 if line_len > 0 {
121                     result.push(' ');
122                     line_len += 1;
123                 }
124
125                 line_len += item_width;
126             }
127             _ => {}
128         }
129
130         result.push_str(item);
131
132         if tactic != ListTactic::Vertical && comment.len() > 0 {
133             if !comment.starts_with('\n') {
134                 result.push(' ');
135             }
136             result.push_str(comment);
137         }
138
139         if separate {
140             result.push_str(formatting.separator);
141         }
142
143         if tactic == ListTactic::Vertical && comment.len() > 0 {
144             if !comment.starts_with('\n') {
145                 result.push(' ');
146             }
147             result.push_str(comment);
148         }
149     }
150
151     result
152 }
153
154 fn needs_trailing_separator(separator_tactic: SeparatorTactic, list_tactic: ListTactic) -> bool {
155     match separator_tactic {
156         SeparatorTactic::Always => true,
157         SeparatorTactic::Vertical => list_tactic == ListTactic::Vertical,
158         SeparatorTactic::Never => false,
159     }
160 }
161
162 fn calculate_width(items:&[(String, String)]) -> usize {
163     let missed_width = items.iter().map(|&(_, ref s)| {
164         let text_len = s.trim().len();
165         if text_len > 0 {
166             // We'll put a space before any comment.
167             text_len + 1
168         } else {
169             text_len
170         }
171     }).fold(0, |a, l| a + l);
172     let item_width = items.iter().map(|&(ref s, _)| s.len()).fold(0, |a, l| a + l);
173     missed_width + item_width
174 }