Skip to content

Commit d346dfd

Browse files
committed
str::lines and BufRead::lines: document trailing bare cr behaviour
Apropos discussion here rust-lang#91047 (comment) Sadly, str::lines gets this wrong. I think it is probably too late to fix this, so document it instead.
1 parent 18fa434 commit d346dfd

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

library/core/src/str/mod.rs

+13
Original file line numberDiff line numberDiff line change
@@ -899,6 +899,19 @@ impl str {
899899
///
900900
/// assert_eq!(None, lines.next());
901901
/// ```
902+
///
903+
/// Handling of a trailing bare CR is, sadly, anomalous:
904+
/// (`std::io::BufRead::lines` handles this case correctly.)
905+
///
906+
/// ```
907+
/// let text = "foo\nbar\r";
908+
/// let mut lines = text.lines();
909+
///
910+
/// assert_eq!(Some("foo"), lines.next());
911+
/// assert_eq!(Some("bar"), lines.next()); // should really return "bar\r"
912+
///
913+
/// assert_eq!(None, lines.next());
914+
/// ```
902915
#[stable(feature = "rust1", since = "1.0.0")]
903916
#[inline]
904917
pub fn lines(&self) -> Lines<'_> {

library/std/src/io/mod.rs

+13
Original file line numberDiff line numberDiff line change
@@ -2281,6 +2281,19 @@ pub trait BufRead: Read {
22812281
/// assert_eq!(lines_iter.next(), None);
22822282
/// ```
22832283
///
2284+
/// Unlike [`str::lines`], trailing bare CR is handled correctly:
2285+
///
2286+
/// ```
2287+
/// use std::io::{self, BufRead};
2288+
///
2289+
/// let cursor = io::Cursor::new(b"lorem\nipsum\r");
2290+
///
2291+
/// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
2292+
/// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
2293+
/// assert_eq!(lines_iter.next(), Some(String::from("ipsum\r"))); // bare CR is not a newline
2294+
/// assert_eq!(lines_iter.next(), None);
2295+
/// ```
2296+
///
22842297
/// # Errors
22852298
///
22862299
/// Each line of the iterator has the same error semantics as [`BufRead::read_line`].

0 commit comments

Comments
 (0)