]> git.lizzy.rs Git - rust.git/commitdiff
Consider max_width when rewriting struct in single-line
authortopecongiro <seuchida@gmail.com>
Thu, 20 Jul 2017 22:17:49 +0000 (07:17 +0900)
committertopecongiro <seuchida@gmail.com>
Thu, 20 Jul 2017 22:17:49 +0000 (07:17 +0900)
src/items.rs
tests/target/issue-1802.rs [new file with mode: 0644]

index 1b9c44957610809b797cffce19dfac2f9f07f910..22ac1354e34ee80aa308b90f0f06fdac53e28db1 100644 (file)
@@ -10,6 +10,8 @@
 
 // Formatting top-level items - functions, structs, enums, traits, impls.
 
+use std::cmp::min;
+
 use syntax::{abi, ast, ptr, symbol};
 use syntax::ast::ImplItem;
 use syntax::codemap::{BytePos, Span};
@@ -1120,15 +1122,22 @@ pub fn format_struct_struct(
         return Some(result);
     }
 
+    // 3 = ` ` and ` }`
+    let one_line_budget = context
+        .config
+        .max_width()
+        .checked_sub(result.len() + 3 + offset.width())
+        .unwrap_or(0);
+
     let items_str = try_opt!(rewrite_with_alignment(
         fields,
         context,
         Shape::indented(offset, context.config),
         mk_sp(body_lo, span.hi),
-        one_line_width.unwrap_or(0),
+        one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget)),
     ));
 
-    if one_line_width.is_some() && !items_str.contains('\n') {
+    if one_line_width.is_some() && !items_str.contains('\n') && !result.contains('\n') {
         Some(format!("{} {} }}", result, items_str))
     } else {
         Some(format!(
diff --git a/tests/target/issue-1802.rs b/tests/target/issue-1802.rs
new file mode 100644 (file)
index 0000000..236a49f
--- /dev/null
@@ -0,0 +1,11 @@
+// rustfmt-tab_spaces: 2
+// rustfmt-max_width: 10
+// rustfmt-struct_variant_width: 10
+// rustfmt-error_on_line_overflow: false
+
+enum F {
+  X {
+    a: d,
+    b: e,
+  },
+}