Module nom::consumer
[−]
[src]
Data consumers
The goal of data producers is to parse data depending on the previous result. It can be used to selectively seek in a file.
Example
This consumer will take 4 samples from the input, print them, then stop
use nom::{IResult,Needed,MemProducer,Consumer,ConsumerState}; use std::str; struct TestPrintConsumer { counter: usize } impl TestPrintConsumer { fn new() -> TestPrintConsumer { TestPrintConsumer { counter: 0 } } } fn take4(i:&[u8]) -> IResult<&[u8], &[u8]>{ if i.len() < 4 { IResult::Incomplete(Needed::Size(4)) } else { IResult::Done(&i[4..],&i[0..4]) } } // Return ConsumerState::Await if it needs more data, or ConsumerDone when it ends impl Consumer for TestPrintConsumer { fn consume(&mut self, input: &[u8]) -> ConsumerState { match take4(input) { IResult::Error(a) => ConsumerState::ConsumerError(0), IResult::Incomplete(a) => ConsumerState::Await(0, 4), IResult::Done(i, o) => { println!("{} -> {}", self.counter, str::from_utf8(o).unwrap()); self.counter = self.counter + 1; if self.counter <= 4 { ConsumerState::Await(4, 4) } else { ConsumerState::ConsumerDone } } } } fn end(&mut self) { println!("finished"); } } // It can consume data directly from a producer let mut p = MemProducer::new(b"abcdefghijklmnopqrstuvwx", 4); let mut c = TestPrintConsumer::new(); c.run(&mut p);
Enums
ConsumerState |
Holds the current state of the consumer |
Traits
Consumer |
Implement the consume method, taking a byte array as input and returning a consumer state |