[][src]Trait omnom::BufReadExt

pub trait BufReadExt: BufRead {
    fn read_while<P>(
        &mut self,
        buf: &mut Vec<u8>,
        predicate: P
    ) -> Result<usize>
    where
        P: FnMut(u8) -> bool
, { ... }
fn skip(&mut self, n: usize) -> Result<()> { ... }
fn skip_while<P>(&mut self, predicate: P) -> Result<usize>
    where
        P: FnMut(u8) -> bool
, { ... }
fn skip_until(&mut self, byte: u8) -> Result<usize> { ... } }

Extend BufRead with methods for streaming parsing.

Provided methods

fn read_while<P>(&mut self, buf: &mut Vec<u8>, predicate: P) -> Result<usize> where
    P: FnMut(u8) -> bool

Read bytes based on a predicate.

read_while takes a predicate as an argument. It will call this on each byte, and copy it to the slice if the predicate evaluates to true. Returns the amount of bytes read.

Errors

If this function encounters an error of the kind ErrorKind::Interrupted then the error is ignored and the operation will continue.

If any other read error is encountered then this function immediately returns. Any bytes which have already been read will be appended to buf.

Examples

[std::io::Cursor][Cursor] is a type that implements BufRead. In this example, we use [Cursor] to read bytes in a byte slice until we encounter a hyphen:

use std::io::{self, BufRead};
use omnom::prelude::*;

let mut cursor = io::Cursor::new(b"lorem-ipsum");
let mut buf = vec![];

let num_bytes = cursor.read_while(&mut buf, |b| b != b'-')
    .expect("reading from cursor won't fail");
assert_eq!(buf, b"lorem");

fn skip(&mut self, n: usize) -> Result<()>

Skip the first n bytes.

fn skip_while<P>(&mut self, predicate: P) -> Result<usize> where
    P: FnMut(u8) -> bool

Skip bytes while the predicate is true.

fn skip_until(&mut self, byte: u8) -> Result<usize>

Skip bytes until the delimiter byte or EOF is reached.

This function will read bytes from the underlying stream until the delimiter or EOF is found. Once found, all bytes up to, and including, the delimiter (if found) will be skipped.

If successful, this function will return the total number of bytes read.

Errors

This function will ignore all instances of ErrorKind::Interrupted and will otherwise return any errors returned by BufRead::fill_buf.

If an I/O error is encountered then all bytes read so far will be present in buf and its length will have been adjusted appropriately.

Examples

std::io::Cursor is a type that implements BufRead. In this example, we use Cursor to read all the bytes in a byte slice in hyphen delimited segments:

use std::io::{self, BufRead, Read};
use omnom::prelude::*;

let mut cursor = io::Cursor::new(b"lorem-ipsum");

// skip up to and including '-'
let num_bytes = cursor.skip_until(b'-').unwrap();
assert_eq!(num_bytes, 6);

// read the rest of the bytes
let mut buf = [0; 5];
cursor.read_exact(&mut buf).unwrap();
assert_eq!(&buf, b"ipsum");
Loading content...

Implementors

impl<T: BufRead> BufReadExt for T[src]

Loading content...