From 48615a68fb01d09749a5b73816d45e0d0669d1f9 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Wed, 26 Aug 2015 17:30:45 -0700 Subject: std: Account for CRLF in {str, BufRead}::lines This commit is an implementation of [RFC 1212][rfc] which tweaks the behavior of the `str::lines` and `BufRead::lines` iterators. Both iterators now account for `\r\n` sequences in addition to `\n`, allowing for less surprising behavior across platforms (especially in the `BufRead` case). Splitting *only* on the `\n` character can still be achieved with `split('\n')` in both cases. The `str::lines_any` function is also now deprecated as `str::lines` is a drop-in replacement for it. [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1212-line-endings.md Closes #28032 --- src/libstd/io/mod.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 72a74c23dc8..54869807cac 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -1439,7 +1439,7 @@ pub trait BufRead: Read { /// /// The iterator returned from this function will yield instances of /// `io::Result`. Each string returned will *not* have a newline - /// byte (the 0xA byte) at the end. + /// byte (the 0xA byte) or CRLF (0xD, 0xA bytes) at the end. /// /// # Examples /// @@ -1763,6 +1763,9 @@ impl Iterator for Lines { Ok(_n) => { if buf.ends_with("\n") { buf.pop(); + if buf.ends_with("\r") { + buf.pop(); + } } Some(Ok(buf)) } @@ -1834,12 +1837,12 @@ mod tests { #[test] fn lines() { - let buf = Cursor::new(&b"12"[..]); + let buf = Cursor::new(&b"12\r"[..]); let mut s = buf.lines(); - assert_eq!(s.next().unwrap().unwrap(), "12".to_string()); + assert_eq!(s.next().unwrap().unwrap(), "12\r".to_string()); assert!(s.next().is_none()); - let buf = Cursor::new(&b"12\n\n"[..]); + let buf = Cursor::new(&b"12\r\n\n"[..]); let mut s = buf.lines(); assert_eq!(s.next().unwrap().unwrap(), "12".to_string()); assert_eq!(s.next().unwrap().unwrap(), "".to_string()); -- cgit 1.4.1-3-g733a5