Skip to content

Commit

Permalink
Add a for_each convenience function
Browse files Browse the repository at this point in the history
  • Loading branch information
Freaky committed Jan 5, 2019
1 parent 38f58d0 commit fa8cb22
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
`LineReader` is a byte-delimiter-focused buffered reader for Rust, meant as a
faster, less error-prone alternative to `BufRead::read_until`.

It provides two main functions:
It provides three main functions:


### `next_line()`
Expand All @@ -28,6 +28,13 @@ Behaves identically to `next_line()`, except it returns a slice of *all* the
complete lines in the buffer.


### `for_each()`

Calls a closure on each line of the input, while the closure returns true and
no IO errors are detected. Such errors terminate iteration and are returned
from the function.


## Example

```rust
Expand Down
37 changes: 37 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,29 @@ impl<R: io::Read> LineReader<R> {
}
}

/// Run the given closure for each line while the closure returns true.
///
/// ```no_run
/// # use linereader::LineReader;
/// # use std::fs::File;
/// # use std::io;
/// # fn solve(x: &[u8]) { }
/// # fn x() -> io::Result<()> {
/// # let mut reader = LineReader::new(File::open("myfile.txt")?);
/// reader.for_each(|line| { if line.len() == 42 { solve(line); true } else { false } })?;
/// # Ok(())
/// # }
/// ```
pub fn for_each<F: FnMut(&[u8]) -> bool>(&mut self, mut f: F) -> io::Result<()> {
while let Some(line) = self.next_line() {
if !f(line?) {
break;
}
}

Ok(())
}

/// Get the next line from the reader, an IO error, or `None` on EOF. The delimiter
/// is included in any returned slice, unless the file ends without one or a line was
/// truncated to the buffer size due to length.
Expand Down Expand Up @@ -314,6 +337,20 @@ mod tests {
assert_eq!(b"7hhhhhh7", reader.next_batch().unwrap().unwrap());
}

#[test]
fn test_for_each() {
let buf: &[u8] = b"f\nba\nbaz\n";
let mut reader = LineReader::new(buf);

let mut len = 2;
reader.for_each(|l| { assert_eq!(len, l.len()); len += 1; true }).unwrap();

let buf: &[u8] = b"f\nba\nbaz\n";
let mut reader = LineReader::new(buf);

reader.for_each(|l| { assert_eq!(l.len(), 2); false }).unwrap();
}

extern crate rand;
use std::io::BufRead;
use std::io::{Cursor, Read};
Expand Down

0 comments on commit fa8cb22

Please sign in to comment.