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.
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.
11 use utils::make_indent;
12 use rustc_serialize::{Decodable, Decoder};
14 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
18 // All items on one row.
20 // Try Horizontal layout, if that fails then vertical
22 // Pack as many items as possible per row over (possibly) many rows.
26 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
27 pub enum SeparatorTactic {
33 // TODO could use a macro for all these Decodable impls.
34 impl Decodable for SeparatorTactic {
35 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
36 let s = try!(d.read_str());
38 "Always" => Ok(SeparatorTactic::Always),
39 "Never" => Ok(SeparatorTactic::Never),
40 "Vertical" => Ok(SeparatorTactic::Vertical),
41 _ => Err(d.error("Bad variant")),
46 // TODO having some helpful ctors for ListFormatting would be nice.
47 pub struct ListFormatting<'a> {
48 pub tactic: ListTactic,
49 pub separator: &'a str,
50 pub trailing_separator: SeparatorTactic,
52 // Available width if we layout horizontally.
54 // Available width if we layout vertically
58 // Format a list of strings into a string.
59 // Precondition: all strings in items are trimmed.
60 pub fn write_list<'b>(items: &[(String, String)], formatting: &ListFormatting<'b>) -> String {
65 let mut tactic = formatting.tactic;
67 // Conservatively overestimates because of the changing separator tactic.
68 let sep_count = if formatting.trailing_separator != SeparatorTactic::Never {
73 let sep_len = formatting.separator.len();
74 let total_sep_len = (sep_len + 1) * sep_count;
75 let total_width = calculate_width(items);
76 let fits_single = total_width + total_sep_len <= formatting.h_width;
78 // Check if we need to fallback from horizontal listing, if possible.
79 if tactic == ListTactic::HorizontalVertical {
80 debug!("write_list: total_width: {}, total_sep_len: {}, h_width: {}",
81 total_width, total_sep_len, formatting.h_width);
82 tactic = if fits_single &&
83 !items.iter().any(|&(ref s, _)| s.contains('\n')) {
84 ListTactic::Horizontal
90 // Check if we can fit everything on a single line in mixed mode.
91 // The horizontal tactic does not break after v_width columns.
92 if tactic == ListTactic::Mixed && fits_single {
93 tactic = ListTactic::Horizontal;
96 // Now that we know how we will layout, we can decide for sure if there
97 // will be a trailing separator.
98 let trailing_separator = needs_trailing_separator(formatting.trailing_separator, tactic);
100 // Create a buffer for the result.
101 // TODO could use a StringBuffer or rope for this
102 let alloc_width = if tactic == ListTactic::Horizontal {
103 total_width + total_sep_len
105 total_width + items.len() * (formatting.indent + 1)
107 let mut result = String::with_capacity(alloc_width);
109 let mut line_len = 0;
110 let indent_str = &make_indent(formatting.indent);
111 for (i, &(ref item, ref comment)) in items.iter().enumerate() {
113 let separate = i != items.len() - 1 || trailing_separator;
116 ListTactic::Horizontal if !first => {
119 ListTactic::Vertical if !first => {
121 result.push_str(indent_str);
123 ListTactic::Mixed => {
124 let mut item_width = item.len();
126 item_width += sep_len;
129 if line_len > 0 && line_len + item_width > formatting.v_width {
131 result.push_str(indent_str);
140 line_len += item_width;
145 result.push_str(item);
147 if tactic != ListTactic::Vertical && comment.len() > 0 {
148 if !comment.starts_with('\n') {
151 result.push_str(comment);
155 result.push_str(formatting.separator);
158 if tactic == ListTactic::Vertical && comment.len() > 0 {
159 if !comment.starts_with('\n') {
162 result.push_str(comment);
169 fn needs_trailing_separator(separator_tactic: SeparatorTactic, list_tactic: ListTactic) -> bool {
170 match separator_tactic {
171 SeparatorTactic::Always => true,
172 SeparatorTactic::Vertical => list_tactic == ListTactic::Vertical,
173 SeparatorTactic::Never => false,
177 fn calculate_width(items:&[(String, String)]) -> usize {
178 let missed_width = items.iter().map(|&(_, ref s)| {
179 let text_len = s.trim().len();
181 // We'll put a space before any comment.
186 }).fold(0, |a, l| a + l);
187 let item_width = items.iter().map(|&(ref s, _)| s.len()).fold(0, |a, l| a + l);
188 missed_width + item_width