@@ -765,12 +765,19 @@ where
765765 Opt : Into < Options < ' a > > ,
766766{
767767 let mut new_options = new_width_or_options. into ( ) ;
768- let trimmed = filled_text. trim_end_matches ( new_options. line_ending . as_str ( ) ) ;
769- let ( text, options) = unfill ( trimmed) ;
768+ let ( text, options) = unfill ( filled_text) ;
769+ // The original line ending is kept by `unfill`.
770+ let stripped = text. strip_suffix ( options. line_ending . as_str ( ) ) ;
771+ let new_line_ending = new_options. line_ending . as_str ( ) ;
772+
770773 new_options. initial_indent = options. initial_indent ;
771774 new_options. subsequent_indent = options. subsequent_indent ;
772- let mut refilled = fill ( & text, new_options) ;
773- refilled. push_str ( & filled_text[ trimmed. len ( ) ..] ) ;
775+ let mut refilled = fill ( stripped. unwrap_or ( & text) , new_options) ;
776+
777+ // Add back right line ending if we stripped one off above.
778+ if stripped. is_some ( ) {
779+ refilled. push_str ( new_line_ending) ;
780+ }
774781 refilled
775782}
776783
@@ -1883,11 +1890,26 @@ mod tests {
18831890 }
18841891
18851892 #[ test]
1886- fn refill_convert_crlf ( ) {
1887- assert_eq ! (
1888- refill( "foo\n bar\n " , Options :: new( 5 ) . line_ending( LineEnding :: CRLF ) ) ,
1889- "foo\r \n bar\n " ,
1890- ) ;
1893+ fn refill_convert_lf_to_crlf ( ) {
1894+ let options = Options :: new ( 5 ) . line_ending ( LineEnding :: CRLF ) ;
1895+ assert_eq ! ( refill( "foo\n bar\n " , options) , "foo\r \n bar\r \n " , ) ;
1896+ }
1897+
1898+ #[ test]
1899+ fn refill_convert_crlf_to_lf ( ) {
1900+ let options = Options :: new ( 5 ) . line_ending ( LineEnding :: LF ) ;
1901+ assert_eq ! ( refill( "foo\r \n bar\r \n " , options) , "foo\n bar\n " , ) ;
1902+ }
1903+
1904+ #[ test]
1905+ fn refill_convert_mixed_newlines ( ) {
1906+ let options = Options :: new ( 5 ) . line_ending ( LineEnding :: CRLF ) ;
1907+ assert_eq ! ( refill( "foo\r \n bar\n " , options) , "foo\r \n bar\r \n " , ) ;
1908+ }
1909+
1910+ #[ test]
1911+ fn refill_defaults_to_lf ( ) {
1912+ assert_eq ! ( refill( "foo bar baz" , 5 ) , "foo\n bar\n baz" ) ;
18911913 }
18921914
18931915 #[ test]
0 commit comments