Skip to content

Commit 0786efc

Browse files
authored
Merge pull request #1804 from topecongiro/issue-1802
Consider max_width when rewriting struct in single-line
2 parents ba70ea3 + db5f77b commit 0786efc

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

src/items.rs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010

1111
// Formatting top-level items - functions, structs, enums, traits, impls.
1212

13+
use std::cmp::min;
14+
1315
use syntax::{abi, ast, ptr, symbol};
1416
use syntax::ast::ImplItem;
1517
use syntax::codemap::{BytePos, Span};
@@ -1120,15 +1122,22 @@ pub fn format_struct_struct(
11201122
return Some(result);
11211123
}
11221124

1125+
// 3 = ` ` and ` }`
1126+
let one_line_budget = context
1127+
.config
1128+
.max_width()
1129+
.checked_sub(result.len() + 3 + offset.width())
1130+
.unwrap_or(0);
1131+
11231132
let items_str = try_opt!(rewrite_with_alignment(
11241133
fields,
11251134
context,
11261135
Shape::indented(offset, context.config),
11271136
mk_sp(body_lo, span.hi),
1128-
one_line_width.unwrap_or(0),
1137+
one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget)),
11291138
));
11301139

1131-
if one_line_width.is_some() && !items_str.contains('\n') {
1140+
if one_line_width.is_some() && !items_str.contains('\n') && !result.contains('\n') {
11321141
Some(format!("{} {} }}", result, items_str))
11331142
} else {
11341143
Some(format!(

tests/target/issue-1802.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// rustfmt-tab_spaces: 2
2+
// rustfmt-max_width: 10
3+
// rustfmt-struct_variant_width: 10
4+
// rustfmt-error_on_line_overflow: false
5+
6+
enum F {
7+
X {
8+
a: d,
9+
b: e,
10+
},
11+
}

0 commit comments

Comments
 (0)