Skip to content

Commit 5a09362

Browse files
committed
Wrote a custom iterator to convert CRLF to LF
1 parent 8a988f2 commit 5a09362

File tree

1 file changed

+34
-2
lines changed

1 file changed

+34
-2
lines changed

tests/system.rs

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@ extern crate term;
1717
use std::collections::HashMap;
1818
use std::fs;
1919
use std::io::{self, BufRead, BufReader, Read};
20+
use std::iter::Peekable;
2021
use std::path::{Path, PathBuf};
22+
use std::str::Bytes;
2123

2224
use rustfmt::*;
2325
use rustfmt::filemap::{write_system_newlines, FileMap};
@@ -369,8 +371,8 @@ fn handle_result(
369371
let read_error = format!("Failed reading target {:?}", &target);
370372
f.read_to_string(&mut text).expect(&read_error);
371373

372-
// Compare line by line, for Windows machines using CRLF newline.
373-
if fmt_text.replace("\r\n", "\n") != text.replace("\r\n", "\n") {
374+
// Ignore LF and CRLF difference for Windows.
375+
if !string_eq_ignore_newline_repr(&fmt_text, &text) {
374376
let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
375377
assert!(
376378
!diff.is_empty(),
@@ -431,3 +433,33 @@ fn rustfmt_diff_no_diff_test() {
431433
let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
432434
assert_eq!(diff, vec![]);
433435
}
436+
437+
// Compare strings without distinguishing between CRLF and LF
438+
fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool {
439+
let left = BytesIgnoreNewlineRepr(left.bytes().peekable());
440+
let right = BytesIgnoreNewlineRepr(right.bytes().peekable());
441+
left.eq(right)
442+
}
443+
444+
struct BytesIgnoreNewlineRepr<'a>(Peekable<Bytes<'a>>);
445+
446+
impl<'a> Iterator for BytesIgnoreNewlineRepr<'a> {
447+
type Item = u8;
448+
fn next(&mut self) -> Option<u8> {
449+
self.0.next().map(|c| if c == b'\r' {
450+
if *self.0.peek().unwrap_or(&0) == b'\n' {
451+
self.0.next();
452+
b'\n'
453+
} else {
454+
b'\r'
455+
}
456+
} else {
457+
c
458+
})
459+
}
460+
}
461+
462+
#[test]
463+
fn string_eq_ignore_newline_repr_test() {
464+
assert!(string_eq_ignore_newline_repr("a\nb\nc\rd", "a\nb\r\nc\rd"));
465+
}

0 commit comments

Comments
 (0)