Skip to content

Commit

Permalink
Add trailing comma support
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Jan 7, 2022
1 parent b9fde2d commit e2a0297
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
4 changes: 4 additions & 0 deletions src/algorithm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ pub enum Breaks {
pub struct BreakToken {
pub offset: isize,
pub blank_space: usize,
pub trailing_comma: bool,
}

#[derive(Clone, Copy)]
Expand Down Expand Up @@ -255,6 +256,9 @@ impl Printer {
self.pending_indentation += token.blank_space;
self.space -= token.blank_space as isize;
} else {
if token.trailing_comma {
self.out.push(',');
}
self.out.push('\n');
let indent = self.indent as isize + token.offset;
self.pending_indentation = indent as usize;
Expand Down
10 changes: 10 additions & 0 deletions src/convenience.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ impl Printer {
self.scan_break(BreakToken {
offset: off,
blank_space: n,
trailing_comma: false,
});
}

Expand Down Expand Up @@ -62,6 +63,15 @@ impl Printer {
Token::Break(BreakToken {
offset: off,
blank_space: algorithm::SIZE_INFINITY as usize,
trailing_comma: false,
})
}

pub fn trailing_comma(&mut self) {
self.scan_break(BreakToken {
offset: 0,
blank_space: 0,
trailing_comma: true,
});
}
}
10 changes: 7 additions & 3 deletions src/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,14 @@ impl Printer {
self.word("(");
self.cbox(INDENT);
self.zerobreak();
for field in &fields.unnamed {
for (i, field) in fields.unnamed.iter().enumerate() {
self.field(field);
self.word(",");
self.space();
if i < fields.unnamed.len() - 1 {
self.word(",");
self.space();
} else {
self.trailing_comma();
}
}
self.offset(-INDENT);
self.end();
Expand Down

0 comments on commit e2a0297

Please sign in to comment.