@@ -19,6 +19,7 @@ fn main() -> io::Result<ExitCode> {
1919}
2020
2121/// Strip trailing whitespace. This also magically fixes \r\n endings.
22+ /// Returns true if the contents were modified.
2223fn strip_trailing_whitespace ( contents : & mut Vec < u8 > ) -> bool {
2324 let mut modified = false ;
2425
@@ -37,17 +38,18 @@ fn strip_trailing_whitespace(contents: &mut Vec<u8>) -> bool {
3738 modified
3839}
3940
40- /// Ensure exactly two newlines at the end of the file. Trailing whitespace
41+ /// Ensure exactly one newline at the end of the file. Trailing whitespace
4142/// after the newlines should already have been stripped.
43+ /// Returns true if the contents were modified.
4244fn ensure_newline_at_end ( contents : & mut Vec < u8 > ) -> bool {
43- let orig_len = contents. len ( ) ;
44- let orig_ends_width = contents. ends_with ( b"\n \n " ) ;
45+ let original_len = contents. len ( ) ;
4546
46- contents. truncate ( contents. trim_ascii_end ( ) . len ( ) ) ;
47- contents. push ( b'\n' ) ;
47+ while contents. ends_with ( b"\n " ) {
48+ contents. pop ( ) ;
49+ }
4850 contents. push ( b'\n' ) ;
4951
50- contents. len ( ) != orig_len || !orig_ends_width
52+ contents. len ( ) != original_len
5153}
5254
5355/// Like `retain`, but in reverse. Based on `retain` before it was optimised
@@ -87,19 +89,19 @@ mod test {
8789
8890 #[ test]
8991 fn test_ensure_newline_at_end ( ) {
90- let mut contents = b"\n hello there\n \n world\n \n " . to_vec ( ) ;
92+ let mut contents = b"\n hello there\n \n world\n " . to_vec ( ) ;
9193 let modified = ensure_newline_at_end ( & mut contents) ;
9294 assert_eq ! ( modified, false ) ;
93- assert_eq ! ( contents, b"\n hello there\n \n world\n \n " ) ;
95+ assert_eq ! ( contents, b"\n hello there\n \n world\n " ) ;
9496
9597 let mut contents = b"\n hello there\n \n world" . to_vec ( ) ;
9698 let modified = ensure_newline_at_end ( & mut contents) ;
9799 assert_eq ! ( modified, true ) ;
98- assert_eq ! ( contents, b"\n hello there\n \n world\n \n " ) ;
100+ assert_eq ! ( contents, b"\n hello there\n \n world\n " ) ;
99101
100- let mut contents = b"\n hello there\n \n world\n " . to_vec ( ) ;
102+ let mut contents = b"\n hello there\n \n world\n \n " . to_vec ( ) ;
101103 let modified = ensure_newline_at_end ( & mut contents) ;
102104 assert_eq ! ( modified, true ) ;
103- assert_eq ! ( contents, b"\n hello there\n \n world\n \n " ) ;
105+ assert_eq ! ( contents, b"\n hello there\n \n world\n " ) ;
104106 }
105107}
0 commit comments