I need to iterate over lines in a string, but keep the newlines at the end in the strings that are yielded.
There is str.lines(), but the strings it returns have the
The solution I currently have looks like this:
/// Iterator yielding every line in a string. The line includes newline character(s).
pub struct LinesWithEndings<'a> {
input: &'a str,
}
impl<'a> LinesWithEndings<'a> {
pub fn from(input: &'a str) -> LinesWithEndings<'a> {
LinesWithEndings {
input: input,
}
}
}
impl<'a> Iterator for LinesWithEndings<'a> {
type Item = &'a str;
#[inline]
fn next(&mut self) -> Option<&'a str> {
if self.input.is_empty() {
return None;
}
let split = self.input.find('\n').map(|i| i + 1).unwrap_or(self.input.len());
let (line, rest) = self.input.split_at(split);
self.input = rest;
Some(line)
}
}